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