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,519 +1,619 @@
1
- import path from "node:path";
2
-
3
- import { getDefaultTemplate, getTemplateById } from "./templates.js";
4
-
5
- const VALID_PROJECT_TYPES = new Set(["greenfield", "add_feature", "bugfix"]);
6
-
7
- const PROJECT_TYPE_LABELS = Object.freeze({
8
- greenfield: "Greenfield",
9
- add_feature: "Add feature",
10
- bugfix: "Bugfix",
11
- });
12
-
13
- function normalizeList(values, fallback = []) {
14
- if (!Array.isArray(values)) {
15
- return fallback;
16
- }
17
- const normalized = values
18
- .map((value) => String(value || "").trim())
19
- .filter(Boolean);
20
- return normalized.length > 0 ? normalized : fallback;
21
- }
22
-
23
- export function resolveSpecTemplate(templateId) {
24
- if (!templateId) {
25
- return getDefaultTemplate();
26
- }
27
- const template = getTemplateById(templateId);
28
- if (!template) {
29
- throw new Error(`Unknown spec template '${templateId}'. Use 'spec list-templates' to view valid ids.`);
30
- }
31
- return template;
32
- }
33
-
34
- export function inferProjectName({ projectPath, ingest }) {
35
- const fromPackage = String(ingest?.packageMetadata?.name || "").trim();
36
- if (fromPackage) {
37
- return fromPackage;
38
- }
39
- return path.basename(path.resolve(projectPath || ingest?.rootPath || process.cwd()));
40
- }
41
-
42
- function renderSectionList(items) {
43
- return items.map((item, index) => `${index + 1}. ${item}`).join("\n");
44
- }
45
-
46
- function clamp(value, min, max) {
47
- return Math.min(Math.max(value, min), max);
48
- }
49
-
50
- function normalizeProjectType(value) {
51
- const normalized = String(value || "")
52
- .trim()
53
- .toLowerCase();
54
- return VALID_PROJECT_TYPES.has(normalized) ? normalized : "";
55
- }
56
-
57
- function inferProjectTypeFromDescription(description) {
58
- const normalized = String(description || "")
59
- .trim()
60
- .toLowerCase();
61
- if (!normalized) {
62
- return "";
63
- }
64
-
65
- if (/\b(bug|fix|hotfix|regression|incident|vulnerability|patch)\b/.test(normalized)) {
66
- return "bugfix";
67
- }
68
- if (/\b(add|feature|extend|enhance|integrat|upgrade|existing|refactor)\b/.test(normalized)) {
69
- return "add_feature";
70
- }
71
- return "";
72
- }
73
-
74
- export function inferProjectTypeFromIngest(ingest = {}) {
75
- const filesScanned = Number(ingest?.summary?.filesScanned || 0);
76
- const hasEntryPoints = Array.isArray(ingest?.entryPoints) && ingest.entryPoints.length > 0;
77
- const hasFrameworks = Array.isArray(ingest?.frameworks) && ingest.frameworks.length > 0;
78
- const hasManifests = Array.isArray(ingest?.manifests?.detected) && ingest.manifests.detected.length > 0;
79
- const indexedFiles = Array.isArray(ingest?.indexedFiles?.files) ? ingest.indexedFiles.files.length : 0;
80
-
81
- if (filesScanned <= 1 && !hasEntryPoints && !hasFrameworks && !hasManifests) {
82
- return "greenfield";
83
- }
84
- if (filesScanned <= 12 && indexedFiles <= 12 && !hasEntryPoints && !hasFrameworks && !hasManifests) {
85
- return "greenfield";
86
- }
87
- return "add_feature";
88
- }
89
-
90
- export function resolveProjectType({ projectType, ingest, description } = {}) {
91
- const explicit = normalizeProjectType(projectType);
92
- if (explicit) {
93
- return explicit;
94
- }
95
-
96
- const fromDescription = inferProjectTypeFromDescription(description);
97
- if (fromDescription) {
98
- return fromDescription;
99
- }
100
- return inferProjectTypeFromIngest(ingest);
101
- }
102
-
103
- export function inferProjectTypeFromSpecMarkdown(markdown) {
104
- const source = String(markdown || "");
105
- const directMatch =
106
- source.match(/- Project type:\s*`?(greenfield|add_feature|bugfix)`?/i) ||
107
- source.match(/^Project type:\s*`?(greenfield|add_feature|bugfix)`?/im);
108
- if (!directMatch) {
109
- return "";
110
- }
111
- return normalizeProjectType(directMatch[1]);
112
- }
113
-
114
- function deriveTechStackLine(ingest) {
115
- const languageSummary = Array.isArray(ingest?.languages)
116
- ? ingest.languages
117
- .slice(0, 6)
118
- .map((item) => `${item.language} (${item.loc} LOC)`)
119
- .join(", ")
120
- : "none";
121
-
122
- const frameworkSummary = Array.isArray(ingest?.frameworks) && ingest.frameworks.length
123
- ? ingest.frameworks.join(", ")
124
- : "none";
125
-
126
- return {
127
- languages: languageSummary,
128
- frameworks: frameworkSummary,
129
- };
130
- }
131
-
132
- function toTitleCaseFromSnake(value) {
133
- return String(value || "")
134
- .split("_")
135
- .filter(Boolean)
136
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
137
- .join(" ");
138
- }
139
-
140
- function estimatePhaseEffort({ projectType, taskCount, riskSurfaceCount, phaseIndex }) {
141
- const phaseWeight = phaseIndex + 1;
142
- const projectTypeBoost = projectType === "bugfix" ? 1 : 0;
143
- const baseline = 4 + taskCount * 2 + Math.min(riskSurfaceCount, 5) + phaseWeight + projectTypeBoost;
144
- const minHours = Math.max(4, baseline - 2);
145
- const maxHours = baseline + 2;
146
- return `${minHours}-${maxHours} hours`;
147
- }
148
-
149
- function derivePhaseAcceptanceCriteria(items, phaseTitle) {
150
- const base = items.slice(0, 3).map((item) => {
151
- const normalized = String(item || "").trim().replace(/\.$/, "");
152
- return `Verified ${normalized.toLowerCase()}.`;
153
- });
154
- if (base.length > 0) {
155
- return base;
156
- }
157
- return [`Verified outcomes for ${phaseTitle}.`];
158
- }
159
-
160
- function buildPhase({
161
- phaseNumber,
162
- titleSuffix,
163
- items,
164
- projectType,
165
- riskSurfaceCount,
166
- previousPhaseTitle = "",
167
- }) {
168
- const title = `Phase ${phaseNumber} - ${titleSuffix}`;
169
- return {
170
- title,
171
- items,
172
- dependencies: previousPhaseTitle ? [previousPhaseTitle] : [],
173
- effort: estimatePhaseEffort({
174
- projectType,
175
- taskCount: items.length,
176
- riskSurfaceCount,
177
- phaseIndex: phaseNumber - 1,
178
- }),
179
- acceptanceCriteria: derivePhaseAcceptanceCriteria(items, title),
180
- };
181
- }
182
-
183
- function deriveBasePhases({ template, projectType, topRiskSurfaces }) {
184
- const templateName = String(template?.name || "template").toLowerCase();
185
- const topSurface = topRiskSurfaces[0] || "critical risk surfaces";
186
-
187
- if (projectType === "bugfix") {
188
- return [
189
- {
190
- titleSuffix: "Root Cause Analysis",
191
- items: [
192
- "Reproduce the defect with deterministic steps and collect impacted traces.",
193
- "Pinpoint fault boundaries and confirm why existing controls missed detection.",
194
- `Document ${topSurface} impact and blast radius before any code changes.`,
195
- ],
196
- },
197
- {
198
- titleSuffix: "Fix Implementation",
199
- items: [
200
- "Implement the smallest safe code change that resolves the confirmed root cause.",
201
- "Add guardrails and failure-mode handling for adjacent paths touched by the fix.",
202
- "Validate data/schema/backward compatibility impacts before rollout.",
203
- ],
204
- },
205
- {
206
- titleSuffix: "Regression Prevention",
207
- items: [
208
- "Add deterministic regression tests for the exact failure path and close variants.",
209
- "Update runbooks, alerts, and release checks to prevent recurrence.",
210
- "Capture post-fix verification evidence and rollback triggers.",
211
- ],
212
- },
213
- ];
214
- }
215
-
216
- if (projectType === "add_feature") {
217
- return [
218
- {
219
- titleSuffix: "Impact Analysis",
220
- items: [
221
- "Map existing module boundaries, API contracts, and state transitions touched by the feature.",
222
- `Define compatibility constraints with current ${templateName} behavior and deployment flow.`,
223
- `Prioritize risk surfaces for the feature path: ${topRiskSurfaces.slice(0, 3).join(", ") || "code_quality"}.`,
224
- ],
225
- },
226
- {
227
- titleSuffix: "Implementation",
228
- items: [
229
- "Implement feature logic end-to-end with explicit interface contracts.",
230
- "Add telemetry and structured error handling for newly introduced branches.",
231
- "Keep migrations/config changes deterministic and reversible.",
232
- ],
233
- },
234
- {
235
- titleSuffix: "Integration Testing",
236
- items: [
237
- "Run integration coverage across touched endpoints, data flows, and job boundaries.",
238
- "Validate backward compatibility and release safety with deterministic gates.",
239
- "Document rollout, rollback, and operational acceptance checks.",
240
- ],
241
- },
242
- ];
243
- }
244
-
245
- return [
246
- {
247
- titleSuffix: "Foundation",
248
- items: [
249
- "Define architecture boundaries and interfaces.",
250
- `Establish ${templateName} baseline scaffolding and dev workflow.`,
251
- "Add deterministic CI checks before feature expansion.",
252
- ],
253
- },
254
- {
255
- titleSuffix: "Core Delivery",
256
- items: [
257
- "Implement highest-value user flow end-to-end.",
258
- "Add telemetry and error handling for critical paths.",
259
- "Document rollout and rollback paths for the first release slice.",
260
- ],
261
- },
262
- {
263
- titleSuffix: "Integration & Hardening",
264
- items: [
265
- `Address prioritized risk surfaces: ${topRiskSurfaces.slice(0, 4).join(", ") || "code_quality"}.`,
266
- "Expand automated test coverage for critical paths and integration seams.",
267
- "Finalize deployment guardrails and incident rollback readiness.",
268
- ],
269
- },
270
- ];
271
- }
272
-
273
- function deriveDynamicPhaseCount({ template, ingest, description, riskSurfaces }) {
274
- const wordCount = String(description || "")
275
- .trim()
276
- .split(/\s+/)
277
- .filter(Boolean).length;
278
- const filesScanned = Number(ingest?.summary?.filesScanned || 0);
279
- const totalLoc = Number(ingest?.summary?.totalLoc || 0);
280
- const riskCount = Array.isArray(riskSurfaces) ? riskSurfaces.length : 0;
281
-
282
- const riskBoost = riskCount >= 12 ? 4 : riskCount >= 8 ? 2 : riskCount >= 4 ? 1 : 0;
283
- const complexityBoost =
284
- (wordCount >= 200 ? 2 : wordCount >= 70 ? 1 : 0) +
285
- (filesScanned >= 1000 ? 2 : filesScanned >= 250 ? 1 : 0) +
286
- (totalLoc >= 50_000 ? 2 : totalLoc >= 10_000 ? 1 : 0);
287
- const templateBoost = ["saas-app", "mobile-app"].includes(String(template?.id || "")) ? 1 : 0;
288
-
289
- // No upper cap — enterprise projects can have 10-20+ phases based on complexity.
290
- // Floor at 3 (minimum viable: foundation + core + hardening).
291
- return Math.max(3, 3 + riskBoost + complexityBoost + templateBoost);
292
- }
293
-
294
- function buildSupplementalPhaseItems({ projectType, surfaces }) {
295
- const normalizedSurfaces = surfaces.map((item) => toTitleCaseFromSnake(item));
296
- const headline = normalizedSurfaces.join(" + ") || "Targeted hardening";
297
-
298
- if (projectType === "bugfix") {
299
- return [
300
- `Harden ${headline} controls with additional negative-path tests.`,
301
- "Validate observability and alert coverage for recurrence signals.",
302
- "Confirm mitigation evidence and operator runbook updates.",
303
- ];
304
- }
305
-
306
- if (projectType === "add_feature") {
307
- return [
308
- `Complete feature readiness for ${headline} boundaries.`,
309
- "Run cross-module integration checks and update interface contracts.",
310
- "Validate deployment sequencing and fallback controls for this slice.",
311
- ];
312
- }
313
-
314
- return [
315
- `Deliver additional capability for ${headline} surfaces.`,
316
- "Expand reliability and security controls for the new scope.",
317
- "Confirm deterministic acceptance checks and release readiness.",
318
- ];
319
- }
320
-
321
- function derivePhasePlan(template, ingest, { projectType, description }) {
322
- const riskSurfaces = Array.isArray(ingest?.riskSurfaces) ? ingest.riskSurfaces : [];
323
- const topRiskSurfaces = riskSurfaces.slice(0, 8).map((item) => item.surface);
324
- const baseBlueprint = deriveBasePhases({ template, projectType, topRiskSurfaces });
325
- const desiredPhaseCount = deriveDynamicPhaseCount({
326
- template,
327
- ingest,
328
- description,
329
- riskSurfaces: topRiskSurfaces,
330
- });
331
- const additionalPhaseCount = Math.max(0, desiredPhaseCount - baseBlueprint.length);
332
-
333
- const phases = [];
334
- for (let index = 0; index < baseBlueprint.length; index += 1) {
335
- const phase = baseBlueprint[index];
336
- phases.push(
337
- buildPhase({
338
- phaseNumber: index + 1,
339
- titleSuffix: phase.titleSuffix,
340
- items: phase.items,
341
- projectType,
342
- riskSurfaceCount: topRiskSurfaces.length,
343
- previousPhaseTitle: phases[index - 1]?.title || "",
344
- })
345
- );
346
- }
347
-
348
- for (let index = 0; index < additionalPhaseCount; index += 1) {
349
- const start = index * 2;
350
- const groupedSurfaces = topRiskSurfaces.slice(start, start + 2);
351
- const fallbackSurface =
352
- groupedSurfaces.length > 0 ? groupedSurfaces[0] : topRiskSurfaces[index] || "code_quality";
353
- const titleSuffix = `${toTitleCaseFromSnake(fallbackSurface)} Optimization`;
354
- const items = buildSupplementalPhaseItems({
355
- projectType,
356
- surfaces: groupedSurfaces.length > 0 ? groupedSurfaces : [fallbackSurface],
357
- });
358
-
359
- phases.push(
360
- buildPhase({
361
- phaseNumber: phases.length + 1,
362
- titleSuffix,
363
- items,
364
- projectType,
365
- riskSurfaceCount: topRiskSurfaces.length,
366
- previousPhaseTitle: phases[phases.length - 1]?.title || "",
367
- })
368
- );
369
- }
370
-
371
- // AIdenID awareness: if auth/login patterns detected, append E2E testing phase
372
- if (shouldSuggestAidenId(ingest, description)) {
373
- phases.push(
374
- buildPhase({
375
- phaseNumber: phases.length + 1,
376
- titleSuffix: "AIdenID E2E Verification",
377
- items: [
378
- "Confirm AIdenID credentials via `sl auth status` (auto-provisioned at login), then provision ephemeral test identity via `sl ai provision-email --execute`.",
379
- "Run automated signup flow with provisioned email and verify account creation.",
380
- "Extract OTP from inbound email via AIdenID extraction pipeline (`sl ai identity wait-for-otp`).",
381
- "Complete login flow with extracted OTP and verify authenticated session.",
382
- "Audit authenticated pages for cookie security (httpOnly, Secure, SameSite) via `sl audit frontend --url`.",
383
- "Revoke test identity after verification (`sl ai identity revoke`).",
384
- ],
385
- projectType,
386
- riskSurfaceCount: topRiskSurfaces.length,
387
- previousPhaseTitle: phases[phases.length - 1]?.title || "",
388
- })
389
- );
390
- }
391
-
392
- return phases;
393
- }
394
-
395
- /**
396
- * Detect if the project warrants AIdenID E2E testing suggestions.
397
- * Returns true if auth/login/signup patterns are found in the ingest or description.
398
- */
399
- function shouldSuggestAidenId(ingest, description) {
400
- const descLower = String(description || "").toLowerCase();
401
- const authKeywords = ["login", "signup", "sign up", "register", "authentication", "auth flow", "otp", "verification", "password reset", "invite", "onboarding"];
402
- const descHasAuth = authKeywords.some((kw) => descLower.includes(kw));
403
-
404
- // Check if ingest detected auth-related risk surfaces or frameworks
405
- const surfaces = (ingest?.riskSurfaces || []).map((s) => String(s.surface || "").toLowerCase());
406
- const surfaceHasAuth = surfaces.includes("security_overlay") || surfaces.includes("frontend_runtime");
407
-
408
- // Check if package.json has auth-related dependencies
409
- const scripts = Object.keys(ingest?.packageMetadata?.scripts || {});
410
- const depsHint = scripts.some((s) => /auth|login|session/i.test(s));
411
-
412
- return descHasAuth || (surfaceHasAuth && descLower.length > 50) || depsHint;
413
- }
414
-
415
- function deriveGlobalAcceptanceCriteria(projectType) {
416
- if (projectType === "bugfix") {
417
- return [
418
- "Root cause and blast radius are documented with deterministic evidence.",
419
- "Fix path and adjacent risks are covered by automated regression checks.",
420
- "Operational guardrails (alerts/runbooks/rollback) are updated and verified.",
421
- "Release safety checks pass with zero blocking findings.",
422
- ];
423
- }
424
-
425
- if (projectType === "add_feature") {
426
- return [
427
- "Feature behavior is validated end-to-end and does not regress existing flows.",
428
- "Compatibility, migration, and rollout safety checks are documented and tested.",
429
- "Security/reliability controls cover all new or changed critical paths.",
430
- "CI gates remain deterministic with reproducible artifacts.",
431
- ];
432
- }
433
-
434
- return [
435
- "Primary user flow is implemented and validated by automated checks.",
436
- "CI gates are deterministic and reproducible.",
437
- "Security and reliability controls for critical surfaces are documented and tested.",
438
- "Deployment/rollback guidance is included for the delivered scope.",
439
- ];
440
- }
441
-
442
- export function generateSpecMarkdown({
443
- template,
444
- description,
445
- ingest,
446
- projectPath,
447
- projectType,
448
- generatedAt = new Date().toISOString(),
449
- } = {}) {
450
- const resolvedTemplate = template || getDefaultTemplate();
451
- const projectName = inferProjectName({ projectPath, ingest });
452
- const goal = String(description || "").trim() || `Build and harden ${projectName}.`;
453
- const resolvedProjectType = resolveProjectType({
454
- projectType,
455
- ingest,
456
- description,
457
- });
458
-
459
- const techStack = deriveTechStackLine(ingest);
460
- const entryPoints = normalizeList(ingest?.entryPoints, ["none detected"]);
461
- const riskSurfaces = normalizeList(
462
- Array.isArray(ingest?.riskSurfaces) ? ingest.riskSurfaces.map((item) => item.surface) : [],
463
- ["code_quality"]
464
- );
465
- const architectureFocus = normalizeList(resolvedTemplate.architectureFocus, ["Define module boundaries."]);
466
- const securityChecklist = normalizeList(resolvedTemplate.securityChecklist, ["Apply secure defaults."]);
467
- const globalAcceptanceCriteria = deriveGlobalAcceptanceCriteria(resolvedProjectType);
468
-
469
- const phases = derivePhasePlan(resolvedTemplate, ingest, {
470
- projectType: resolvedProjectType,
471
- description,
472
- });
473
-
474
- const phaseMarkdown = phases
475
- .map(
476
- (phase) =>
477
- [
478
- `### ${phase.title}`,
479
- `- Estimated effort: ${phase.effort}`,
480
- `- Dependencies: ${
481
- phase.dependencies.length > 0 ? phase.dependencies.join(", ") : "none (entry phase)"
482
- }`,
483
- `- Acceptance criteria: ${phase.acceptanceCriteria.join(" | ")}`,
484
- phase.items.map((item, index) => `${index + 1}. ${item}`).join("\n"),
485
- ].join("\n")
486
- )
487
- .join("\n\n");
488
-
489
- return `# SPEC - ${projectName}
490
-
491
- Generated: ${generatedAt}
492
- Template: ${resolvedTemplate.id}
493
- Workspace: ${ingest?.rootPath || path.resolve(projectPath || process.cwd())}
494
-
495
- ## Goal
496
- ${goal}
497
-
498
- ## Ingest Snapshot
499
- - Files scanned: ${ingest?.summary?.filesScanned || 0}
500
- - Total LOC: ${ingest?.summary?.totalLoc || 0}
501
- - Languages: ${techStack.languages}
502
- - Frameworks: ${techStack.frameworks}
503
- - Entry points: ${entryPoints.join(", ")}
504
- - Risk surfaces: ${riskSurfaces.join(", ")}
505
- - Project type: \`${resolvedProjectType}\` (${PROJECT_TYPE_LABELS[resolvedProjectType] || "Greenfield"})
506
-
507
- ## Architecture Focus
508
- ${renderSectionList(architectureFocus)}
509
-
510
- ## Security Checklist
511
- ${renderSectionList(securityChecklist)}
512
-
513
- ## Acceptance Criteria
514
- ${renderSectionList(globalAcceptanceCriteria)}
515
-
516
- ## Phase Plan
517
- ${phaseMarkdown}
518
- `;
519
- }
1
+ import path from "node:path";
2
+
3
+ import { getDefaultTemplate, getTemplateById } from "./templates.js";
4
+
5
+ const VALID_PROJECT_TYPES = new Set(["greenfield", "add_feature", "bugfix"]);
6
+
7
+ const PROJECT_TYPE_LABELS = Object.freeze({
8
+ greenfield: "Greenfield",
9
+ add_feature: "Add feature",
10
+ bugfix: "Bugfix",
11
+ });
12
+
13
+ function normalizeList(values, fallback = []) {
14
+ if (!Array.isArray(values)) {
15
+ return fallback;
16
+ }
17
+ const normalized = values
18
+ .map((value) => String(value || "").trim())
19
+ .filter(Boolean);
20
+ return normalized.length > 0 ? normalized : fallback;
21
+ }
22
+
23
+ export function resolveSpecTemplate(templateId) {
24
+ if (!templateId) {
25
+ return getDefaultTemplate();
26
+ }
27
+ const template = getTemplateById(templateId);
28
+ if (!template) {
29
+ throw new Error(`Unknown spec template '${templateId}'. Use 'spec list-templates' to view valid ids.`);
30
+ }
31
+ return template;
32
+ }
33
+
34
+ export function inferProjectName({ projectPath, ingest }) {
35
+ const fromPackage = String(ingest?.packageMetadata?.name || "").trim();
36
+ if (fromPackage) {
37
+ return fromPackage;
38
+ }
39
+ return path.basename(path.resolve(projectPath || ingest?.rootPath || process.cwd()));
40
+ }
41
+
42
+ function renderSectionList(items) {
43
+ return items.map((item, index) => `${index + 1}. ${item}`).join("\n");
44
+ }
45
+
46
+ function clamp(value, min, max) {
47
+ return Math.min(Math.max(value, min), max);
48
+ }
49
+
50
+ function normalizeProjectType(value) {
51
+ const normalized = String(value || "")
52
+ .trim()
53
+ .toLowerCase();
54
+ return VALID_PROJECT_TYPES.has(normalized) ? normalized : "";
55
+ }
56
+
57
+ function inferProjectTypeFromDescription(description) {
58
+ const normalized = String(description || "")
59
+ .trim()
60
+ .toLowerCase();
61
+ if (!normalized) {
62
+ return "";
63
+ }
64
+
65
+ if (/\b(bug|fix|hotfix|regression|incident|vulnerability|patch)\b/.test(normalized)) {
66
+ return "bugfix";
67
+ }
68
+ if (/\b(add|feature|extend|enhance|integrat|upgrade|existing|refactor)\b/.test(normalized)) {
69
+ return "add_feature";
70
+ }
71
+ return "";
72
+ }
73
+
74
+ export function inferProjectTypeFromIngest(ingest = {}) {
75
+ const filesScanned = Number(ingest?.summary?.filesScanned || 0);
76
+ const hasEntryPoints = Array.isArray(ingest?.entryPoints) && ingest.entryPoints.length > 0;
77
+ const hasFrameworks = Array.isArray(ingest?.frameworks) && ingest.frameworks.length > 0;
78
+ const hasManifests = Array.isArray(ingest?.manifests?.detected) && ingest.manifests.detected.length > 0;
79
+ const indexedFiles = Array.isArray(ingest?.indexedFiles?.files) ? ingest.indexedFiles.files.length : 0;
80
+
81
+ if (filesScanned <= 1 && !hasEntryPoints && !hasFrameworks && !hasManifests) {
82
+ return "greenfield";
83
+ }
84
+ if (filesScanned <= 12 && indexedFiles <= 12 && !hasEntryPoints && !hasFrameworks && !hasManifests) {
85
+ return "greenfield";
86
+ }
87
+ return "add_feature";
88
+ }
89
+
90
+ export function resolveProjectType({ projectType, ingest, description } = {}) {
91
+ const explicit = normalizeProjectType(projectType);
92
+ if (explicit) {
93
+ return explicit;
94
+ }
95
+
96
+ const fromDescription = inferProjectTypeFromDescription(description);
97
+ if (fromDescription) {
98
+ return fromDescription;
99
+ }
100
+ return inferProjectTypeFromIngest(ingest);
101
+ }
102
+
103
+ export function inferProjectTypeFromSpecMarkdown(markdown) {
104
+ const source = String(markdown || "");
105
+ const directMatch =
106
+ source.match(/- Project type:\s*`?(greenfield|add_feature|bugfix)`?/i) ||
107
+ source.match(/^Project type:\s*`?(greenfield|add_feature|bugfix)`?/im);
108
+ if (!directMatch) {
109
+ return "";
110
+ }
111
+ return normalizeProjectType(directMatch[1]);
112
+ }
113
+
114
+ function deriveTechStackLine(ingest) {
115
+ const languageSummary = Array.isArray(ingest?.languages)
116
+ ? ingest.languages
117
+ .slice(0, 6)
118
+ .map((item) => `${item.language} (${item.loc} LOC)`)
119
+ .join(", ")
120
+ : "none";
121
+
122
+ const frameworkSummary = Array.isArray(ingest?.frameworks) && ingest.frameworks.length
123
+ ? ingest.frameworks.join(", ")
124
+ : "none";
125
+
126
+ return {
127
+ languages: languageSummary,
128
+ frameworks: frameworkSummary,
129
+ };
130
+ }
131
+
132
+ function toTitleCaseFromSnake(value) {
133
+ return String(value || "")
134
+ .split("_")
135
+ .filter(Boolean)
136
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
137
+ .join(" ");
138
+ }
139
+
140
+ function estimatePhaseEffort({ projectType, taskCount, riskSurfaceCount, phaseIndex }) {
141
+ const phaseWeight = phaseIndex + 1;
142
+ const projectTypeBoost = projectType === "bugfix" ? 1 : 0;
143
+ const baseline = 4 + taskCount * 2 + Math.min(riskSurfaceCount, 5) + phaseWeight + projectTypeBoost;
144
+ const minHours = Math.max(4, baseline - 2);
145
+ const maxHours = baseline + 2;
146
+ return `${minHours}-${maxHours} hours`;
147
+ }
148
+
149
+ function derivePhaseAcceptanceCriteria(items, phaseTitle) {
150
+ const base = items.slice(0, 3).map((item) => {
151
+ const normalized = String(item || "").trim().replace(/\.$/, "");
152
+ return `Verified ${normalized.toLowerCase()}.`;
153
+ });
154
+ if (base.length > 0) {
155
+ return base;
156
+ }
157
+ return [`Verified outcomes for ${phaseTitle}.`];
158
+ }
159
+
160
+ function buildPhase({
161
+ phaseNumber,
162
+ titleSuffix,
163
+ items,
164
+ projectType,
165
+ riskSurfaceCount,
166
+ previousPhaseTitle = "",
167
+ }) {
168
+ const title = `Phase ${phaseNumber} - ${titleSuffix}`;
169
+ return {
170
+ title,
171
+ items,
172
+ dependencies: previousPhaseTitle ? [previousPhaseTitle] : [],
173
+ effort: estimatePhaseEffort({
174
+ projectType,
175
+ taskCount: items.length,
176
+ riskSurfaceCount,
177
+ phaseIndex: phaseNumber - 1,
178
+ }),
179
+ acceptanceCriteria: derivePhaseAcceptanceCriteria(items, title),
180
+ };
181
+ }
182
+
183
+ function deriveBasePhases({ template, projectType, topRiskSurfaces }) {
184
+ const templateName = String(template?.name || "template").toLowerCase();
185
+ const topSurface = topRiskSurfaces[0] || "critical risk surfaces";
186
+
187
+ if (projectType === "bugfix") {
188
+ return [
189
+ {
190
+ titleSuffix: "Root Cause Analysis",
191
+ items: [
192
+ "Reproduce the defect with deterministic steps and collect impacted traces.",
193
+ "Pinpoint fault boundaries and confirm why existing controls missed detection.",
194
+ `Document ${topSurface} impact and blast radius before any code changes.`,
195
+ ],
196
+ },
197
+ {
198
+ titleSuffix: "Fix Implementation",
199
+ items: [
200
+ "Implement the smallest safe code change that resolves the confirmed root cause.",
201
+ "Add guardrails and failure-mode handling for adjacent paths touched by the fix.",
202
+ "Validate data/schema/backward compatibility impacts before rollout.",
203
+ ],
204
+ },
205
+ {
206
+ titleSuffix: "Regression Prevention",
207
+ items: [
208
+ "Add deterministic regression tests for the exact failure path and close variants.",
209
+ "Update runbooks, alerts, and release checks to prevent recurrence.",
210
+ "Capture post-fix verification evidence and rollback triggers.",
211
+ ],
212
+ },
213
+ ];
214
+ }
215
+
216
+ if (projectType === "add_feature") {
217
+ return [
218
+ {
219
+ titleSuffix: "Impact Analysis",
220
+ items: [
221
+ "Map existing module boundaries, API contracts, and state transitions touched by the feature.",
222
+ `Define compatibility constraints with current ${templateName} behavior and deployment flow.`,
223
+ `Prioritize risk surfaces for the feature path: ${topRiskSurfaces.slice(0, 3).join(", ") || "code_quality"}.`,
224
+ ],
225
+ },
226
+ {
227
+ titleSuffix: "Implementation",
228
+ items: [
229
+ "Implement feature logic end-to-end with explicit interface contracts.",
230
+ "Add telemetry and structured error handling for newly introduced branches.",
231
+ "Keep migrations/config changes deterministic and reversible.",
232
+ ],
233
+ },
234
+ {
235
+ titleSuffix: "Integration Testing",
236
+ items: [
237
+ "Run integration coverage across touched endpoints, data flows, and job boundaries.",
238
+ "Validate backward compatibility and release safety with deterministic gates.",
239
+ "Document rollout, rollback, and operational acceptance checks.",
240
+ ],
241
+ },
242
+ ];
243
+ }
244
+
245
+ return [
246
+ {
247
+ titleSuffix: "Foundation",
248
+ items: [
249
+ "Define architecture boundaries and interfaces.",
250
+ `Establish ${templateName} baseline scaffolding and dev workflow.`,
251
+ "Add deterministic CI checks before feature expansion.",
252
+ ],
253
+ },
254
+ {
255
+ titleSuffix: "Core Delivery",
256
+ items: [
257
+ "Implement highest-value user flow end-to-end.",
258
+ "Add telemetry and error handling for critical paths.",
259
+ "Document rollout and rollback paths for the first release slice.",
260
+ ],
261
+ },
262
+ {
263
+ titleSuffix: "Integration & Hardening",
264
+ items: [
265
+ `Address prioritized risk surfaces: ${topRiskSurfaces.slice(0, 4).join(", ") || "code_quality"}.`,
266
+ "Expand automated test coverage for critical paths and integration seams.",
267
+ "Finalize deployment guardrails and incident rollback readiness.",
268
+ ],
269
+ },
270
+ ];
271
+ }
272
+
273
+ function deriveDynamicPhaseCount({ template, ingest, description, riskSurfaces }) {
274
+ const wordCount = String(description || "")
275
+ .trim()
276
+ .split(/\s+/)
277
+ .filter(Boolean).length;
278
+ const filesScanned = Number(ingest?.summary?.filesScanned || 0);
279
+ const totalLoc = Number(ingest?.summary?.totalLoc || 0);
280
+ const riskCount = Array.isArray(riskSurfaces) ? riskSurfaces.length : 0;
281
+
282
+ const riskBoost = riskCount >= 12 ? 4 : riskCount >= 8 ? 2 : riskCount >= 4 ? 1 : 0;
283
+ const complexityBoost =
284
+ (wordCount >= 200 ? 2 : wordCount >= 70 ? 1 : 0) +
285
+ (filesScanned >= 1000 ? 2 : filesScanned >= 250 ? 1 : 0) +
286
+ (totalLoc >= 50_000 ? 2 : totalLoc >= 10_000 ? 1 : 0);
287
+ const templateBoost = ["saas-app", "mobile-app"].includes(String(template?.id || "")) ? 1 : 0;
288
+
289
+ // No upper cap — enterprise projects can have 10-20+ phases based on complexity.
290
+ // Floor at 3 (minimum viable: foundation + core + hardening).
291
+ return Math.max(3, 3 + riskBoost + complexityBoost + templateBoost);
292
+ }
293
+
294
+ function buildSupplementalPhaseItems({ projectType, surfaces }) {
295
+ const normalizedSurfaces = surfaces.map((item) => toTitleCaseFromSnake(item));
296
+ const headline = normalizedSurfaces.join(" + ") || "Targeted hardening";
297
+
298
+ if (projectType === "bugfix") {
299
+ return [
300
+ `Harden ${headline} controls with additional negative-path tests.`,
301
+ "Validate observability and alert coverage for recurrence signals.",
302
+ "Confirm mitigation evidence and operator runbook updates.",
303
+ ];
304
+ }
305
+
306
+ if (projectType === "add_feature") {
307
+ return [
308
+ `Complete feature readiness for ${headline} boundaries.`,
309
+ "Run cross-module integration checks and update interface contracts.",
310
+ "Validate deployment sequencing and fallback controls for this slice.",
311
+ ];
312
+ }
313
+
314
+ return [
315
+ `Deliver additional capability for ${headline} surfaces.`,
316
+ "Expand reliability and security controls for the new scope.",
317
+ "Confirm deterministic acceptance checks and release readiness.",
318
+ ];
319
+ }
320
+
321
+ function derivePhasePlan(template, ingest, { projectType, description }) {
322
+ const riskSurfaces = Array.isArray(ingest?.riskSurfaces) ? ingest.riskSurfaces : [];
323
+ const topRiskSurfaces = riskSurfaces.slice(0, 8).map((item) => item.surface);
324
+ const baseBlueprint = deriveBasePhases({ template, projectType, topRiskSurfaces });
325
+ const desiredPhaseCount = deriveDynamicPhaseCount({
326
+ template,
327
+ ingest,
328
+ description,
329
+ riskSurfaces: topRiskSurfaces,
330
+ });
331
+ const additionalPhaseCount = Math.max(0, desiredPhaseCount - baseBlueprint.length);
332
+
333
+ const phases = [];
334
+ for (let index = 0; index < baseBlueprint.length; index += 1) {
335
+ const phase = baseBlueprint[index];
336
+ phases.push(
337
+ buildPhase({
338
+ phaseNumber: index + 1,
339
+ titleSuffix: phase.titleSuffix,
340
+ items: phase.items,
341
+ projectType,
342
+ riskSurfaceCount: topRiskSurfaces.length,
343
+ previousPhaseTitle: phases[index - 1]?.title || "",
344
+ })
345
+ );
346
+ }
347
+
348
+ for (let index = 0; index < additionalPhaseCount; index += 1) {
349
+ const start = index * 2;
350
+ const groupedSurfaces = topRiskSurfaces.slice(start, start + 2);
351
+ const fallbackSurface =
352
+ groupedSurfaces.length > 0 ? groupedSurfaces[0] : topRiskSurfaces[index] || "code_quality";
353
+ const titleSuffix = `${toTitleCaseFromSnake(fallbackSurface)} Optimization`;
354
+ const items = buildSupplementalPhaseItems({
355
+ projectType,
356
+ surfaces: groupedSurfaces.length > 0 ? groupedSurfaces : [fallbackSurface],
357
+ });
358
+
359
+ phases.push(
360
+ buildPhase({
361
+ phaseNumber: phases.length + 1,
362
+ titleSuffix,
363
+ items,
364
+ projectType,
365
+ riskSurfaceCount: topRiskSurfaces.length,
366
+ previousPhaseTitle: phases[phases.length - 1]?.title || "",
367
+ })
368
+ );
369
+ }
370
+
371
+ // AIdenID awareness: if auth/login patterns detected, append E2E testing phase
372
+ if (shouldSuggestAidenId(ingest, description)) {
373
+ phases.push(
374
+ buildPhase({
375
+ phaseNumber: phases.length + 1,
376
+ titleSuffix: "AIdenID E2E Verification",
377
+ items: [
378
+ "Confirm AIdenID credentials via `sl auth status` (auto-provisioned at login), then provision ephemeral test identity via `sl ai provision-email --execute`.",
379
+ "Run automated signup flow with provisioned email and verify account creation.",
380
+ "Extract OTP from inbound email via AIdenID extraction pipeline (`sl ai identity wait-for-otp`).",
381
+ "Complete login flow with extracted OTP and verify authenticated session.",
382
+ "Audit authenticated pages for cookie security (httpOnly, Secure, SameSite) via `sl audit frontend --url`.",
383
+ "Revoke test identity after verification (`sl ai identity revoke`).",
384
+ ],
385
+ projectType,
386
+ riskSurfaceCount: topRiskSurfaces.length,
387
+ previousPhaseTitle: phases[phases.length - 1]?.title || "",
388
+ })
389
+ );
390
+ }
391
+
392
+ return phases;
393
+ }
394
+
395
+ /**
396
+ * Detect if the project warrants AIdenID E2E testing suggestions.
397
+ * Returns true if auth/login/signup patterns are found in the ingest or description.
398
+ */
399
+ function shouldSuggestAidenId(ingest, description) {
400
+ const descLower = String(description || "").toLowerCase();
401
+ const authKeywords = ["login", "signup", "sign up", "register", "authentication", "auth flow", "otp", "verification", "password reset", "invite", "onboarding"];
402
+ const descHasAuth = authKeywords.some((kw) => descLower.includes(kw));
403
+
404
+ // Check if ingest detected auth-related risk surfaces or frameworks
405
+ const surfaces = (ingest?.riskSurfaces || []).map((s) => String(s.surface || "").toLowerCase());
406
+ const surfaceHasAuth = surfaces.includes("security_overlay") || surfaces.includes("frontend_runtime");
407
+
408
+ // Check if package.json has auth-related dependencies
409
+ const scripts = Object.keys(ingest?.packageMetadata?.scripts || {});
410
+ const depsHint = scripts.some((s) => /auth|login|session/i.test(s));
411
+
412
+ return descHasAuth || (surfaceHasAuth && descLower.length > 50) || depsHint;
413
+ }
414
+
415
+ function deriveGlobalAcceptanceCriteria(projectType) {
416
+ if (projectType === "bugfix") {
417
+ return [
418
+ "Root cause and blast radius are documented with deterministic evidence.",
419
+ "Fix path and adjacent risks are covered by automated regression checks.",
420
+ "Operational guardrails (alerts/runbooks/rollback) are updated and verified.",
421
+ "Release safety checks pass with zero blocking findings.",
422
+ ];
423
+ }
424
+
425
+ if (projectType === "add_feature") {
426
+ return [
427
+ "Feature behavior is validated end-to-end and does not regress existing flows.",
428
+ "Compatibility, migration, and rollout safety checks are documented and tested.",
429
+ "Security/reliability controls cover all new or changed critical paths.",
430
+ "CI gates remain deterministic with reproducible artifacts.",
431
+ ];
432
+ }
433
+
434
+ return [
435
+ "Primary user flow is implemented and validated by automated checks.",
436
+ "CI gates are deterministic and reproducible.",
437
+ "Security and reliability controls for critical surfaces are documented and tested.",
438
+ "Deployment/rollback guidance is included for the delivered scope.",
439
+ ];
440
+ }
441
+
442
+ function countAgentInstructions(agentsMarkdown) {
443
+ const markdown = String(agentsMarkdown || "");
444
+ if (!markdown) {
445
+ return 0;
446
+ }
447
+
448
+ const lines = markdown.split(/\r?\n/);
449
+ let inAgentsSection = false;
450
+ let sectionCount = 0;
451
+ let globalCount = 0;
452
+ for (const rawLine of lines) {
453
+ const line = String(rawLine || "");
454
+ const trimmed = line.trim();
455
+ if (!trimmed) {
456
+ continue;
457
+ }
458
+
459
+ if (/^#{1,6}\s+.*\bagents?\b/i.test(trimmed)) {
460
+ inAgentsSection = true;
461
+ continue;
462
+ }
463
+ if (inAgentsSection && /^#{1,6}\s+/.test(trimmed)) {
464
+ inAgentsSection = false;
465
+ }
466
+
467
+ if (!/^\s*[-*]\s+/.test(line)) {
468
+ continue;
469
+ }
470
+
471
+ if (/\b(agent|coder|reviewer|tester|observer|persona|daemon)\b/i.test(trimmed)) {
472
+ globalCount += 1;
473
+ if (inAgentsSection) {
474
+ sectionCount += 1;
475
+ }
476
+ }
477
+ }
478
+
479
+ if (sectionCount >= 2) {
480
+ return sectionCount;
481
+ }
482
+ return globalCount;
483
+ }
484
+
485
+ function hasCollaborationSignals(description) {
486
+ const normalized = String(description || "").toLowerCase();
487
+ if (!normalized) {
488
+ return false;
489
+ }
490
+ return /\b(team|pair|paired|multi-agent|multi agent|swarm|collaborat)\b/.test(normalized);
491
+ }
492
+
493
+ function shouldIncludeCoordinationPhase({
494
+ description = "",
495
+ agentsMarkdown = "",
496
+ sessionActive = false,
497
+ } = {}) {
498
+ if (sessionActive === true) {
499
+ return true;
500
+ }
501
+ if (hasCollaborationSignals(description)) {
502
+ return true;
503
+ }
504
+ return countAgentInstructions(agentsMarkdown) >= 2;
505
+ }
506
+
507
+ function buildCoordinationPhase(phaseNumber, previousPhaseTitle = "") {
508
+ return {
509
+ title: `Phase ${phaseNumber}: Multi-Agent Coordination Protocol`,
510
+ items: [
511
+ "Check for active sessions: `sl session list`.",
512
+ "If a session exists, join it: `sl session join <id> --name <your-name> --role coder`.",
513
+ "Emit status updates every 5 minutes: `sl session say <id> \"status: <what you're doing>\"`.",
514
+ "Before modifying a shared file, check recent session activity for that file.",
515
+ "On unexpected file changes, ask in-session instead of stopping: `sl session say <id> \"help: <question>\"`.",
516
+ "Post findings in-session: `sl session say <id> \"finding: [P2] <title> in <file>:<line>\"`.",
517
+ "On completion, update `tasks/todo.md` and emit completion status in-session.",
518
+ "Leave the session when done: `sl session leave <id>`.",
519
+ ],
520
+ dependencies: previousPhaseTitle ? [previousPhaseTitle] : [],
521
+ effort: "4-8 hours",
522
+ acceptanceCriteria: [
523
+ "Session participation path is explicit for all collaborating agents.",
524
+ "Unexpected file-change handling favors in-session coordination over stop-and-wait behavior.",
525
+ "Status and finding updates are emitted with actionable file-level context.",
526
+ ],
527
+ };
528
+ }
529
+
530
+ export function generateSpecMarkdown({
531
+ template,
532
+ description,
533
+ ingest,
534
+ projectPath,
535
+ projectType,
536
+ agentsMarkdown = "",
537
+ sessionActive = false,
538
+ generatedAt = new Date().toISOString(),
539
+ } = {}) {
540
+ const resolvedTemplate = template || getDefaultTemplate();
541
+ const projectName = inferProjectName({ projectPath, ingest });
542
+ const goal = String(description || "").trim() || `Build and harden ${projectName}.`;
543
+ const resolvedProjectType = resolveProjectType({
544
+ projectType,
545
+ ingest,
546
+ description,
547
+ });
548
+
549
+ const techStack = deriveTechStackLine(ingest);
550
+ const entryPoints = normalizeList(ingest?.entryPoints, ["none detected"]);
551
+ const riskSurfaces = normalizeList(
552
+ Array.isArray(ingest?.riskSurfaces) ? ingest.riskSurfaces.map((item) => item.surface) : [],
553
+ ["code_quality"]
554
+ );
555
+ const architectureFocus = normalizeList(resolvedTemplate.architectureFocus, ["Define module boundaries."]);
556
+ const securityChecklist = normalizeList(resolvedTemplate.securityChecklist, ["Apply secure defaults."]);
557
+ const globalAcceptanceCriteria = deriveGlobalAcceptanceCriteria(resolvedProjectType);
558
+
559
+ const phases = derivePhasePlan(resolvedTemplate, ingest, {
560
+ projectType: resolvedProjectType,
561
+ description,
562
+ });
563
+
564
+ if (
565
+ shouldIncludeCoordinationPhase({
566
+ description,
567
+ agentsMarkdown,
568
+ sessionActive,
569
+ })
570
+ ) {
571
+ phases.push(buildCoordinationPhase(phases.length + 1, phases[phases.length - 1]?.title || ""));
572
+ }
573
+
574
+ const phaseMarkdown = phases
575
+ .map(
576
+ (phase) =>
577
+ [
578
+ `### ${phase.title}`,
579
+ `- Estimated effort: ${phase.effort}`,
580
+ `- Dependencies: ${
581
+ phase.dependencies.length > 0 ? phase.dependencies.join(", ") : "none (entry phase)"
582
+ }`,
583
+ `- Acceptance criteria: ${phase.acceptanceCriteria.join(" | ")}`,
584
+ phase.items.map((item, index) => `${index + 1}. ${item}`).join("\n"),
585
+ ].join("\n")
586
+ )
587
+ .join("\n\n");
588
+
589
+ return `# SPEC - ${projectName}
590
+
591
+ Generated: ${generatedAt}
592
+ Template: ${resolvedTemplate.id}
593
+ Workspace: ${ingest?.rootPath || path.resolve(projectPath || process.cwd())}
594
+
595
+ ## Goal
596
+ ${goal}
597
+
598
+ ## Ingest Snapshot
599
+ - Files scanned: ${ingest?.summary?.filesScanned || 0}
600
+ - Total LOC: ${ingest?.summary?.totalLoc || 0}
601
+ - Languages: ${techStack.languages}
602
+ - Frameworks: ${techStack.frameworks}
603
+ - Entry points: ${entryPoints.join(", ")}
604
+ - Risk surfaces: ${riskSurfaces.join(", ")}
605
+ - Project type: \`${resolvedProjectType}\` (${PROJECT_TYPE_LABELS[resolvedProjectType] || "Greenfield"})
606
+
607
+ ## Architecture Focus
608
+ ${renderSectionList(architectureFocus)}
609
+
610
+ ## Security Checklist
611
+ ${renderSectionList(securityChecklist)}
612
+
613
+ ## Acceptance Criteria
614
+ ${renderSectionList(globalAcceptanceCriteria)}
615
+
616
+ ## Phase Plan
617
+ ${phaseMarkdown}
618
+ `;
619
+ }