sentinelayer-cli 0.4.4 → 0.6.2

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 (149) hide show
  1. package/README.md +996 -998
  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 +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -0
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1166 -1166
  67. package/src/commands/auth.js +419 -375
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -21
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -1,519 +1,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
- 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
+ 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
+ }