litedbmodel-gen 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -49
- package/cli-contract.yaml +420 -6
- package/dist/chunk-2H7UOFLK.js +11 -0
- package/dist/chunk-2H7UOFLK.js.map +1 -0
- package/dist/cli.js +559 -20
- package/dist/cli.js.map +1 -1
- package/dist/dsl-4DLYIQ4T.js +14842 -0
- package/dist/dsl-4DLYIQ4T.js.map +1 -0
- package/docs/cli-reference.md +171 -5
- package/package.json +30 -4
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import "./chunk-2H7UOFLK.js";
|
|
2
3
|
|
|
3
4
|
// src/cli.ts
|
|
4
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from "fs";
|
|
5
|
-
import { resolve, dirname, join } from "path";
|
|
5
|
+
import { readFileSync, writeFileSync as writeFileSync3, existsSync as existsSync2, mkdirSync, copyFileSync } from "fs";
|
|
6
|
+
import { resolve as resolve3, dirname, join } from "path";
|
|
6
7
|
import { fileURLToPath } from "url";
|
|
7
8
|
import { createRequire } from "module";
|
|
8
|
-
import
|
|
9
|
+
import yaml2 from "js-yaml";
|
|
9
10
|
|
|
10
11
|
// src/generated/program.ts
|
|
11
12
|
import { Command } from "commander";
|
|
@@ -15,9 +16,519 @@ function createProgram(handlers2, version) {
|
|
|
15
16
|
program.command("init").description("Set up litedbmodel-gen in an embedoc project.").argument("[config]", "Path to embedoc.config.yaml. Defaults to embedoc.config.yaml in the current directory.").action(async (config, opts, cmd) => {
|
|
16
17
|
await handlers2.init(config, {}, cmd.optsWithGlobals());
|
|
17
18
|
});
|
|
19
|
+
program.command("audit").description("Audit litedbmodel usage code for common anti-patterns.").argument("[target]", "File or directory path to audit. Defaults to the current working directory.").option("--adapter <value>", "LLM adapter to use for the audit.", "mock").option("--model <value>", "Model name override for the selected adapter.").option("--dry-run", "Output the constructed prompt without calling the LLM.", false).option("--fail-on <value>", "Minimum finding severity that causes exit code 10. Findings below this threshold are still reported.", "error").option("-o, --output <value>", "Write the report to a file instead of stdout.").option("--report-format <value>", "Output format for the audit report.", "json").option("--show-prompt", "Output the constructed prompt without calling the LLM API.", false).action(async (target, opts, cmd) => {
|
|
20
|
+
if (opts.showPrompt) {
|
|
21
|
+
const prompt = await handlers2.audit(target, opts, cmd.optsWithGlobals());
|
|
22
|
+
if (typeof prompt === "string") process.stdout.write(prompt + "\n");
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
await handlers2.audit(target, opts, cmd.optsWithGlobals());
|
|
26
|
+
});
|
|
27
|
+
program.command("implement").description("Implement a feature using litedbmodel best practices.").argument("<description>", "Natural-language description of the feature to implement. Should specify the function name, target file, and business logic.").option("-t, --target <value>", "Target source file(s) to create or edit. The agent reads these files to understand existing code and writes the implementation to them.").option("--models <value>", "Glob pattern for model definition files. The agent reads these to understand available models, columns, and relations.", "models/**/*.ts").option("--adapter <value>", "LLM adapter to use for code generation.", "mock").option("--model <value>", "Model name override for the selected adapter.").option("--dry-run", "Output the constructed prompt without calling the LLM.", false).option("--fail-on <value>", "Minimum finding severity that causes exit code 10. Design concerns (info/warning) are still reported at exit 0.", "error").option("-o, --output <value>", "Write the report to a file instead of stdout.").option("--report-format <value>", "Output format for the implementation report.", "json").option("--show-prompt", "Output the constructed prompt without calling the LLM API.", false).action(async (description, opts, cmd) => {
|
|
28
|
+
if (opts.showPrompt) {
|
|
29
|
+
const prompt = await handlers2.implement(description, opts, cmd.optsWithGlobals());
|
|
30
|
+
if (typeof prompt === "string") process.stdout.write(prompt + "\n");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
await handlers2.implement(description, opts, cmd.optsWithGlobals());
|
|
34
|
+
});
|
|
18
35
|
return program;
|
|
19
36
|
}
|
|
20
37
|
|
|
38
|
+
// src/commands/audit.ts
|
|
39
|
+
import { existsSync, writeFileSync } from "fs";
|
|
40
|
+
import { resolve } from "path";
|
|
41
|
+
|
|
42
|
+
// src/agents/context-builder.ts
|
|
43
|
+
function buildAuditContext(input) {
|
|
44
|
+
return [
|
|
45
|
+
"# litedbmodel Code Audit Request",
|
|
46
|
+
`## Target
|
|
47
|
+
|
|
48
|
+
Read all TypeScript source files at \`${input.targetPath}\` using your file tools. Find every file that imports or uses litedbmodel models, and audit each usage against the eight anti-pattern categories defined in your instructions.`
|
|
49
|
+
].join("\n\n");
|
|
50
|
+
}
|
|
51
|
+
function buildImplementContext(input) {
|
|
52
|
+
const lines = [];
|
|
53
|
+
lines.push("# litedbmodel Implementation Request");
|
|
54
|
+
lines.push("");
|
|
55
|
+
lines.push(`## Feature Description
|
|
56
|
+
|
|
57
|
+
${input.description}`);
|
|
58
|
+
lines.push("");
|
|
59
|
+
lines.push("## Parameters");
|
|
60
|
+
lines.push("");
|
|
61
|
+
lines.push(`- **Models glob**: \`${input.modelsGlob}\``);
|
|
62
|
+
if (input.targetPath) {
|
|
63
|
+
lines.push(`- **Target file**: \`${input.targetPath}\``);
|
|
64
|
+
}
|
|
65
|
+
return lines.join("\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/agents/orchestrator.ts
|
|
69
|
+
var EXIT_RUNTIME_MISSING = 11;
|
|
70
|
+
var EXIT_ADAPTER_ERROR = 12;
|
|
71
|
+
var PKG = "agent-contracts-runtime";
|
|
72
|
+
async function createAdapter(adapterName, config) {
|
|
73
|
+
const name = adapterName.toLowerCase();
|
|
74
|
+
try {
|
|
75
|
+
switch (name) {
|
|
76
|
+
case "mock": {
|
|
77
|
+
const m = await import(`${PKG}/adapters/mock`);
|
|
78
|
+
return new m.MockAdapter({
|
|
79
|
+
defaultLatencyMs: 0,
|
|
80
|
+
responses: config.mockResponses ?? {}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
case "cursor": {
|
|
84
|
+
const m = await import(`${PKG}/adapters/cursor-sdk`);
|
|
85
|
+
const apiKey = process.env["CURSOR_API_KEY"];
|
|
86
|
+
return m.CursorSdkAdapter.create({
|
|
87
|
+
apiKey,
|
|
88
|
+
...config.model ? { model: config.model } : {},
|
|
89
|
+
...config.cwd ? { cwd: config.cwd } : {}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
case "claude": {
|
|
93
|
+
const m = await import(`${PKG}/adapters/claude-agent-sdk`);
|
|
94
|
+
return new m.ClaudeAgentSdkAdapter({
|
|
95
|
+
...config.model ? { model: config.model } : {},
|
|
96
|
+
...config.cwd ? { cwd: config.cwd } : {}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
case "openai": {
|
|
100
|
+
const m = await import(`${PKG}/adapters/openai-agents-sdk`);
|
|
101
|
+
return new m.OpenAIAgentsSdkAdapter({
|
|
102
|
+
...config.model ? { model: config.model } : {}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
case "gemini": {
|
|
106
|
+
const m = await import(`${PKG}/adapters/gemini-sdk`);
|
|
107
|
+
return new m.GeminiSdkAdapter({
|
|
108
|
+
apiKey: process.env["GEMINI_API_KEY"],
|
|
109
|
+
...config.model ? { model: config.model } : {}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
default:
|
|
113
|
+
throw Object.assign(
|
|
114
|
+
new Error(`Unknown adapter: "${adapterName}". Valid values: mock, cursor, claude, openai, gemini`),
|
|
115
|
+
{ exitCode: EXIT_ADAPTER_ERROR }
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
} catch (err) {
|
|
119
|
+
const e = err;
|
|
120
|
+
if (e.exitCode === EXIT_ADAPTER_ERROR) throw err;
|
|
121
|
+
throw Object.assign(
|
|
122
|
+
new Error(
|
|
123
|
+
`Failed to initialise adapter "${adapterName}": ${e.message ?? String(err)}. Ensure the SDK package is installed and the required API key is set.`
|
|
124
|
+
),
|
|
125
|
+
{ exitCode: EXIT_ADAPTER_ERROR }
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function loadRegistries() {
|
|
130
|
+
try {
|
|
131
|
+
const dsl = await import("./dsl-4DLYIQ4T.js");
|
|
132
|
+
return {
|
|
133
|
+
agentRegistry: dsl.agentRegistry ?? {},
|
|
134
|
+
taskRegistry: dsl.taskRegistry ?? {},
|
|
135
|
+
handoffSchemas: dsl.handoffSchemas ?? {},
|
|
136
|
+
workflowRegistry: dsl.workflowRegistry ?? {}
|
|
137
|
+
};
|
|
138
|
+
} catch (err) {
|
|
139
|
+
const msg = err.message ?? String(err);
|
|
140
|
+
process.stderr.write(
|
|
141
|
+
`[litedbmodel-gen] warning: generated DSL registries could not be loaded \u2014 running without schema contracts. Run: npx agent-runtime generate
|
|
142
|
+
Cause: ${msg}
|
|
143
|
+
`
|
|
144
|
+
);
|
|
145
|
+
return { agentRegistry: {}, taskRegistry: {}, handoffSchemas: {}, workflowRegistry: {} };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async function runAgentTask(userRequest, taskId, config, options) {
|
|
149
|
+
let runTask;
|
|
150
|
+
let buildTaskPrompt;
|
|
151
|
+
try {
|
|
152
|
+
const rt = await import(PKG);
|
|
153
|
+
runTask = rt.runTask;
|
|
154
|
+
buildTaskPrompt = rt.buildTaskPrompt;
|
|
155
|
+
} catch {
|
|
156
|
+
throw Object.assign(
|
|
157
|
+
new Error(
|
|
158
|
+
"agent-contracts-runtime is not installed. Run: npm install --save-dev agent-contracts-runtime"
|
|
159
|
+
),
|
|
160
|
+
{ exitCode: EXIT_RUNTIME_MISSING }
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const registries = await loadRegistries();
|
|
164
|
+
if (options.dryRun) {
|
|
165
|
+
const task = registries.taskRegistry[taskId];
|
|
166
|
+
const targetAgent = task?.target_agent;
|
|
167
|
+
const agent = targetAgent ? registries.agentRegistry[targetAgent] : void 0;
|
|
168
|
+
if (!task || !agent) {
|
|
169
|
+
throw Object.assign(
|
|
170
|
+
new Error(
|
|
171
|
+
`DSL registry missing task "${taskId}" or its target agent. Run: npx agent-runtime generate`
|
|
172
|
+
),
|
|
173
|
+
{ exitCode: 1 }
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
const fullPrompt = buildTaskPrompt(
|
|
177
|
+
agent,
|
|
178
|
+
task,
|
|
179
|
+
{ user_request: userRequest },
|
|
180
|
+
{ handoffSchemas: registries.handoffSchemas }
|
|
181
|
+
);
|
|
182
|
+
return {
|
|
183
|
+
taskId,
|
|
184
|
+
data: null,
|
|
185
|
+
raw: "",
|
|
186
|
+
prompt: fullPrompt,
|
|
187
|
+
dryRun: true,
|
|
188
|
+
status: "success",
|
|
189
|
+
followUpsUsed: 0,
|
|
190
|
+
retriesUsed: 0
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
const adapter = await createAdapter(config.adapter ?? "mock", config);
|
|
194
|
+
const result = await runTask(
|
|
195
|
+
adapter,
|
|
196
|
+
taskId,
|
|
197
|
+
{ user_request: userRequest },
|
|
198
|
+
{
|
|
199
|
+
maxFollowUps: 3,
|
|
200
|
+
maxRetries: 1,
|
|
201
|
+
...registries
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
const { outcome, follow_ups_used, retries_used } = result;
|
|
205
|
+
if (outcome.data !== void 0) {
|
|
206
|
+
return {
|
|
207
|
+
taskId,
|
|
208
|
+
data: outcome.data,
|
|
209
|
+
raw: outcome.raw ?? "",
|
|
210
|
+
prompt: userRequest,
|
|
211
|
+
dryRun: false,
|
|
212
|
+
status: "success",
|
|
213
|
+
followUpsUsed: follow_ups_used,
|
|
214
|
+
retriesUsed: retries_used
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
if (Array.isArray(outcome.errors)) {
|
|
218
|
+
return {
|
|
219
|
+
taskId,
|
|
220
|
+
data: null,
|
|
221
|
+
raw: outcome.raw ?? "",
|
|
222
|
+
prompt: userRequest,
|
|
223
|
+
dryRun: false,
|
|
224
|
+
status: "validation_error",
|
|
225
|
+
errorMessage: outcome.errors.join("; "),
|
|
226
|
+
followUpsUsed: follow_ups_used,
|
|
227
|
+
retriesUsed: retries_used
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (typeof outcome.reason === "string") {
|
|
231
|
+
return {
|
|
232
|
+
taskId,
|
|
233
|
+
data: null,
|
|
234
|
+
raw: outcome.raw ?? "",
|
|
235
|
+
prompt: userRequest,
|
|
236
|
+
dryRun: false,
|
|
237
|
+
status: "escalation",
|
|
238
|
+
errorMessage: outcome.reason,
|
|
239
|
+
followUpsUsed: follow_ups_used,
|
|
240
|
+
retriesUsed: retries_used
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
taskId,
|
|
245
|
+
data: null,
|
|
246
|
+
raw: "",
|
|
247
|
+
prompt: userRequest,
|
|
248
|
+
dryRun: false,
|
|
249
|
+
status: "error",
|
|
250
|
+
errorMessage: typeof outcome.message === "string" ? outcome.message : "Unknown agent error",
|
|
251
|
+
followUpsUsed: follow_ups_used,
|
|
252
|
+
retriesUsed: retries_used
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/agents/formatter.ts
|
|
257
|
+
import yaml from "js-yaml";
|
|
258
|
+
var SEVERITY_ORDER = ["info", "warning", "error", "critical"];
|
|
259
|
+
function severityIndex(s) {
|
|
260
|
+
const idx = SEVERITY_ORDER.indexOf(s);
|
|
261
|
+
return idx === -1 ? 0 : idx;
|
|
262
|
+
}
|
|
263
|
+
function computeExitCode(result, options) {
|
|
264
|
+
if (result.dryRun) return 0;
|
|
265
|
+
if (result.status === "error" || result.status === "escalation" || result.status === "validation_error") {
|
|
266
|
+
return 1;
|
|
267
|
+
}
|
|
268
|
+
if (result.status !== "success" || !result.data) return 1;
|
|
269
|
+
const threshold = severityIndex(options.failOn ?? "error");
|
|
270
|
+
const hasBlocking = result.data.findings.some(
|
|
271
|
+
(f) => severityIndex(f.severity) >= threshold
|
|
272
|
+
);
|
|
273
|
+
return hasBlocking ? 10 : 0;
|
|
274
|
+
}
|
|
275
|
+
function severityIcon(severity) {
|
|
276
|
+
switch (severity) {
|
|
277
|
+
case "critical":
|
|
278
|
+
return "\u2716";
|
|
279
|
+
case "error":
|
|
280
|
+
return "\u2716";
|
|
281
|
+
case "warning":
|
|
282
|
+
return "\u26A0";
|
|
283
|
+
case "info":
|
|
284
|
+
return "\u2139";
|
|
285
|
+
default:
|
|
286
|
+
return "\xB7";
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function formatResultText(result) {
|
|
290
|
+
if (result.dryRun) {
|
|
291
|
+
return `[DRY RUN \u2014 prompt only, LLM was not called]
|
|
292
|
+
|
|
293
|
+
${result.prompt}`;
|
|
294
|
+
}
|
|
295
|
+
if (result.status !== "success" || !result.data) {
|
|
296
|
+
return `litedbmodel-gen agent error
|
|
297
|
+
Status : ${result.status}
|
|
298
|
+
Message : ${result.errorMessage ?? "unknown error"}
|
|
299
|
+
`;
|
|
300
|
+
}
|
|
301
|
+
const data = result.data;
|
|
302
|
+
const lines = [];
|
|
303
|
+
lines.push(`Summary : ${data.summary}`);
|
|
304
|
+
lines.push(`Risk level: ${data.riskLevel.toUpperCase()}`);
|
|
305
|
+
if (data.findings.length === 0) {
|
|
306
|
+
lines.push("\n\u2714 No issues found.");
|
|
307
|
+
} else {
|
|
308
|
+
lines.push(`
|
|
309
|
+
Findings (${data.findings.length}):
|
|
310
|
+
`);
|
|
311
|
+
for (const f of data.findings) {
|
|
312
|
+
const icon = severityIcon(f.severity);
|
|
313
|
+
lines.push(` ${icon} [${f.severity.toUpperCase()}] ${f.category}${f.target ? ` \u2014 ${f.target}` : ""}`);
|
|
314
|
+
if (f.location) lines.push(` Location : ${f.location}`);
|
|
315
|
+
lines.push(` Message : ${f.message}`);
|
|
316
|
+
if (f.recommendation) lines.push(` Recommendation: ${f.recommendation}`);
|
|
317
|
+
if (f.confidence !== void 0) {
|
|
318
|
+
lines.push(` Confidence : ${Math.round(f.confidence * 100)}%`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (data.recommendedActions && data.recommendedActions.length > 0) {
|
|
323
|
+
lines.push(`
|
|
324
|
+
Recommended Actions:
|
|
325
|
+
`);
|
|
326
|
+
for (const action of data.recommendedActions) {
|
|
327
|
+
lines.push(` \u2192 [${action.kind}] ${action.title}`);
|
|
328
|
+
if (action.command) lines.push(` $ ${action.command}`);
|
|
329
|
+
if (action.target) lines.push(` Target: ${action.target}`);
|
|
330
|
+
if (action.rationale) lines.push(` ${action.rationale}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (isImplementResult(data)) {
|
|
334
|
+
if (data.changedFiles.length > 0) {
|
|
335
|
+
lines.push(`
|
|
336
|
+
Changed Files (${data.changedFiles.length}):
|
|
337
|
+
`);
|
|
338
|
+
for (const file of data.changedFiles) {
|
|
339
|
+
lines.push(` [${file.action.toUpperCase()}] ${file.path}`);
|
|
340
|
+
if (file.rationale) lines.push(` ${file.rationale}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (data.dependencies && data.dependencies.length > 0) {
|
|
344
|
+
lines.push(`
|
|
345
|
+
Required dependencies:
|
|
346
|
+
npm install ${data.dependencies.join(" ")}`);
|
|
347
|
+
}
|
|
348
|
+
if (data.notes) {
|
|
349
|
+
lines.push(`
|
|
350
|
+
Notes:
|
|
351
|
+
${data.notes}`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (data.metadata) {
|
|
355
|
+
const m = data.metadata;
|
|
356
|
+
lines.push(
|
|
357
|
+
`
|
|
358
|
+
Generated at ${m.generatedAt ?? "\u2014"} by ${m.tool ?? "litedbmodel-gen"} (adapter: ${m.adapter ?? "\u2014"}, model: ${m.model ?? "\u2014"})`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
return lines.join("\n");
|
|
362
|
+
}
|
|
363
|
+
function formatResultJson(result) {
|
|
364
|
+
if (result.dryRun) {
|
|
365
|
+
return JSON.stringify({ dryRun: true, prompt: result.prompt }, null, 2);
|
|
366
|
+
}
|
|
367
|
+
return JSON.stringify(result.data, null, 2);
|
|
368
|
+
}
|
|
369
|
+
function formatResultYaml(result) {
|
|
370
|
+
if (result.dryRun) {
|
|
371
|
+
return yaml.dump({ dryRun: true, prompt: result.prompt });
|
|
372
|
+
}
|
|
373
|
+
return yaml.dump(result.data, { lineWidth: 120 });
|
|
374
|
+
}
|
|
375
|
+
function isImplementResult(data) {
|
|
376
|
+
return data !== null && typeof data === "object" && "changedFiles" in data && Array.isArray(data.changedFiles);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/commands/audit.ts
|
|
380
|
+
async function commandAudit(target, opts) {
|
|
381
|
+
const targetPath = resolve(target ?? ".");
|
|
382
|
+
if (!existsSync(targetPath)) {
|
|
383
|
+
const err = {
|
|
384
|
+
error: "target_not_found",
|
|
385
|
+
message: `Target path not found: ${targetPath}`,
|
|
386
|
+
target: targetPath
|
|
387
|
+
};
|
|
388
|
+
if ((opts.reportFormat ?? "json") === "json") {
|
|
389
|
+
process.stderr.write(JSON.stringify(err, null, 2) + "\n");
|
|
390
|
+
} else {
|
|
391
|
+
process.stderr.write(`Error: target path not found: ${targetPath}
|
|
392
|
+
`);
|
|
393
|
+
}
|
|
394
|
+
process.exit(3);
|
|
395
|
+
}
|
|
396
|
+
const prompt = buildAuditContext({ targetPath });
|
|
397
|
+
const adapterName = opts.adapter ?? "mock";
|
|
398
|
+
const agentConfig = {
|
|
399
|
+
adapter: adapterName,
|
|
400
|
+
model: opts.model,
|
|
401
|
+
cwd: process.cwd(),
|
|
402
|
+
...adapterName === "mock" ? {
|
|
403
|
+
mockResponses: {
|
|
404
|
+
"audit-litedbmodel-usage": () => JSON.stringify({
|
|
405
|
+
summary: "Mock audit completed. No issues found.",
|
|
406
|
+
riskLevel: "low",
|
|
407
|
+
findings: [],
|
|
408
|
+
metadata: { tool: "litedbmodel-gen", command: "audit", adapter: "mock" }
|
|
409
|
+
})
|
|
410
|
+
}
|
|
411
|
+
} : {}
|
|
412
|
+
};
|
|
413
|
+
const agentOpts = {
|
|
414
|
+
dryRun: opts.dryRun ?? false,
|
|
415
|
+
failOn: opts.failOn ?? "error"
|
|
416
|
+
};
|
|
417
|
+
let result;
|
|
418
|
+
try {
|
|
419
|
+
result = await runAgentTask(prompt, "audit-litedbmodel-usage", agentConfig, agentOpts);
|
|
420
|
+
} catch (err) {
|
|
421
|
+
const e = err;
|
|
422
|
+
const exitCode = e.exitCode ?? 1;
|
|
423
|
+
if (exitCode === EXIT_RUNTIME_MISSING || exitCode === EXIT_ADAPTER_ERROR) {
|
|
424
|
+
const payload = { error: "agent_error", exitCode, message: e.message ?? String(err) };
|
|
425
|
+
process.stderr.write(JSON.stringify(payload, null, 2) + "\n");
|
|
426
|
+
process.exit(exitCode);
|
|
427
|
+
}
|
|
428
|
+
process.stderr.write(`Error: ${e.message ?? String(err)}
|
|
429
|
+
`);
|
|
430
|
+
process.exit(1);
|
|
431
|
+
}
|
|
432
|
+
const fmt = opts.reportFormat ?? "json";
|
|
433
|
+
let output;
|
|
434
|
+
if (fmt === "text") {
|
|
435
|
+
output = formatResultText(result);
|
|
436
|
+
} else if (fmt === "yaml") {
|
|
437
|
+
output = formatResultYaml(result);
|
|
438
|
+
} else {
|
|
439
|
+
output = formatResultJson(result);
|
|
440
|
+
}
|
|
441
|
+
if (opts.output) {
|
|
442
|
+
const outPath = resolve(opts.output);
|
|
443
|
+
writeFileSync(outPath, output + "\n", "utf-8");
|
|
444
|
+
process.stderr.write(`Report written to: ${outPath}
|
|
445
|
+
`);
|
|
446
|
+
} else {
|
|
447
|
+
process.stdout.write(output + "\n");
|
|
448
|
+
}
|
|
449
|
+
process.exit(computeExitCode(result, agentOpts));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// src/commands/implement.ts
|
|
453
|
+
import { writeFileSync as writeFileSync2 } from "fs";
|
|
454
|
+
import { resolve as resolve2 } from "path";
|
|
455
|
+
async function commandImplement(description, opts) {
|
|
456
|
+
if (!description || description.trim().length === 0) {
|
|
457
|
+
const err = {
|
|
458
|
+
error: "missing_description",
|
|
459
|
+
message: 'A feature description is required. Example: litedbmodel-gen implement "Sync order items from API"'
|
|
460
|
+
};
|
|
461
|
+
process.stderr.write(JSON.stringify(err, null, 2) + "\n");
|
|
462
|
+
process.exit(3);
|
|
463
|
+
}
|
|
464
|
+
const cwd = process.cwd();
|
|
465
|
+
const prompt = buildImplementContext({
|
|
466
|
+
description: description.trim(),
|
|
467
|
+
modelsGlob: opts.models ?? "models/**/*.ts",
|
|
468
|
+
targetPath: opts.target,
|
|
469
|
+
cwd
|
|
470
|
+
});
|
|
471
|
+
const adapterName = opts.adapter ?? "mock";
|
|
472
|
+
const agentConfig = {
|
|
473
|
+
adapter: adapterName,
|
|
474
|
+
model: opts.model,
|
|
475
|
+
cwd,
|
|
476
|
+
...adapterName === "mock" ? {
|
|
477
|
+
mockResponses: {
|
|
478
|
+
"implement-litedbmodel-feature": () => JSON.stringify({
|
|
479
|
+
summary: "Mock implementation completed.",
|
|
480
|
+
riskLevel: "low",
|
|
481
|
+
findings: [],
|
|
482
|
+
changedFiles: opts.target ? [{ path: opts.target, action: "updated", rationale: "Mock implementation" }] : [],
|
|
483
|
+
metadata: { tool: "litedbmodel-gen", command: "implement", adapter: "mock" }
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
} : {}
|
|
487
|
+
};
|
|
488
|
+
const agentOpts = {
|
|
489
|
+
dryRun: opts.dryRun ?? false,
|
|
490
|
+
failOn: opts.failOn ?? "error"
|
|
491
|
+
};
|
|
492
|
+
let result;
|
|
493
|
+
try {
|
|
494
|
+
result = await runAgentTask(
|
|
495
|
+
prompt,
|
|
496
|
+
"implement-litedbmodel-feature",
|
|
497
|
+
agentConfig,
|
|
498
|
+
agentOpts
|
|
499
|
+
);
|
|
500
|
+
} catch (err) {
|
|
501
|
+
const e = err;
|
|
502
|
+
const exitCode = e.exitCode ?? 1;
|
|
503
|
+
if (exitCode === EXIT_RUNTIME_MISSING || exitCode === EXIT_ADAPTER_ERROR) {
|
|
504
|
+
const payload = { error: "agent_error", exitCode, message: e.message ?? String(err) };
|
|
505
|
+
process.stderr.write(JSON.stringify(payload, null, 2) + "\n");
|
|
506
|
+
process.exit(exitCode);
|
|
507
|
+
}
|
|
508
|
+
process.stderr.write(`Error: ${e.message ?? String(err)}
|
|
509
|
+
`);
|
|
510
|
+
process.exit(1);
|
|
511
|
+
}
|
|
512
|
+
const fmt = opts.reportFormat ?? "json";
|
|
513
|
+
let output;
|
|
514
|
+
if (fmt === "text") {
|
|
515
|
+
output = formatResultText(result);
|
|
516
|
+
} else if (fmt === "yaml") {
|
|
517
|
+
output = formatResultYaml(result);
|
|
518
|
+
} else {
|
|
519
|
+
output = formatResultJson(result);
|
|
520
|
+
}
|
|
521
|
+
if (opts.output) {
|
|
522
|
+
const outPath = resolve2(opts.output);
|
|
523
|
+
writeFileSync2(outPath, output + "\n", "utf-8");
|
|
524
|
+
process.stderr.write(`Report written to: ${outPath}
|
|
525
|
+
`);
|
|
526
|
+
} else {
|
|
527
|
+
process.stdout.write(output + "\n");
|
|
528
|
+
}
|
|
529
|
+
process.exit(computeExitCode(result, agentOpts));
|
|
530
|
+
}
|
|
531
|
+
|
|
21
532
|
// src/cli.ts
|
|
22
533
|
var require2 = createRequire(import.meta.url);
|
|
23
534
|
var pkg = require2("../package.json");
|
|
@@ -26,28 +537,56 @@ var __dirname = dirname(__filename);
|
|
|
26
537
|
function resolveEmbedocDirs(configPath) {
|
|
27
538
|
const configDir = dirname(configPath);
|
|
28
539
|
const raw = readFileSync(configPath, "utf-8");
|
|
29
|
-
const config =
|
|
30
|
-
const renderersDir =
|
|
540
|
+
const config = yaml2.load(raw) ?? {};
|
|
541
|
+
const renderersDir = resolve3(
|
|
31
542
|
configDir,
|
|
32
543
|
config["renderers_dir"] ?? ".embedoc/renderers"
|
|
33
544
|
);
|
|
34
|
-
const datasourcesDir =
|
|
545
|
+
const datasourcesDir = resolve3(
|
|
35
546
|
configDir,
|
|
36
547
|
config["datasources_dir"] ?? ".embedoc/datasources"
|
|
37
548
|
);
|
|
38
|
-
const templatesDir =
|
|
549
|
+
const templatesDir = resolve3(
|
|
39
550
|
configDir,
|
|
40
551
|
config["templates_dir"] ?? ".embedoc/templates"
|
|
41
552
|
);
|
|
42
553
|
return { renderersDir, datasourcesDir, templatesDir };
|
|
43
554
|
}
|
|
44
555
|
var handlers = {
|
|
556
|
+
// ── audit ──────────────────────────────────────────────────────────────────
|
|
557
|
+
audit: async (target, opts) => {
|
|
558
|
+
await commandAudit(target, {
|
|
559
|
+
adapter: opts.adapter,
|
|
560
|
+
model: opts.model,
|
|
561
|
+
dryRun: opts.dryRun,
|
|
562
|
+
failOn: opts.failOn,
|
|
563
|
+
output: opts.output,
|
|
564
|
+
reportFormat: opts.reportFormat
|
|
565
|
+
});
|
|
566
|
+
},
|
|
567
|
+
// ── implement ──────────────────────────────────────────────────────────────
|
|
568
|
+
implement: async (description, opts) => {
|
|
569
|
+
await commandImplement(description, {
|
|
570
|
+
target: opts.target,
|
|
571
|
+
models: opts.models,
|
|
572
|
+
adapter: opts.adapter,
|
|
573
|
+
model: opts.model,
|
|
574
|
+
dryRun: opts.dryRun,
|
|
575
|
+
failOn: opts.failOn,
|
|
576
|
+
output: opts.output,
|
|
577
|
+
reportFormat: opts.reportFormat
|
|
578
|
+
});
|
|
579
|
+
},
|
|
580
|
+
// ── init ───────────────────────────────────────────────────────────────────
|
|
45
581
|
init: async (config) => {
|
|
46
582
|
const configPath = config ?? "embedoc.config.yaml";
|
|
47
|
-
const absConfigPath =
|
|
48
|
-
if (!
|
|
49
|
-
|
|
50
|
-
|
|
583
|
+
const absConfigPath = resolve3(configPath);
|
|
584
|
+
if (!existsSync2(absConfigPath)) {
|
|
585
|
+
process.stderr.write(JSON.stringify({
|
|
586
|
+
error: "config_not_found",
|
|
587
|
+
message: `${configPath} not found. Run "npx embedoc init" first.`
|
|
588
|
+
}, null, 2) + "\n");
|
|
589
|
+
process.exit(3);
|
|
51
590
|
}
|
|
52
591
|
const dirs = resolveEmbedocDirs(absConfigPath);
|
|
53
592
|
console.log("Setting up litedbmodel-gen...\n");
|
|
@@ -64,7 +603,7 @@ var handlers = {
|
|
|
64
603
|
function copyTemplate(templatesDir) {
|
|
65
604
|
mkdirSync(templatesDir, { recursive: true });
|
|
66
605
|
const destPath = join(templatesDir, "model.hbs");
|
|
67
|
-
if (
|
|
606
|
+
if (existsSync2(destPath)) {
|
|
68
607
|
console.log(` skip ${destPath} (already exists)`);
|
|
69
608
|
return;
|
|
70
609
|
}
|
|
@@ -74,17 +613,17 @@ function copyTemplate(templatesDir) {
|
|
|
74
613
|
}
|
|
75
614
|
function resolvePackageTemplate() {
|
|
76
615
|
const candidates = [
|
|
77
|
-
|
|
78
|
-
|
|
616
|
+
resolve3(__dirname, "..", "templates", "model.hbs"),
|
|
617
|
+
resolve3(__dirname, "templates", "model.hbs")
|
|
79
618
|
];
|
|
80
619
|
for (const p of candidates) {
|
|
81
|
-
if (
|
|
620
|
+
if (existsSync2(p)) return p;
|
|
82
621
|
}
|
|
83
622
|
throw new Error("Could not find model.hbs template in package");
|
|
84
623
|
}
|
|
85
624
|
function updateRenderersIndex(renderersDir) {
|
|
86
625
|
const filePath = join(renderersDir, "index.ts");
|
|
87
|
-
if (!
|
|
626
|
+
if (!existsSync2(filePath)) {
|
|
88
627
|
console.error(` warn ${filePath} not found, skipping renderers setup`);
|
|
89
628
|
return;
|
|
90
629
|
}
|
|
@@ -106,12 +645,12 @@ function updateRenderersIndex(renderersDir) {
|
|
|
106
645
|
content = importLine + "\n\n" + content;
|
|
107
646
|
}
|
|
108
647
|
content = insertIntoObject(content, "embeds", entry);
|
|
109
|
-
|
|
648
|
+
writeFileSync3(filePath, content, "utf-8");
|
|
110
649
|
console.log(` update ${filePath}`);
|
|
111
650
|
}
|
|
112
651
|
function updateDatasourcesIndex(datasourcesDir) {
|
|
113
652
|
const filePath = join(datasourcesDir, "index.ts");
|
|
114
|
-
if (!
|
|
653
|
+
if (!existsSync2(filePath)) {
|
|
115
654
|
console.error(` warn ${filePath} not found, skipping datasources setup`);
|
|
116
655
|
return;
|
|
117
656
|
}
|
|
@@ -130,7 +669,7 @@ function updateDatasourcesIndex(datasourcesDir) {
|
|
|
130
669
|
content = importLine + "\n\n" + content;
|
|
131
670
|
}
|
|
132
671
|
content = insertIntoObject(content, "datasourceTypes", entry);
|
|
133
|
-
|
|
672
|
+
writeFileSync3(filePath, content, "utf-8");
|
|
134
673
|
console.log(` update ${filePath}`);
|
|
135
674
|
}
|
|
136
675
|
function insertIntoObject(source, objectName, entry) {
|
|
@@ -181,7 +720,7 @@ function updateConfig(configPath) {
|
|
|
181
720
|
content = content.slice(0, lineEnd + 1) + targetsInsert + "\n" + content.slice(lineEnd + 1);
|
|
182
721
|
}
|
|
183
722
|
}
|
|
184
|
-
|
|
723
|
+
writeFileSync3(configPath, content, "utf-8");
|
|
185
724
|
console.log(" update embedoc.config.yaml");
|
|
186
725
|
}
|
|
187
726
|
createProgram(handlers, pkg.version).parse();
|