sentinelayer-cli 0.6.2 → 0.8.1

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