sentinelayer-cli 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,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
+ }