sentinelayer-cli 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +62 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +319 -319
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +226 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +493 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/ai/aidenid.js +972 -945
  30. package/src/ai/client.js +508 -508
  31. package/src/ai/domain-target-store.js +268 -268
  32. package/src/ai/identity-store.js +270 -270
  33. package/src/ai/site-store.js +145 -145
  34. package/src/audit/agents/architecture.js +180 -180
  35. package/src/audit/agents/compliance.js +179 -179
  36. package/src/audit/agents/documentation.js +165 -165
  37. package/src/audit/agents/performance.js +145 -145
  38. package/src/audit/agents/security.js +215 -215
  39. package/src/audit/agents/testing.js +172 -172
  40. package/src/audit/orchestrator.js +557 -557
  41. package/src/audit/package.js +204 -204
  42. package/src/audit/registry.js +284 -284
  43. package/src/audit/replay.js +103 -103
  44. package/src/auth/http.js +113 -113
  45. package/src/auth/service.js +891 -848
  46. package/src/auth/session-store.js +359 -345
  47. package/src/cli.js +252 -252
  48. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  49. package/src/commands/ai/provision-governance.js +1272 -1246
  50. package/src/commands/ai/shared.js +147 -147
  51. package/src/commands/ai.js +11 -11
  52. package/src/commands/apply.js +12 -12
  53. package/src/commands/audit.js +1166 -1166
  54. package/src/commands/auth.js +375 -366
  55. package/src/commands/chat.js +191 -191
  56. package/src/commands/config.js +184 -184
  57. package/src/commands/cost.js +311 -311
  58. package/src/commands/daemon/core.js +850 -850
  59. package/src/commands/daemon/extended.js +1048 -1048
  60. package/src/commands/daemon/shared.js +213 -213
  61. package/src/commands/daemon.js +11 -11
  62. package/src/commands/guide.js +174 -174
  63. package/src/commands/ingest.js +58 -58
  64. package/src/commands/init.js +55 -55
  65. package/src/commands/legacy-args.js +10 -10
  66. package/src/commands/mcp.js +461 -404
  67. package/src/commands/omargate.js +15 -15
  68. package/src/commands/persona.js +20 -20
  69. package/src/commands/plugin.js +260 -260
  70. package/src/commands/policy.js +132 -132
  71. package/src/commands/prompt.js +238 -238
  72. package/src/commands/review.js +704 -704
  73. package/src/commands/scan.js +866 -788
  74. package/src/commands/spec.js +716 -716
  75. package/src/commands/swarm.js +651 -651
  76. package/src/commands/telemetry.js +202 -202
  77. package/src/commands/watch.js +510 -510
  78. package/src/config/agent-dictionary.js +182 -182
  79. package/src/config/io.js +56 -56
  80. package/src/config/paths.js +18 -18
  81. package/src/config/schema.js +55 -55
  82. package/src/config/service.js +184 -184
  83. package/src/cost/budget.js +235 -235
  84. package/src/cost/history.js +188 -188
  85. package/src/cost/tracker.js +171 -171
  86. package/src/daemon/artifact-lineage.js +534 -534
  87. package/src/daemon/assignment-ledger.js +770 -770
  88. package/src/daemon/ast-parser-layer.js +258 -258
  89. package/src/daemon/budget-governor.js +633 -633
  90. package/src/daemon/callgraph-overlay.js +646 -646
  91. package/src/daemon/error-worker.js +626 -626
  92. package/src/daemon/hybrid-mapper.js +929 -929
  93. package/src/daemon/jira-lifecycle.js +632 -632
  94. package/src/daemon/operator-control.js +657 -657
  95. package/src/daemon/reliability-lane.js +471 -471
  96. package/src/daemon/watchdog.js +971 -971
  97. package/src/guide/generator.js +316 -316
  98. package/src/ingest/engine.js +918 -918
  99. package/src/legacy-cli.js +2548 -2435
  100. package/src/mcp/registry.js +695 -695
  101. package/src/memory/blackboard.js +301 -301
  102. package/src/memory/retrieval.js +581 -581
  103. package/src/plugin/manifest.js +553 -553
  104. package/src/policy/packs.js +144 -144
  105. package/src/prompt/generator.js +118 -106
  106. package/src/review/ai-review.js +669 -669
  107. package/src/review/local-review.js +1284 -1284
  108. package/src/review/replay.js +235 -235
  109. package/src/review/report.js +664 -664
  110. package/src/review/spec-binding.js +487 -487
  111. package/src/scaffold/generator.js +67 -0
  112. package/src/scaffold/templates.js +150 -0
  113. package/src/scan/generator.js +418 -351
  114. package/src/scan/gh-secrets.js +107 -0
  115. package/src/spec/generator.js +519 -519
  116. package/src/spec/regenerate.js +237 -237
  117. package/src/spec/templates.js +91 -91
  118. package/src/swarm/dashboard.js +247 -247
  119. package/src/swarm/factory.js +363 -363
  120. package/src/swarm/pentest.js +934 -934
  121. package/src/swarm/registry.js +419 -419
  122. package/src/swarm/report.js +158 -158
  123. package/src/swarm/runtime.js +576 -576
  124. package/src/swarm/scenario-dsl.js +272 -272
  125. package/src/telemetry/ledger.js +302 -302
  126. package/src/telemetry/sync.js +96 -59
  127. package/src/ui/markdown.js +220 -220
@@ -1,716 +1,716 @@
1
- import fs from "node:fs";
2
- import fsp from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- import pc from "picocolors";
6
-
7
- import {
8
- createMultiProviderApiClient,
9
- resolveModel,
10
- resolveProvider,
11
- } from "../ai/client.js";
12
- import { loadConfig } from "../config/service.js";
13
- import { evaluateBudget } from "../cost/budget.js";
14
- import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
15
- import { estimateModelCost } from "../cost/tracker.js";
16
- import { formatIngestResolutionNotice, resolveCodebaseIngest } from "../ingest/engine.js";
17
- import {
18
- buildLineDiff,
19
- inferTemplateFromSpec,
20
- mergeSpecRegeneration,
21
- renderLineDiff,
22
- } from "../spec/regenerate.js";
23
- import {
24
- generateSpecMarkdown,
25
- inferProjectTypeFromSpecMarkdown,
26
- resolveProjectType,
27
- resolveSpecTemplate,
28
- } from "../spec/generator.js";
29
- import { SPEC_TEMPLATES } from "../spec/templates.js";
30
- import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
31
- import { renderTerminalMarkdown } from "../ui/markdown.js";
32
- import { createProgressReporter } from "../ui/progress.js";
33
-
34
- const VALID_PROJECT_TYPES = new Set(["greenfield", "add_feature", "bugfix"]);
35
-
36
- function shouldEmitJson(options, command) {
37
- const local = Boolean(options && options.json);
38
- const globalFromCommand =
39
- command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
40
- return local || globalFromCommand;
41
- }
42
-
43
- function isQuietMode(options, command) {
44
- const local = Boolean(options && options.quiet);
45
- const globalFromCommand =
46
- command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().quiet) : false;
47
- return local || globalFromCommand;
48
- }
49
-
50
- function parseNonNegativeNumber(rawValue, field) {
51
- const normalized = Number(rawValue || 0);
52
- if (!Number.isFinite(normalized) || normalized < 0) {
53
- throw new Error(`${field} must be a non-negative number.`);
54
- }
55
- return normalized;
56
- }
57
-
58
- function parsePercent(rawValue, field) {
59
- const normalized = Number(rawValue || 0);
60
- if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
61
- throw new Error(`${field} must be between 0 and 100.`);
62
- }
63
- return normalized;
64
- }
65
-
66
- function parseProjectTypeOption(value) {
67
- const normalized = String(value || "")
68
- .trim()
69
- .toLowerCase();
70
- if (!normalized) {
71
- return "";
72
- }
73
- if (!VALID_PROJECT_TYPES.has(normalized)) {
74
- throw new Error("projectType must be one of: greenfield, add_feature, bugfix.");
75
- }
76
- return normalized;
77
- }
78
-
79
- function resolveSpecArtifactPath(targetPath, explicitPath) {
80
- const explicit = String(explicitPath || "").trim();
81
- if (explicit) {
82
- return path.resolve(targetPath, explicit);
83
- }
84
-
85
- const candidates = [path.join(targetPath, "SPEC.md"), path.join(targetPath, "docs", "spec.md")];
86
- const found = candidates.find((candidate) => fs.existsSync(candidate));
87
- if (found) {
88
- return found;
89
- }
90
-
91
- throw new Error("No spec artifact found. Generate one with 'spec generate' or pass --file.");
92
- }
93
-
94
- function estimateTokenCount(text) {
95
- const normalized = String(text || "");
96
- if (!normalized) {
97
- return 0;
98
- }
99
- return Math.max(1, Math.ceil(normalized.length / 4));
100
- }
101
-
102
- function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
103
- const normalizedProvider = String(provider || "").trim().toLowerCase();
104
- if (normalizedProvider === "openai") {
105
- return String(resolvedConfig.openaiApiKey || "").trim();
106
- }
107
- if (normalizedProvider === "anthropic") {
108
- return String(resolvedConfig.anthropicApiKey || "").trim();
109
- }
110
- if (normalizedProvider === "google") {
111
- return String(resolvedConfig.googleApiKey || "").trim();
112
- }
113
- return "";
114
- }
115
-
116
- function buildAiSpecPrompt({
117
- baseSpecMarkdown,
118
- template,
119
- description,
120
- ingest,
121
- } = {}) {
122
- const summary = ingest?.summary || {};
123
- const frameworkSummary =
124
- Array.isArray(ingest?.frameworks) && ingest.frameworks.length > 0
125
- ? ingest.frameworks.join(", ")
126
- : "none";
127
- const riskSummary =
128
- Array.isArray(ingest?.riskSurfaces) && ingest.riskSurfaces.length > 0
129
- ? ingest.riskSurfaces.slice(0, 10).map((item) => item.surface).join(", ")
130
- : "code_quality";
131
-
132
- return [
133
- "You are a senior software architect improving a deterministic SPEC document.",
134
- "Return only markdown. Do not include code fences around the full response.",
135
- "Maintain the section structure and keep language concrete and implementation-ready.",
136
- "Preserve deterministic constraints and include explicit security/reliability controls.",
137
- "",
138
- `Template: ${template?.id || "api-service"}`,
139
- `Goal override: ${String(description || "").trim() || "none"}`,
140
- `Files scanned: ${summary.filesScanned || 0}`,
141
- `Total LOC: ${summary.totalLoc || 0}`,
142
- `Framework hints: ${frameworkSummary}`,
143
- `Risk surfaces: ${riskSummary}`,
144
- "",
145
- "Source SPEC markdown:",
146
- baseSpecMarkdown,
147
- ].join("\n");
148
- }
149
-
150
- function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
151
- try {
152
- return {
153
- costUsd: estimateModelCost({
154
- modelId,
155
- inputTokens,
156
- outputTokens,
157
- }),
158
- pricingFound: true,
159
- };
160
- } catch {
161
- return {
162
- costUsd: 0,
163
- pricingFound: false,
164
- };
165
- }
166
- }
167
-
168
- function printAiSummary(ai) {
169
- console.log(pc.bold("AI enhancement"));
170
- console.log(pc.gray(`Provider: ${ai.provider}, Model: ${ai.model}`));
171
- console.log(
172
- pc.gray(
173
- `Input tokens=${ai.usage.inputTokens}, Output tokens=${ai.usage.outputTokens}, Cost=$${ai.usage.costUsd.toFixed(6)}, DurationMs=${ai.usage.durationMs}`
174
- )
175
- );
176
- if (!ai.pricingFound) {
177
- console.log(pc.yellow("Model pricing missing from local table; cost recorded as 0."));
178
- }
179
- if (ai.budget.blocking) {
180
- console.log(pc.red("AI budget guardrail triggered:"));
181
- for (const reason of ai.budget.reasons) {
182
- console.log(`- ${reason.code}: ${reason.message}`);
183
- }
184
- } else if (ai.budget.warnings.length > 0) {
185
- console.log(pc.yellow("AI budget warning threshold reached:"));
186
- for (const warning of ai.budget.warnings) {
187
- console.log(`- ${warning.code}: ${warning.message}`);
188
- }
189
- }
190
- }
191
-
192
- async function maybeEnhanceSpecWithAi({
193
- enabled,
194
- options,
195
- targetPath,
196
- template,
197
- description,
198
- ingest,
199
- baseSpecMarkdown,
200
- } = {}) {
201
- if (!enabled) {
202
- return {
203
- markdown: baseSpecMarkdown,
204
- ai: null,
205
- };
206
- }
207
-
208
- const config = await loadConfig({ cwd: targetPath });
209
- const resolvedProvider = resolveProvider({
210
- provider: options.provider,
211
- configProvider: config.resolved.defaultModelProvider,
212
- env: process.env,
213
- });
214
- const resolvedModel = resolveModel({
215
- provider: resolvedProvider,
216
- model: options.model,
217
- configModel: config.resolved.defaultModelId,
218
- });
219
- const explicitApiKey = String(options.apiKey || "").trim();
220
- const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
221
-
222
- const prompt = buildAiSpecPrompt({
223
- baseSpecMarkdown,
224
- template,
225
- description,
226
- ingest,
227
- });
228
-
229
- const startedAtMs = Date.now();
230
- const client = createMultiProviderApiClient();
231
- const result = await client.invoke({
232
- provider: resolvedProvider,
233
- model: resolvedModel,
234
- prompt,
235
- apiKey: explicitApiKey || configuredApiKey,
236
- env: process.env,
237
- stream: false,
238
- });
239
- const durationMs = Math.max(0, Date.now() - startedAtMs);
240
-
241
- const normalizedText = String(result.text || "").trim();
242
- const enhancedMarkdown = normalizedText || baseSpecMarkdown;
243
-
244
- const inputTokens = estimateTokenCount(prompt);
245
- const outputTokens = estimateTokenCount(enhancedMarkdown);
246
- const modelCost = maybeEstimateModelCost({
247
- modelId: result.model,
248
- inputTokens,
249
- outputTokens,
250
- });
251
-
252
- const sessionId = String(options.sessionId || "spec-generate-ai").trim() || "spec-generate-ai";
253
- const appendedCost = await appendCostEntry(
254
- {
255
- targetPath,
256
- outputDirOverride: options.outputDir,
257
- },
258
- {
259
- sessionId,
260
- provider: result.provider,
261
- model: result.model,
262
- inputTokens,
263
- outputTokens,
264
- cacheReadTokens: 0,
265
- cacheWriteTokens: 0,
266
- durationMs,
267
- toolCalls: 1,
268
- costUsd: modelCost.costUsd,
269
- progressScore: normalizedText ? 1 : 0,
270
- }
271
- );
272
-
273
- const costSummary = summarizeCostHistory(appendedCost.history);
274
- const sessionSummary = costSummary.sessions.find((item) => item.sessionId === sessionId) || {
275
- sessionId,
276
- invocationCount: 0,
277
- inputTokens: 0,
278
- outputTokens: 0,
279
- cacheReadTokens: 0,
280
- cacheWriteTokens: 0,
281
- durationMs: 0,
282
- toolCalls: 0,
283
- costUsd: 0,
284
- noProgressStreak: 0,
285
- };
286
-
287
- const budget = evaluateBudget({
288
- sessionSummary,
289
- maxCostUsd: parseNonNegativeNumber(options.maxCost, "maxCost"),
290
- maxOutputTokens: parseNonNegativeNumber(options.maxTokens, "maxTokens"),
291
- maxNoProgress: parseNonNegativeNumber(options.maxNoProgress, "maxNoProgress"),
292
- maxRuntimeMs: parseNonNegativeNumber(options.maxRuntimeMs, "maxRuntimeMs"),
293
- maxToolCalls: parseNonNegativeNumber(options.maxToolCalls, "maxToolCalls"),
294
- warningThresholdPercent: parsePercent(options.warnAtPercent, "warnAtPercent"),
295
- });
296
-
297
- const usageTelemetry = await appendRunEvent(
298
- {
299
- targetPath,
300
- outputDirOverride: options.outputDir,
301
- },
302
- {
303
- sessionId,
304
- runId: sessionId,
305
- eventType: "usage",
306
- usage: {
307
- inputTokens,
308
- outputTokens,
309
- cacheReadTokens: 0,
310
- cacheWriteTokens: 0,
311
- costUsd: modelCost.costUsd,
312
- durationMs,
313
- toolCalls: 1,
314
- },
315
- metadata: {
316
- sourceCommand: "spec generate --ai",
317
- provider: result.provider,
318
- model: result.model,
319
- invocationId: appendedCost.entry.invocationId,
320
- },
321
- }
322
- );
323
-
324
- let stopTelemetry = null;
325
- if (budget.blocking) {
326
- stopTelemetry = await appendRunEvent(
327
- {
328
- targetPath,
329
- outputDirOverride: options.outputDir,
330
- },
331
- {
332
- sessionId,
333
- runId: sessionId,
334
- eventType: "run_stop",
335
- usage: {
336
- inputTokens: sessionSummary.inputTokens,
337
- outputTokens: sessionSummary.outputTokens,
338
- cacheReadTokens: sessionSummary.cacheReadTokens,
339
- cacheWriteTokens: sessionSummary.cacheWriteTokens,
340
- costUsd: sessionSummary.costUsd,
341
- durationMs: sessionSummary.durationMs,
342
- toolCalls: sessionSummary.toolCalls,
343
- },
344
- stop: {
345
- stopClass: deriveStopClassFromBudget(budget),
346
- blocking: true,
347
- reasonCodes: budget.reasons.map((reason) => reason.code),
348
- },
349
- metadata: {
350
- sourceCommand: "spec generate --ai",
351
- provider: result.provider,
352
- model: result.model,
353
- invocationId: appendedCost.entry.invocationId,
354
- },
355
- }
356
- );
357
- }
358
-
359
- return {
360
- markdown: enhancedMarkdown,
361
- ai: {
362
- enabled: true,
363
- provider: result.provider,
364
- model: result.model,
365
- pricingFound: modelCost.pricingFound,
366
- usage: {
367
- inputTokens,
368
- outputTokens,
369
- costUsd: modelCost.costUsd,
370
- durationMs,
371
- toolCalls: 1,
372
- },
373
- budget,
374
- cost: {
375
- filePath: appendedCost.filePath,
376
- invocationId: appendedCost.entry.invocationId,
377
- sessionId,
378
- },
379
- telemetry: {
380
- filePath: usageTelemetry.filePath,
381
- usageEventId: usageTelemetry.event.eventId,
382
- stopEventId: stopTelemetry?.event?.eventId || null,
383
- },
384
- },
385
- };
386
- }
387
-
388
- export function registerSpecCommand(program) {
389
- const spec = program
390
- .command("spec")
391
- .description("Offline spec generation and template management");
392
-
393
- spec
394
- .command("list-templates")
395
- .description("List built-in spec templates")
396
- .option("--json", "Emit machine-readable output")
397
- .action(async (options, command) => {
398
- if (shouldEmitJson(options, command)) {
399
- console.log(JSON.stringify({ templates: SPEC_TEMPLATES }, null, 2));
400
- return;
401
- }
402
-
403
- console.log(pc.bold("Available templates"));
404
- for (const template of SPEC_TEMPLATES) {
405
- console.log(`- ${template.id}: ${template.name} - ${template.description}`);
406
- }
407
- });
408
-
409
- spec
410
- .command("show-template <templateId>")
411
- .description("Show details for one template")
412
- .option("--json", "Emit machine-readable output")
413
- .action(async (templateId, options, command) => {
414
- const template = resolveSpecTemplate(templateId);
415
- if (shouldEmitJson(options, command)) {
416
- console.log(JSON.stringify({ template }, null, 2));
417
- return;
418
- }
419
-
420
- console.log(pc.bold(`${template.name} (${template.id})`));
421
- console.log(template.description);
422
- console.log("\nArchitecture focus:");
423
- template.architectureFocus.forEach((item, index) => console.log(`${index + 1}. ${item}`));
424
- console.log("\nSecurity checklist:");
425
- template.securityChecklist.forEach((item, index) => console.log(`${index + 1}. ${item}`));
426
- });
427
-
428
- spec
429
- .command("generate")
430
- .description("Generate SPEC.md from ingest + selected template")
431
- .option("--path <path>", "Target workspace path", ".")
432
- .option("--template <templateId>", "Template id (see spec list-templates)", "api-service")
433
- .option("--description <text>", "Optional primary goal override")
434
- .option("--project-type <type>", "Project type override (greenfield|add_feature|bugfix)")
435
- .option("--output-file <path>", "Output file path relative to --path", "SPEC.md")
436
- .option("--output-dir <path>", "Optional output dir override for cost/telemetry artifacts")
437
- .option("--refresh", "Refresh CODEBASE_INGEST before generating SPEC")
438
- .option("--ai", "Enable AI-enhanced markdown refinement after deterministic spec generation")
439
- .option("--provider <name>", "AI provider override (openai|anthropic|google)")
440
- .option("--model <id>", "AI model override")
441
- .option("--api-key <key>", "Optional explicit API key override for --ai mode")
442
- .option("--session-id <id>", "Cost/telemetry session id for --ai mode", "spec-generate-ai")
443
- .option("--max-cost <usd>", "Max AI cost budget per session", "1")
444
- .option("--max-tokens <n>", "Max output token budget per session (0 = disabled)", "0")
445
- .option("--max-runtime-ms <n>", "Max runtime budget per session in milliseconds (0 = disabled)", "0")
446
- .option("--max-tool-calls <n>", "Max tool-call budget per session (0 = disabled)", "0")
447
- .option("--max-no-progress <n>", "Max consecutive no-progress events before stop", "3")
448
- .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
449
- .option("--json", "Emit machine-readable output")
450
- .action(async (options, command) => {
451
- const emitJson = shouldEmitJson(options, command);
452
- const progress = createProgressReporter({
453
- quiet: emitJson || isQuietMode(options, command),
454
- });
455
- progress.start("spec generate: collecting codebase ingest");
456
-
457
- try {
458
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
459
- const outputFile = String(options.outputFile || "SPEC.md").trim() || "SPEC.md";
460
- const outputPath = path.resolve(targetPath, outputFile);
461
-
462
- const template = resolveSpecTemplate(options.template);
463
- const ingestResolution = await resolveCodebaseIngest({
464
- rootPath: targetPath,
465
- outputDir: options.outputDir,
466
- refresh: Boolean(options.refresh),
467
- });
468
- const ingest = ingestResolution.ingest;
469
- const explicitProjectType = parseProjectTypeOption(options.projectType);
470
- const resolvedProjectType = resolveProjectType({
471
- projectType: explicitProjectType,
472
- ingest,
473
- description: options.description,
474
- });
475
- progress.update(30, "spec generate: deterministic draft");
476
- const deterministicMarkdown = generateSpecMarkdown({
477
- template,
478
- description: options.description,
479
- ingest,
480
- projectPath: targetPath,
481
- projectType: resolvedProjectType,
482
- });
483
-
484
- progress.update(65, "spec generate: optional AI refinement");
485
- const aiResult = await maybeEnhanceSpecWithAi({
486
- enabled: Boolean(options.ai),
487
- options,
488
- targetPath,
489
- template,
490
- description: options.description,
491
- ingest,
492
- baseSpecMarkdown: deterministicMarkdown,
493
- });
494
-
495
- progress.update(85, "spec generate: writing spec artifact");
496
- await fsp.mkdir(path.dirname(outputPath), { recursive: true });
497
- await fsp.writeFile(outputPath, `${aiResult.markdown.trimEnd()}\n`, "utf-8");
498
-
499
- const payload = {
500
- command: "spec generate",
501
- template: template.id,
502
- targetPath,
503
- outputPath,
504
- summary: ingest.summary,
505
- frameworks: ingest.frameworks,
506
- riskSurfaces: ingest.riskSurfaces,
507
- projectType: resolvedProjectType,
508
- ingestRefresh: {
509
- outputPath: ingestResolution.outputPath,
510
- refreshed: ingestResolution.refreshed,
511
- stale: ingestResolution.stale,
512
- reasons: ingestResolution.reasons,
513
- refreshedBecause: ingestResolution.refreshedBecause,
514
- lastCommitAt: ingestResolution.lastCommitAt,
515
- contentHash: ingestResolution.fingerprint?.contentHash || "",
516
- },
517
- ai: aiResult.ai,
518
- };
519
-
520
- if (emitJson) {
521
- console.log(JSON.stringify(payload, null, 2));
522
- } else {
523
- console.log(pc.bold("Spec generated"));
524
- console.log(pc.gray(`Template: ${template.id}`));
525
- console.log(pc.gray(`Output: ${outputPath}`));
526
- if (ingestResolution.stale || ingestResolution.refreshed) {
527
- const color = ingestResolution.stale && !ingestResolution.refreshed ? pc.yellow : pc.gray;
528
- console.log(color(formatIngestResolutionNotice(ingestResolution)));
529
- }
530
- if (aiResult.ai) {
531
- printAiSummary(aiResult.ai);
532
- }
533
- }
534
-
535
- if (aiResult.ai?.budget?.blocking) {
536
- process.exitCode = 2;
537
- }
538
- progress.complete("spec generate complete");
539
- } catch (error) {
540
- progress.fail("spec generate failed");
541
- throw error;
542
- }
543
- });
544
-
545
- spec
546
- .command("regenerate")
547
- .description("Regenerate SPEC.md, preserve manual edits, and show line diff before overwrite")
548
- .option("--path <path>", "Target workspace path", ".")
549
- .option("--file <path>", "Spec file path relative to --path")
550
- .option("--template <templateId>", "Template id override (defaults to template inferred from SPEC.md)")
551
- .option("--description <text>", "Optional goal override for regenerated deterministic sections")
552
- .option("--project-type <type>", "Project type override (greenfield|add_feature|bugfix)")
553
- .option("--refresh", "Refresh CODEBASE_INGEST before regenerating SPEC")
554
- .option("--dry-run", "Preview merged SPEC and diff without writing file")
555
- .option("--no-diff", "Disable terminal diff output")
556
- .option("--plain", "Disable colorized diff output")
557
- .option("--max-diff-lines <n>", "Max diff lines to print (0 = unlimited)", "220")
558
- .option("--no-preserve-manual", "Allow regenerated sections to overwrite manual edits")
559
- .option("--json", "Emit machine-readable output")
560
- .action(async (options, command) => {
561
- const emitJson = shouldEmitJson(options, command);
562
- const progress = createProgressReporter({
563
- quiet: emitJson || isQuietMode(options, command),
564
- });
565
- progress.start("spec regenerate: loading current spec");
566
-
567
- try {
568
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
569
- const specPath = resolveSpecArtifactPath(targetPath, options.file);
570
- const existingMarkdown = await fsp.readFile(specPath, "utf-8");
571
-
572
- progress.update(25, "spec regenerate: rebuilding deterministic spec");
573
- const inferredTemplate = inferTemplateFromSpec(existingMarkdown);
574
- const resolvedTemplateId =
575
- String(options.template || "").trim() || inferredTemplate || "api-service";
576
- const template = resolveSpecTemplate(resolvedTemplateId);
577
- const ingestResolution = await resolveCodebaseIngest({
578
- rootPath: targetPath,
579
- refresh: Boolean(options.refresh),
580
- });
581
- const ingest = ingestResolution.ingest;
582
- const explicitProjectType = parseProjectTypeOption(options.projectType);
583
- const inferredProjectType = inferProjectTypeFromSpecMarkdown(existingMarkdown);
584
- const resolvedProjectType = resolveProjectType({
585
- projectType: explicitProjectType || inferredProjectType,
586
- ingest,
587
- description: options.description,
588
- });
589
- const regeneratedMarkdown = generateSpecMarkdown({
590
- template,
591
- description: options.description,
592
- ingest,
593
- projectPath: targetPath,
594
- projectType: resolvedProjectType,
595
- });
596
-
597
- progress.update(55, "spec regenerate: preserving manual sections");
598
- const merged = mergeSpecRegeneration({
599
- existingMarkdown,
600
- regeneratedMarkdown,
601
- preserveManual: Boolean(options.preserveManual),
602
- });
603
- const diff = buildLineDiff(existingMarkdown, merged.mergedMarkdown);
604
- const maxDiffLines = Number.parseInt(String(options.maxDiffLines || "220"), 10);
605
- const diffPreview = renderLineDiff(diff, {
606
- plain: true,
607
- maxLines: Number.isFinite(maxDiffLines) ? maxDiffLines : 220,
608
- });
609
-
610
- progress.update(80, "spec regenerate: writing changes");
611
- const shouldWrite = !options.dryRun && diff.changed;
612
- if (shouldWrite) {
613
- await fsp.writeFile(specPath, merged.mergedMarkdown, "utf-8");
614
- }
615
-
616
- const payload = {
617
- command: "spec regenerate",
618
- targetPath,
619
- specPath,
620
- template: template.id,
621
- projectType: resolvedProjectType,
622
- dryRun: Boolean(options.dryRun),
623
- preserveManual: Boolean(options.preserveManual),
624
- changed: diff.changed,
625
- wroteFile: shouldWrite,
626
- summary: merged.summary,
627
- diff: {
628
- added: diff.added,
629
- removed: diff.removed,
630
- changed: diff.changed,
631
- preview: diffPreview,
632
- },
633
- ingestRefresh: {
634
- outputPath: ingestResolution.outputPath,
635
- refreshed: ingestResolution.refreshed,
636
- stale: ingestResolution.stale,
637
- reasons: ingestResolution.reasons,
638
- refreshedBecause: ingestResolution.refreshedBecause,
639
- lastCommitAt: ingestResolution.lastCommitAt,
640
- contentHash: ingestResolution.fingerprint?.contentHash || "",
641
- },
642
- };
643
-
644
- if (emitJson) {
645
- console.log(JSON.stringify(payload, null, 2));
646
- progress.complete("spec regenerate complete");
647
- return;
648
- }
649
-
650
- console.log(pc.bold("Spec regeneration"));
651
- console.log(pc.gray(`Spec: ${specPath}`));
652
- console.log(pc.gray(`Template: ${template.id}`));
653
- console.log(
654
- pc.gray(
655
- `Summary: changed=${diff.changed} added=${diff.added} removed=${diff.removed} preserved_manual_sections=${merged.summary.preservedManualSections.length}`
656
- )
657
- );
658
- if (ingestResolution.stale || ingestResolution.refreshed) {
659
- const color = ingestResolution.stale && !ingestResolution.refreshed ? pc.yellow : pc.gray;
660
- console.log(color(formatIngestResolutionNotice(ingestResolution)));
661
- }
662
- if (options.diff) {
663
- const rendered = renderLineDiff(diff, {
664
- plain: Boolean(options.plain),
665
- maxLines: Number.isFinite(maxDiffLines) ? maxDiffLines : 220,
666
- });
667
- if (rendered.trim()) {
668
- console.log(rendered);
669
- }
670
- }
671
- if (options.dryRun) {
672
- console.log(pc.yellow("Dry run enabled: SPEC file was not modified."));
673
- } else if (shouldWrite) {
674
- console.log(pc.green(`Updated ${specPath}`));
675
- } else {
676
- console.log(pc.gray("No file write required; generated output matches current spec."));
677
- }
678
- progress.complete("spec regenerate complete");
679
- } catch (error) {
680
- progress.fail("spec regenerate failed");
681
- throw error;
682
- }
683
- });
684
-
685
- spec
686
- .command("show")
687
- .description("Render an existing SPEC artifact in terminal markdown")
688
- .option("--path <path>", "Target workspace path", ".")
689
- .option("--file <path>", "Spec file path relative to --path")
690
- .option("--plain", "Disable terminal markdown styling")
691
- .option("--json", "Emit machine-readable output")
692
- .action(async (options, command) => {
693
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
694
- const specPath = resolveSpecArtifactPath(targetPath, options.file);
695
- const markdown = await fsp.readFile(specPath, "utf-8");
696
-
697
- if (shouldEmitJson(options, command)) {
698
- console.log(
699
- JSON.stringify(
700
- {
701
- command: "spec show",
702
- specPath,
703
- lineCount: markdown.split(/\r?\n/).length,
704
- preview: markdown,
705
- },
706
- null,
707
- 2
708
- )
709
- );
710
- return;
711
- }
712
-
713
- console.log(renderTerminalMarkdown(markdown, { plain: Boolean(options.plain) }));
714
- });
715
- }
716
-
1
+ import fs from "node:fs";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import pc from "picocolors";
6
+
7
+ import {
8
+ createMultiProviderApiClient,
9
+ resolveModel,
10
+ resolveProvider,
11
+ } from "../ai/client.js";
12
+ import { loadConfig } from "../config/service.js";
13
+ import { evaluateBudget } from "../cost/budget.js";
14
+ import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
15
+ import { estimateModelCost } from "../cost/tracker.js";
16
+ import { formatIngestResolutionNotice, resolveCodebaseIngest } from "../ingest/engine.js";
17
+ import {
18
+ buildLineDiff,
19
+ inferTemplateFromSpec,
20
+ mergeSpecRegeneration,
21
+ renderLineDiff,
22
+ } from "../spec/regenerate.js";
23
+ import {
24
+ generateSpecMarkdown,
25
+ inferProjectTypeFromSpecMarkdown,
26
+ resolveProjectType,
27
+ resolveSpecTemplate,
28
+ } from "../spec/generator.js";
29
+ import { SPEC_TEMPLATES } from "../spec/templates.js";
30
+ import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
31
+ import { renderTerminalMarkdown } from "../ui/markdown.js";
32
+ import { createProgressReporter } from "../ui/progress.js";
33
+
34
+ const VALID_PROJECT_TYPES = new Set(["greenfield", "add_feature", "bugfix"]);
35
+
36
+ function shouldEmitJson(options, command) {
37
+ const local = Boolean(options && options.json);
38
+ const globalFromCommand =
39
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
40
+ return local || globalFromCommand;
41
+ }
42
+
43
+ function isQuietMode(options, command) {
44
+ const local = Boolean(options && options.quiet);
45
+ const globalFromCommand =
46
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().quiet) : false;
47
+ return local || globalFromCommand;
48
+ }
49
+
50
+ function parseNonNegativeNumber(rawValue, field) {
51
+ const normalized = Number(rawValue || 0);
52
+ if (!Number.isFinite(normalized) || normalized < 0) {
53
+ throw new Error(`${field} must be a non-negative number.`);
54
+ }
55
+ return normalized;
56
+ }
57
+
58
+ function parsePercent(rawValue, field) {
59
+ const normalized = Number(rawValue || 0);
60
+ if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
61
+ throw new Error(`${field} must be between 0 and 100.`);
62
+ }
63
+ return normalized;
64
+ }
65
+
66
+ function parseProjectTypeOption(value) {
67
+ const normalized = String(value || "")
68
+ .trim()
69
+ .toLowerCase();
70
+ if (!normalized) {
71
+ return "";
72
+ }
73
+ if (!VALID_PROJECT_TYPES.has(normalized)) {
74
+ throw new Error("projectType must be one of: greenfield, add_feature, bugfix.");
75
+ }
76
+ return normalized;
77
+ }
78
+
79
+ function resolveSpecArtifactPath(targetPath, explicitPath) {
80
+ const explicit = String(explicitPath || "").trim();
81
+ if (explicit) {
82
+ return path.resolve(targetPath, explicit);
83
+ }
84
+
85
+ const candidates = [path.join(targetPath, "SPEC.md"), path.join(targetPath, "docs", "spec.md")];
86
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
87
+ if (found) {
88
+ return found;
89
+ }
90
+
91
+ throw new Error("No spec artifact found. Generate one with 'spec generate' or pass --file.");
92
+ }
93
+
94
+ function estimateTokenCount(text) {
95
+ const normalized = String(text || "");
96
+ if (!normalized) {
97
+ return 0;
98
+ }
99
+ return Math.max(1, Math.ceil(normalized.length / 4));
100
+ }
101
+
102
+ function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
103
+ const normalizedProvider = String(provider || "").trim().toLowerCase();
104
+ if (normalizedProvider === "openai") {
105
+ return String(resolvedConfig.openaiApiKey || "").trim();
106
+ }
107
+ if (normalizedProvider === "anthropic") {
108
+ return String(resolvedConfig.anthropicApiKey || "").trim();
109
+ }
110
+ if (normalizedProvider === "google") {
111
+ return String(resolvedConfig.googleApiKey || "").trim();
112
+ }
113
+ return "";
114
+ }
115
+
116
+ function buildAiSpecPrompt({
117
+ baseSpecMarkdown,
118
+ template,
119
+ description,
120
+ ingest,
121
+ } = {}) {
122
+ const summary = ingest?.summary || {};
123
+ const frameworkSummary =
124
+ Array.isArray(ingest?.frameworks) && ingest.frameworks.length > 0
125
+ ? ingest.frameworks.join(", ")
126
+ : "none";
127
+ const riskSummary =
128
+ Array.isArray(ingest?.riskSurfaces) && ingest.riskSurfaces.length > 0
129
+ ? ingest.riskSurfaces.slice(0, 10).map((item) => item.surface).join(", ")
130
+ : "code_quality";
131
+
132
+ return [
133
+ "You are a senior software architect improving a deterministic SPEC document.",
134
+ "Return only markdown. Do not include code fences around the full response.",
135
+ "Maintain the section structure and keep language concrete and implementation-ready.",
136
+ "Preserve deterministic constraints and include explicit security/reliability controls.",
137
+ "",
138
+ `Template: ${template?.id || "api-service"}`,
139
+ `Goal override: ${String(description || "").trim() || "none"}`,
140
+ `Files scanned: ${summary.filesScanned || 0}`,
141
+ `Total LOC: ${summary.totalLoc || 0}`,
142
+ `Framework hints: ${frameworkSummary}`,
143
+ `Risk surfaces: ${riskSummary}`,
144
+ "",
145
+ "Source SPEC markdown:",
146
+ baseSpecMarkdown,
147
+ ].join("\n");
148
+ }
149
+
150
+ function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
151
+ try {
152
+ return {
153
+ costUsd: estimateModelCost({
154
+ modelId,
155
+ inputTokens,
156
+ outputTokens,
157
+ }),
158
+ pricingFound: true,
159
+ };
160
+ } catch {
161
+ return {
162
+ costUsd: 0,
163
+ pricingFound: false,
164
+ };
165
+ }
166
+ }
167
+
168
+ function printAiSummary(ai) {
169
+ console.log(pc.bold("AI enhancement"));
170
+ console.log(pc.gray(`Provider: ${ai.provider}, Model: ${ai.model}`));
171
+ console.log(
172
+ pc.gray(
173
+ `Input tokens=${ai.usage.inputTokens}, Output tokens=${ai.usage.outputTokens}, Cost=$${ai.usage.costUsd.toFixed(6)}, DurationMs=${ai.usage.durationMs}`
174
+ )
175
+ );
176
+ if (!ai.pricingFound) {
177
+ console.log(pc.yellow("Model pricing missing from local table; cost recorded as 0."));
178
+ }
179
+ if (ai.budget.blocking) {
180
+ console.log(pc.red("AI budget guardrail triggered:"));
181
+ for (const reason of ai.budget.reasons) {
182
+ console.log(`- ${reason.code}: ${reason.message}`);
183
+ }
184
+ } else if (ai.budget.warnings.length > 0) {
185
+ console.log(pc.yellow("AI budget warning threshold reached:"));
186
+ for (const warning of ai.budget.warnings) {
187
+ console.log(`- ${warning.code}: ${warning.message}`);
188
+ }
189
+ }
190
+ }
191
+
192
+ async function maybeEnhanceSpecWithAi({
193
+ enabled,
194
+ options,
195
+ targetPath,
196
+ template,
197
+ description,
198
+ ingest,
199
+ baseSpecMarkdown,
200
+ } = {}) {
201
+ if (!enabled) {
202
+ return {
203
+ markdown: baseSpecMarkdown,
204
+ ai: null,
205
+ };
206
+ }
207
+
208
+ const config = await loadConfig({ cwd: targetPath });
209
+ const resolvedProvider = resolveProvider({
210
+ provider: options.provider,
211
+ configProvider: config.resolved.defaultModelProvider,
212
+ env: process.env,
213
+ });
214
+ const resolvedModel = resolveModel({
215
+ provider: resolvedProvider,
216
+ model: options.model,
217
+ configModel: config.resolved.defaultModelId,
218
+ });
219
+ const explicitApiKey = String(options.apiKey || "").trim();
220
+ const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
221
+
222
+ const prompt = buildAiSpecPrompt({
223
+ baseSpecMarkdown,
224
+ template,
225
+ description,
226
+ ingest,
227
+ });
228
+
229
+ const startedAtMs = Date.now();
230
+ const client = createMultiProviderApiClient();
231
+ const result = await client.invoke({
232
+ provider: resolvedProvider,
233
+ model: resolvedModel,
234
+ prompt,
235
+ apiKey: explicitApiKey || configuredApiKey,
236
+ env: process.env,
237
+ stream: false,
238
+ });
239
+ const durationMs = Math.max(0, Date.now() - startedAtMs);
240
+
241
+ const normalizedText = String(result.text || "").trim();
242
+ const enhancedMarkdown = normalizedText || baseSpecMarkdown;
243
+
244
+ const inputTokens = estimateTokenCount(prompt);
245
+ const outputTokens = estimateTokenCount(enhancedMarkdown);
246
+ const modelCost = maybeEstimateModelCost({
247
+ modelId: result.model,
248
+ inputTokens,
249
+ outputTokens,
250
+ });
251
+
252
+ const sessionId = String(options.sessionId || "spec-generate-ai").trim() || "spec-generate-ai";
253
+ const appendedCost = await appendCostEntry(
254
+ {
255
+ targetPath,
256
+ outputDirOverride: options.outputDir,
257
+ },
258
+ {
259
+ sessionId,
260
+ provider: result.provider,
261
+ model: result.model,
262
+ inputTokens,
263
+ outputTokens,
264
+ cacheReadTokens: 0,
265
+ cacheWriteTokens: 0,
266
+ durationMs,
267
+ toolCalls: 1,
268
+ costUsd: modelCost.costUsd,
269
+ progressScore: normalizedText ? 1 : 0,
270
+ }
271
+ );
272
+
273
+ const costSummary = summarizeCostHistory(appendedCost.history);
274
+ const sessionSummary = costSummary.sessions.find((item) => item.sessionId === sessionId) || {
275
+ sessionId,
276
+ invocationCount: 0,
277
+ inputTokens: 0,
278
+ outputTokens: 0,
279
+ cacheReadTokens: 0,
280
+ cacheWriteTokens: 0,
281
+ durationMs: 0,
282
+ toolCalls: 0,
283
+ costUsd: 0,
284
+ noProgressStreak: 0,
285
+ };
286
+
287
+ const budget = evaluateBudget({
288
+ sessionSummary,
289
+ maxCostUsd: parseNonNegativeNumber(options.maxCost, "maxCost"),
290
+ maxOutputTokens: parseNonNegativeNumber(options.maxTokens, "maxTokens"),
291
+ maxNoProgress: parseNonNegativeNumber(options.maxNoProgress, "maxNoProgress"),
292
+ maxRuntimeMs: parseNonNegativeNumber(options.maxRuntimeMs, "maxRuntimeMs"),
293
+ maxToolCalls: parseNonNegativeNumber(options.maxToolCalls, "maxToolCalls"),
294
+ warningThresholdPercent: parsePercent(options.warnAtPercent, "warnAtPercent"),
295
+ });
296
+
297
+ const usageTelemetry = await appendRunEvent(
298
+ {
299
+ targetPath,
300
+ outputDirOverride: options.outputDir,
301
+ },
302
+ {
303
+ sessionId,
304
+ runId: sessionId,
305
+ eventType: "usage",
306
+ usage: {
307
+ inputTokens,
308
+ outputTokens,
309
+ cacheReadTokens: 0,
310
+ cacheWriteTokens: 0,
311
+ costUsd: modelCost.costUsd,
312
+ durationMs,
313
+ toolCalls: 1,
314
+ },
315
+ metadata: {
316
+ sourceCommand: "spec generate --ai",
317
+ provider: result.provider,
318
+ model: result.model,
319
+ invocationId: appendedCost.entry.invocationId,
320
+ },
321
+ }
322
+ );
323
+
324
+ let stopTelemetry = null;
325
+ if (budget.blocking) {
326
+ stopTelemetry = await appendRunEvent(
327
+ {
328
+ targetPath,
329
+ outputDirOverride: options.outputDir,
330
+ },
331
+ {
332
+ sessionId,
333
+ runId: sessionId,
334
+ eventType: "run_stop",
335
+ usage: {
336
+ inputTokens: sessionSummary.inputTokens,
337
+ outputTokens: sessionSummary.outputTokens,
338
+ cacheReadTokens: sessionSummary.cacheReadTokens,
339
+ cacheWriteTokens: sessionSummary.cacheWriteTokens,
340
+ costUsd: sessionSummary.costUsd,
341
+ durationMs: sessionSummary.durationMs,
342
+ toolCalls: sessionSummary.toolCalls,
343
+ },
344
+ stop: {
345
+ stopClass: deriveStopClassFromBudget(budget),
346
+ blocking: true,
347
+ reasonCodes: budget.reasons.map((reason) => reason.code),
348
+ },
349
+ metadata: {
350
+ sourceCommand: "spec generate --ai",
351
+ provider: result.provider,
352
+ model: result.model,
353
+ invocationId: appendedCost.entry.invocationId,
354
+ },
355
+ }
356
+ );
357
+ }
358
+
359
+ return {
360
+ markdown: enhancedMarkdown,
361
+ ai: {
362
+ enabled: true,
363
+ provider: result.provider,
364
+ model: result.model,
365
+ pricingFound: modelCost.pricingFound,
366
+ usage: {
367
+ inputTokens,
368
+ outputTokens,
369
+ costUsd: modelCost.costUsd,
370
+ durationMs,
371
+ toolCalls: 1,
372
+ },
373
+ budget,
374
+ cost: {
375
+ filePath: appendedCost.filePath,
376
+ invocationId: appendedCost.entry.invocationId,
377
+ sessionId,
378
+ },
379
+ telemetry: {
380
+ filePath: usageTelemetry.filePath,
381
+ usageEventId: usageTelemetry.event.eventId,
382
+ stopEventId: stopTelemetry?.event?.eventId || null,
383
+ },
384
+ },
385
+ };
386
+ }
387
+
388
+ export function registerSpecCommand(program) {
389
+ const spec = program
390
+ .command("spec")
391
+ .description("Offline spec generation and template management");
392
+
393
+ spec
394
+ .command("list-templates")
395
+ .description("List built-in spec templates")
396
+ .option("--json", "Emit machine-readable output")
397
+ .action(async (options, command) => {
398
+ if (shouldEmitJson(options, command)) {
399
+ console.log(JSON.stringify({ templates: SPEC_TEMPLATES }, null, 2));
400
+ return;
401
+ }
402
+
403
+ console.log(pc.bold("Available templates"));
404
+ for (const template of SPEC_TEMPLATES) {
405
+ console.log(`- ${template.id}: ${template.name} - ${template.description}`);
406
+ }
407
+ });
408
+
409
+ spec
410
+ .command("show-template <templateId>")
411
+ .description("Show details for one template")
412
+ .option("--json", "Emit machine-readable output")
413
+ .action(async (templateId, options, command) => {
414
+ const template = resolveSpecTemplate(templateId);
415
+ if (shouldEmitJson(options, command)) {
416
+ console.log(JSON.stringify({ template }, null, 2));
417
+ return;
418
+ }
419
+
420
+ console.log(pc.bold(`${template.name} (${template.id})`));
421
+ console.log(template.description);
422
+ console.log("\nArchitecture focus:");
423
+ template.architectureFocus.forEach((item, index) => console.log(`${index + 1}. ${item}`));
424
+ console.log("\nSecurity checklist:");
425
+ template.securityChecklist.forEach((item, index) => console.log(`${index + 1}. ${item}`));
426
+ });
427
+
428
+ spec
429
+ .command("generate")
430
+ .description("Generate SPEC.md from ingest + selected template")
431
+ .option("--path <path>", "Target workspace path", ".")
432
+ .option("--template <templateId>", "Template id (see spec list-templates)", "api-service")
433
+ .option("--description <text>", "Optional primary goal override")
434
+ .option("--project-type <type>", "Project type override (greenfield|add_feature|bugfix)")
435
+ .option("--output-file <path>", "Output file path relative to --path", "SPEC.md")
436
+ .option("--output-dir <path>", "Optional output dir override for cost/telemetry artifacts")
437
+ .option("--refresh", "Refresh CODEBASE_INGEST before generating SPEC")
438
+ .option("--ai", "Enable AI-enhanced markdown refinement after deterministic spec generation")
439
+ .option("--provider <name>", "AI provider override (openai|anthropic|google)")
440
+ .option("--model <id>", "AI model override")
441
+ .option("--api-key <key>", "Optional explicit API key override for --ai mode")
442
+ .option("--session-id <id>", "Cost/telemetry session id for --ai mode", "spec-generate-ai")
443
+ .option("--max-cost <usd>", "Max AI cost budget per session", "1")
444
+ .option("--max-tokens <n>", "Max output token budget per session (0 = disabled)", "0")
445
+ .option("--max-runtime-ms <n>", "Max runtime budget per session in milliseconds (0 = disabled)", "0")
446
+ .option("--max-tool-calls <n>", "Max tool-call budget per session (0 = disabled)", "0")
447
+ .option("--max-no-progress <n>", "Max consecutive no-progress events before stop", "3")
448
+ .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
449
+ .option("--json", "Emit machine-readable output")
450
+ .action(async (options, command) => {
451
+ const emitJson = shouldEmitJson(options, command);
452
+ const progress = createProgressReporter({
453
+ quiet: emitJson || isQuietMode(options, command),
454
+ });
455
+ progress.start("spec generate: collecting codebase ingest");
456
+
457
+ try {
458
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
459
+ const outputFile = String(options.outputFile || "SPEC.md").trim() || "SPEC.md";
460
+ const outputPath = path.resolve(targetPath, outputFile);
461
+
462
+ const template = resolveSpecTemplate(options.template);
463
+ const ingestResolution = await resolveCodebaseIngest({
464
+ rootPath: targetPath,
465
+ outputDir: options.outputDir,
466
+ refresh: Boolean(options.refresh),
467
+ });
468
+ const ingest = ingestResolution.ingest;
469
+ const explicitProjectType = parseProjectTypeOption(options.projectType);
470
+ const resolvedProjectType = resolveProjectType({
471
+ projectType: explicitProjectType,
472
+ ingest,
473
+ description: options.description,
474
+ });
475
+ progress.update(30, "spec generate: deterministic draft");
476
+ const deterministicMarkdown = generateSpecMarkdown({
477
+ template,
478
+ description: options.description,
479
+ ingest,
480
+ projectPath: targetPath,
481
+ projectType: resolvedProjectType,
482
+ });
483
+
484
+ progress.update(65, "spec generate: optional AI refinement");
485
+ const aiResult = await maybeEnhanceSpecWithAi({
486
+ enabled: Boolean(options.ai),
487
+ options,
488
+ targetPath,
489
+ template,
490
+ description: options.description,
491
+ ingest,
492
+ baseSpecMarkdown: deterministicMarkdown,
493
+ });
494
+
495
+ progress.update(85, "spec generate: writing spec artifact");
496
+ await fsp.mkdir(path.dirname(outputPath), { recursive: true });
497
+ await fsp.writeFile(outputPath, `${aiResult.markdown.trimEnd()}\n`, "utf-8");
498
+
499
+ const payload = {
500
+ command: "spec generate",
501
+ template: template.id,
502
+ targetPath,
503
+ outputPath,
504
+ summary: ingest.summary,
505
+ frameworks: ingest.frameworks,
506
+ riskSurfaces: ingest.riskSurfaces,
507
+ projectType: resolvedProjectType,
508
+ ingestRefresh: {
509
+ outputPath: ingestResolution.outputPath,
510
+ refreshed: ingestResolution.refreshed,
511
+ stale: ingestResolution.stale,
512
+ reasons: ingestResolution.reasons,
513
+ refreshedBecause: ingestResolution.refreshedBecause,
514
+ lastCommitAt: ingestResolution.lastCommitAt,
515
+ contentHash: ingestResolution.fingerprint?.contentHash || "",
516
+ },
517
+ ai: aiResult.ai,
518
+ };
519
+
520
+ if (emitJson) {
521
+ console.log(JSON.stringify(payload, null, 2));
522
+ } else {
523
+ console.log(pc.bold("Spec generated"));
524
+ console.log(pc.gray(`Template: ${template.id}`));
525
+ console.log(pc.gray(`Output: ${outputPath}`));
526
+ if (ingestResolution.stale || ingestResolution.refreshed) {
527
+ const color = ingestResolution.stale && !ingestResolution.refreshed ? pc.yellow : pc.gray;
528
+ console.log(color(formatIngestResolutionNotice(ingestResolution)));
529
+ }
530
+ if (aiResult.ai) {
531
+ printAiSummary(aiResult.ai);
532
+ }
533
+ }
534
+
535
+ if (aiResult.ai?.budget?.blocking) {
536
+ process.exitCode = 2;
537
+ }
538
+ progress.complete("spec generate complete");
539
+ } catch (error) {
540
+ progress.fail("spec generate failed");
541
+ throw error;
542
+ }
543
+ });
544
+
545
+ spec
546
+ .command("regenerate")
547
+ .description("Regenerate SPEC.md, preserve manual edits, and show line diff before overwrite")
548
+ .option("--path <path>", "Target workspace path", ".")
549
+ .option("--file <path>", "Spec file path relative to --path")
550
+ .option("--template <templateId>", "Template id override (defaults to template inferred from SPEC.md)")
551
+ .option("--description <text>", "Optional goal override for regenerated deterministic sections")
552
+ .option("--project-type <type>", "Project type override (greenfield|add_feature|bugfix)")
553
+ .option("--refresh", "Refresh CODEBASE_INGEST before regenerating SPEC")
554
+ .option("--dry-run", "Preview merged SPEC and diff without writing file")
555
+ .option("--no-diff", "Disable terminal diff output")
556
+ .option("--plain", "Disable colorized diff output")
557
+ .option("--max-diff-lines <n>", "Max diff lines to print (0 = unlimited)", "220")
558
+ .option("--no-preserve-manual", "Allow regenerated sections to overwrite manual edits")
559
+ .option("--json", "Emit machine-readable output")
560
+ .action(async (options, command) => {
561
+ const emitJson = shouldEmitJson(options, command);
562
+ const progress = createProgressReporter({
563
+ quiet: emitJson || isQuietMode(options, command),
564
+ });
565
+ progress.start("spec regenerate: loading current spec");
566
+
567
+ try {
568
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
569
+ const specPath = resolveSpecArtifactPath(targetPath, options.file);
570
+ const existingMarkdown = await fsp.readFile(specPath, "utf-8");
571
+
572
+ progress.update(25, "spec regenerate: rebuilding deterministic spec");
573
+ const inferredTemplate = inferTemplateFromSpec(existingMarkdown);
574
+ const resolvedTemplateId =
575
+ String(options.template || "").trim() || inferredTemplate || "api-service";
576
+ const template = resolveSpecTemplate(resolvedTemplateId);
577
+ const ingestResolution = await resolveCodebaseIngest({
578
+ rootPath: targetPath,
579
+ refresh: Boolean(options.refresh),
580
+ });
581
+ const ingest = ingestResolution.ingest;
582
+ const explicitProjectType = parseProjectTypeOption(options.projectType);
583
+ const inferredProjectType = inferProjectTypeFromSpecMarkdown(existingMarkdown);
584
+ const resolvedProjectType = resolveProjectType({
585
+ projectType: explicitProjectType || inferredProjectType,
586
+ ingest,
587
+ description: options.description,
588
+ });
589
+ const regeneratedMarkdown = generateSpecMarkdown({
590
+ template,
591
+ description: options.description,
592
+ ingest,
593
+ projectPath: targetPath,
594
+ projectType: resolvedProjectType,
595
+ });
596
+
597
+ progress.update(55, "spec regenerate: preserving manual sections");
598
+ const merged = mergeSpecRegeneration({
599
+ existingMarkdown,
600
+ regeneratedMarkdown,
601
+ preserveManual: Boolean(options.preserveManual),
602
+ });
603
+ const diff = buildLineDiff(existingMarkdown, merged.mergedMarkdown);
604
+ const maxDiffLines = Number.parseInt(String(options.maxDiffLines || "220"), 10);
605
+ const diffPreview = renderLineDiff(diff, {
606
+ plain: true,
607
+ maxLines: Number.isFinite(maxDiffLines) ? maxDiffLines : 220,
608
+ });
609
+
610
+ progress.update(80, "spec regenerate: writing changes");
611
+ const shouldWrite = !options.dryRun && diff.changed;
612
+ if (shouldWrite) {
613
+ await fsp.writeFile(specPath, merged.mergedMarkdown, "utf-8");
614
+ }
615
+
616
+ const payload = {
617
+ command: "spec regenerate",
618
+ targetPath,
619
+ specPath,
620
+ template: template.id,
621
+ projectType: resolvedProjectType,
622
+ dryRun: Boolean(options.dryRun),
623
+ preserveManual: Boolean(options.preserveManual),
624
+ changed: diff.changed,
625
+ wroteFile: shouldWrite,
626
+ summary: merged.summary,
627
+ diff: {
628
+ added: diff.added,
629
+ removed: diff.removed,
630
+ changed: diff.changed,
631
+ preview: diffPreview,
632
+ },
633
+ ingestRefresh: {
634
+ outputPath: ingestResolution.outputPath,
635
+ refreshed: ingestResolution.refreshed,
636
+ stale: ingestResolution.stale,
637
+ reasons: ingestResolution.reasons,
638
+ refreshedBecause: ingestResolution.refreshedBecause,
639
+ lastCommitAt: ingestResolution.lastCommitAt,
640
+ contentHash: ingestResolution.fingerprint?.contentHash || "",
641
+ },
642
+ };
643
+
644
+ if (emitJson) {
645
+ console.log(JSON.stringify(payload, null, 2));
646
+ progress.complete("spec regenerate complete");
647
+ return;
648
+ }
649
+
650
+ console.log(pc.bold("Spec regeneration"));
651
+ console.log(pc.gray(`Spec: ${specPath}`));
652
+ console.log(pc.gray(`Template: ${template.id}`));
653
+ console.log(
654
+ pc.gray(
655
+ `Summary: changed=${diff.changed} added=${diff.added} removed=${diff.removed} preserved_manual_sections=${merged.summary.preservedManualSections.length}`
656
+ )
657
+ );
658
+ if (ingestResolution.stale || ingestResolution.refreshed) {
659
+ const color = ingestResolution.stale && !ingestResolution.refreshed ? pc.yellow : pc.gray;
660
+ console.log(color(formatIngestResolutionNotice(ingestResolution)));
661
+ }
662
+ if (options.diff) {
663
+ const rendered = renderLineDiff(diff, {
664
+ plain: Boolean(options.plain),
665
+ maxLines: Number.isFinite(maxDiffLines) ? maxDiffLines : 220,
666
+ });
667
+ if (rendered.trim()) {
668
+ console.log(rendered);
669
+ }
670
+ }
671
+ if (options.dryRun) {
672
+ console.log(pc.yellow("Dry run enabled: SPEC file was not modified."));
673
+ } else if (shouldWrite) {
674
+ console.log(pc.green(`Updated ${specPath}`));
675
+ } else {
676
+ console.log(pc.gray("No file write required; generated output matches current spec."));
677
+ }
678
+ progress.complete("spec regenerate complete");
679
+ } catch (error) {
680
+ progress.fail("spec regenerate failed");
681
+ throw error;
682
+ }
683
+ });
684
+
685
+ spec
686
+ .command("show")
687
+ .description("Render an existing SPEC artifact in terminal markdown")
688
+ .option("--path <path>", "Target workspace path", ".")
689
+ .option("--file <path>", "Spec file path relative to --path")
690
+ .option("--plain", "Disable terminal markdown styling")
691
+ .option("--json", "Emit machine-readable output")
692
+ .action(async (options, command) => {
693
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
694
+ const specPath = resolveSpecArtifactPath(targetPath, options.file);
695
+ const markdown = await fsp.readFile(specPath, "utf-8");
696
+
697
+ if (shouldEmitJson(options, command)) {
698
+ console.log(
699
+ JSON.stringify(
700
+ {
701
+ command: "spec show",
702
+ specPath,
703
+ lineCount: markdown.split(/\r?\n/).length,
704
+ preview: markdown,
705
+ },
706
+ null,
707
+ 2
708
+ )
709
+ );
710
+ return;
711
+ }
712
+
713
+ console.log(renderTerminalMarkdown(markdown, { plain: Boolean(options.plain) }));
714
+ });
715
+ }
716
+