@stackwright-pro/mcp 0.2.0-alpha.8 → 0.2.0-alpha.81

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.
package/dist/server.mjs CHANGED
@@ -3,15 +3,44 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
 
5
5
  // src/tools/data-explorer.ts
6
- import { z } from "zod";
6
+ import { z as z2 } from "zod";
7
7
  import { listEntities, generateFilter } from "@stackwright-pro/cli-data-explorer";
8
+
9
+ // src/coerce.ts
10
+ import { z } from "zod";
11
+ function jsonCoerce(schema) {
12
+ return z.preprocess((v) => {
13
+ if (typeof v === "string") {
14
+ try {
15
+ return JSON.parse(v);
16
+ } catch {
17
+ return v;
18
+ }
19
+ }
20
+ return v;
21
+ }, schema);
22
+ }
23
+ function boolCoerce(schema) {
24
+ return z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
25
+ }
26
+ function numCoerce(schema) {
27
+ return z.preprocess((v) => {
28
+ if (typeof v === "string" && v.trim() !== "") {
29
+ const n = Number(v);
30
+ if (!Number.isNaN(n)) return n;
31
+ }
32
+ return v;
33
+ }, schema);
34
+ }
35
+
36
+ // src/tools/data-explorer.ts
8
37
  function registerDataExplorerTools(server2) {
9
38
  server2.tool(
10
39
  "stackwright_pro_list_entities",
11
40
  "List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
12
41
  {
13
- specPath: z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
14
- projectRoot: z.string().optional().describe("Project root directory (auto-detected if omitted)")
42
+ specPath: z2.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
43
+ projectRoot: z2.string().optional().describe("Project root directory (auto-detected if omitted)")
15
44
  },
16
45
  async ({ specPath, projectRoot }) => {
17
46
  const result = listEntities({
@@ -59,9 +88,13 @@ function registerDataExplorerTools(server2) {
59
88
  "stackwright_pro_generate_filter",
60
89
  "Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
61
90
  {
62
- selectedEntities: z.array(z.string()).describe('Entity slugs to include (e.g., ["equipment", "supplies"])'),
63
- excludePatterns: z.array(z.string()).optional().describe('Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'),
64
- projectRoot: z.string().optional().describe("Project root directory")
91
+ selectedEntities: jsonCoerce(z2.array(z2.string())).describe(
92
+ 'Entity slugs to include (e.g., ["equipment", "supplies"])'
93
+ ),
94
+ excludePatterns: jsonCoerce(z2.array(z2.string()).optional()).describe(
95
+ 'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
96
+ ),
97
+ projectRoot: z2.string().optional().describe("Project root directory")
65
98
  },
66
99
  async ({ selectedEntities, excludePatterns, projectRoot }) => {
67
100
  const result = generateFilter({
@@ -117,7 +150,7 @@ function registerDataExplorerTools(server2) {
117
150
  }
118
151
 
119
152
  // src/tools/security.ts
120
- import { z as z2 } from "zod";
153
+ import { z as z3 } from "zod";
121
154
  import { createHash } from "crypto";
122
155
  import fs from "fs";
123
156
  import path from "path";
@@ -126,8 +159,8 @@ function registerSecurityTools(server2) {
126
159
  "stackwright_pro_validate_spec",
127
160
  "Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
128
161
  {
129
- specPath: z2.string().describe("URL or file path to the OpenAPI spec to validate"),
130
- configPath: z2.string().optional().describe("Path to stackwright.yml with prebuild.security config")
162
+ specPath: z3.string().describe("URL or file path to the OpenAPI spec to validate"),
163
+ configPath: z3.string().optional().describe("Path to stackwright.yml with prebuild.security config")
131
164
  },
132
165
  async ({ specPath, configPath }) => {
133
166
  let securityEnabled = false;
@@ -235,16 +268,15 @@ Status: Valid (${allowlist.length} specs on allowlist)`
235
268
  "stackwright_pro_add_approved_spec",
236
269
  "Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
237
270
  {
238
- name: z2.string().describe("Human-readable name for the spec"),
239
- url: z2.string().describe("URL or file path to the OpenAPI spec"),
240
- configPath: z2.string().optional().describe("Path to stackwright.yml")
271
+ name: z3.string().describe("Human-readable name for the spec"),
272
+ url: z3.string().describe("URL or file path to the OpenAPI spec"),
273
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
241
274
  },
242
275
  async ({ name, url, configPath }) => {
243
276
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
244
277
  let sha256 = "<computed-at-build>";
245
278
  try {
246
279
  if (url.startsWith("http://") || url.startsWith("https://")) {
247
- sha256 = "<computed-at-build>";
248
280
  } else if (fs.existsSync(url)) {
249
281
  const specContent = fs.readFileSync(url, "utf8");
250
282
  sha256 = createHash("sha256").update(specContent).digest("hex");
@@ -291,7 +323,7 @@ SHA-256 computed: ${sha256}`
291
323
  "stackwright_pro_list_approved_specs",
292
324
  "List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
293
325
  {
294
- configPath: z2.string().optional().describe("Path to stackwright.yml")
326
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
295
327
  },
296
328
  async ({ configPath }) => {
297
329
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
@@ -360,16 +392,18 @@ SHA-256 computed: ${sha256}`
360
392
  }
361
393
 
362
394
  // src/tools/isr.ts
363
- import { z as z3 } from "zod";
395
+ import { z as z4 } from "zod";
364
396
  function registerIsrTools(server2) {
365
397
  server2.tool(
366
398
  "stackwright_pro_configure_isr",
367
399
  "Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
368
400
  {
369
- collection: z3.string().describe('Collection name (e.g., "equipment", "supplies")'),
370
- revalidateSeconds: z3.number().optional().describe("Revalidation interval in seconds (default: 60)"),
371
- fallback: z3.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
372
- configPath: z3.string().optional().describe("Path to stackwright.yml")
401
+ collection: z4.string().describe('Collection name (e.g., "equipment", "supplies")'),
402
+ revalidateSeconds: numCoerce(z4.number().optional()).describe(
403
+ "Revalidation interval in seconds (default: 60)"
404
+ ),
405
+ fallback: z4.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
406
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
373
407
  },
374
408
  async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
375
409
  const revalidate = revalidateSeconds;
@@ -380,7 +414,7 @@ function registerIsrTools(server2) {
380
414
  isr:
381
415
  revalidate: ${revalidate}
382
416
  fallback: ${fallback}`;
383
- let description = "";
417
+ let description;
384
418
  if (revalidate < 60) {
385
419
  description = "\u26A1 Very fresh data (revalidate every " + revalidate + "s)";
386
420
  } else if (revalidate < 300) {
@@ -412,14 +446,16 @@ ${yamlSnippet}
412
446
  "stackwright_pro_configure_isr_batch",
413
447
  "Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
414
448
  {
415
- collections: z3.array(
416
- z3.object({
417
- name: z3.string().describe("Collection name"),
418
- revalidateSeconds: z3.number().optional().describe("Revalidation interval")
419
- })
449
+ collections: jsonCoerce(
450
+ z4.array(
451
+ z4.object({
452
+ name: z4.string().describe("Collection name"),
453
+ revalidateSeconds: numCoerce(z4.number().optional()).describe("Revalidation interval")
454
+ })
455
+ )
420
456
  ).describe("Array of collection configurations"),
421
- defaultFallback: z3.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
422
- configPath: z3.string().optional().describe("Path to stackwright.yml")
457
+ defaultFallback: z4.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
458
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
423
459
  },
424
460
  async ({ collections, defaultFallback = "blocking", configPath }) => {
425
461
  const lines = [`\u2699\uFE0F Batch ISR Configuration:
@@ -447,17 +483,17 @@ Fallback: ${defaultFallback}`);
447
483
  }
448
484
 
449
485
  // src/tools/dashboard.ts
450
- import { z as z4 } from "zod";
486
+ import { z as z5 } from "zod";
451
487
  import { listEntities as listEntities2 } from "@stackwright-pro/cli-data-explorer";
452
488
  function registerDashboardTools(server2) {
453
489
  server2.tool(
454
490
  "stackwright_pro_generate_dashboard",
455
491
  "Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
456
492
  {
457
- entities: z4.array(z4.string()).describe("Entity slugs to include in dashboard"),
458
- layout: z4.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
459
- pageTitle: z4.string().optional().describe("Page title"),
460
- specPath: z4.string().optional().describe("Path to OpenAPI spec for entity details")
493
+ entities: jsonCoerce(z5.array(z5.string())).describe("Entity slugs to include in dashboard"),
494
+ layout: z5.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
495
+ pageTitle: z5.string().optional().describe("Page title"),
496
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for entity details")
461
497
  },
462
498
  async ({ entities, layout = "mixed", pageTitle, specPath }) => {
463
499
  let entityDetails = [];
@@ -543,9 +579,9 @@ ${yaml}
543
579
  "stackwright_pro_generate_detail_page",
544
580
  "Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
545
581
  {
546
- entity: z4.string().describe('Entity slug (e.g., "equipment")'),
547
- slugField: z4.string().optional().describe('Field to use as URL slug (default: "id")'),
548
- specPath: z4.string().optional().describe("Path to OpenAPI spec for field details")
582
+ entity: z5.string().describe('Entity slug (e.g., "equipment")'),
583
+ slugField: z5.string().optional().describe('Field to use as URL slug (default: "id")'),
584
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for field details")
549
585
  },
550
586
  async ({ entity, slugField = "id", specPath }) => {
551
587
  let fields = [];
@@ -568,39 +604,49 @@ ${yaml}
568
604
  ` title: "${entityName} Details | {{ ${entity}.${slugField} }}"`,
569
605
  "",
570
606
  " content_items:",
571
- " - main:",
572
- ' label: "detail-header"',
573
- " heading:",
574
- ` text: "{{ ${entity}.${slugField} }}"`,
575
- ' textSize: "h1"',
576
- " textBlocks:",
577
- ` - text: "Details for this ${entity}"`,
578
- ' textSize: "body1"',
579
- ' background: "primary"',
580
- ' color: "text"',
607
+ " - type: text_block",
608
+ ' label: "detail-header"',
609
+ " heading:",
610
+ ` text: "{{ ${entity}.${slugField} }}"`,
611
+ ' textSize: "h1"',
612
+ " textBlocks:",
613
+ ` - text: "Details for this ${entity}"`,
614
+ ' textSize: "body1"',
581
615
  "",
582
- " - grid:",
583
- ' label: "detail-fields"',
584
- " columns: 2",
585
- " items:"
616
+ " - type: grid",
617
+ ' label: "detail-fields"',
618
+ " columns:"
586
619
  ];
587
620
  const displayFields = fields.length > 0 ? fields.slice(0, 8) : [
588
621
  { name: slugField, type: "string" },
589
622
  { name: "created_at", type: "datetime" },
590
623
  { name: "updated_at", type: "datetime" }
591
624
  ];
592
- for (const field of displayFields) {
593
- const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
594
- yamlLines.push(` - card:`);
595
- yamlLines.push(` label: "${field.name}-field"`);
596
- yamlLines.push(` heading:`);
597
- yamlLines.push(` text: "${label}"`);
598
- yamlLines.push(` textSize: "h4"`);
599
- yamlLines.push(` content:`);
600
- yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
601
- yamlLines.push(` textSize: "body1"`);
602
- }
603
- yamlLines.push(' background: "background"');
625
+ const mid = Math.ceil(displayFields.length / 2);
626
+ const col1 = displayFields.slice(0, mid);
627
+ const col2 = displayFields.slice(mid);
628
+ for (const [colIndex, colFields] of [col1, col2].entries()) {
629
+ yamlLines.push(" - width: 1");
630
+ yamlLines.push(" content_items:");
631
+ for (const field of colFields) {
632
+ const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
633
+ yamlLines.push(" - type: text_block");
634
+ yamlLines.push(` label: "${field.name}-field"`);
635
+ yamlLines.push(" heading:");
636
+ yamlLines.push(` text: "${label}"`);
637
+ yamlLines.push(' textSize: "h4"');
638
+ yamlLines.push(" textBlocks:");
639
+ yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
640
+ yamlLines.push(' textSize: "body1"');
641
+ }
642
+ }
643
+ yamlLines.push("");
644
+ yamlLines.push(" - type: action_bar");
645
+ yamlLines.push(" actions:");
646
+ yamlLines.push(` - label: "<- Back to ${entityName}"`);
647
+ yamlLines.push(" action: navigate");
648
+ yamlLines.push(` href: "/${entity}"`);
649
+ yamlLines.push(" style: secondary");
604
650
  const yaml = yamlLines.join("\n");
605
651
  return {
606
652
  content: [
@@ -621,7 +667,7 @@ ${yaml}
621
667
  }
622
668
 
623
669
  // src/tools/clarification.ts
624
- import { z as z5 } from "zod";
670
+ import { z as z6 } from "zod";
625
671
  var CONTRADICTION_PATTERNS = [
626
672
  {
627
673
  keywords: ["minimal", "clean", "simple"],
@@ -709,12 +755,14 @@ function registerClarificationTools(server2) {
709
755
  "stackwright_pro_clarify",
710
756
  "Ask the user for clarification when a specialist otter encounters ambiguity. This is for MID-EXECUTION questions, NOT upfront question collection (use the Question Manifest Protocol for that). Returns a structured response for the foreman to present to the user via ask_user_question (closed_choice) or directly (open_text).",
711
757
  {
712
- context: z5.string().optional().describe("Context about what the otter is trying to do"),
713
- question_type: z5.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
714
- question: z5.string().describe("The clarification question to ask the user"),
715
- choices: z5.array(z5.string()).optional().describe("Options for closed_choice questions"),
716
- priority: z5.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
717
- target_field: z5.string().optional().describe("What field/config does this clarify?")
758
+ context: z6.string().optional().describe("Context about what the otter is trying to do"),
759
+ question_type: z6.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
760
+ question: z6.string().describe("The clarification question to ask the user"),
761
+ choices: jsonCoerce(z6.array(z6.string()).optional()).describe(
762
+ "Options for closed_choice questions"
763
+ ),
764
+ priority: z6.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
765
+ target_field: z6.string().optional().describe("What field/config does this clarify?")
718
766
  },
719
767
  async ({ context, question_type, question, choices, priority, target_field }) => {
720
768
  const result = handleClarify({
@@ -743,8 +791,10 @@ function registerClarificationTools(server2) {
743
791
  "stackwright_pro_detect_conflict",
744
792
  "Detect when a user's stated preference conflicts with their selected choices. Uses keyword heuristics against known contradiction patterns (minimal vs vibrant, dark vs light, etc). Returns conflict details and resolution options.",
745
793
  {
746
- stated_preference: z5.string().describe("What the user said they wanted"),
747
- selected_values: z5.record(z5.string(), z5.string()).describe("What the user actually selected (field \u2192 value)")
794
+ stated_preference: z6.string().describe("What the user said they wanted"),
795
+ selected_values: jsonCoerce(z6.record(z6.string(), z6.string())).describe(
796
+ "What the user actually selected (field \u2192 value)"
797
+ )
748
798
  },
749
799
  async ({ stated_preference, selected_values }) => {
750
800
  const result = handleDetectConflict({ stated_preference, selected_values });
@@ -789,7 +839,7 @@ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
789
839
  }
790
840
 
791
841
  // src/tools/packages.ts
792
- import { z as z6 } from "zod";
842
+ import { z as z7 } from "zod";
793
843
  import { readFileSync, writeFileSync, existsSync, realpathSync, lstatSync } from "fs";
794
844
  import { execSync } from "child_process";
795
845
  import path2 from "path";
@@ -810,17 +860,23 @@ function registerPackageTools(server2) {
810
860
  "Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run. Pass includeBaseline: true to automatically include all required @stackwright-pro/* baseline dependencies. Safe to call on existing projects \u2014 never overwrites pinned versions.",
811
861
  {
812
862
  // FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
813
- packages: z6.record(z6.string(), z6.string()).describe(
814
- 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
863
+ packages: jsonCoerce(z7.record(z7.string(), z7.string()).optional().default({})).describe(
864
+ 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
865
+ ),
866
+ devPackages: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
867
+ "devDependencies to add. Same format as packages."
815
868
  ),
816
- devPackages: z6.record(z6.string(), z6.string()).optional().describe("devDependencies to add. Same format as packages."),
817
- scripts: z6.record(z6.string(), z6.string()).optional().describe("npm scripts to add. Only adds if key does not already exist."),
818
- targetDir: z6.string().optional().describe(
869
+ scripts: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
870
+ "npm scripts to add. Only adds if key does not already exist."
871
+ ),
872
+ targetDir: z7.string().optional().describe(
819
873
  "Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
820
874
  ),
821
- runInstall: z6.boolean().optional().default(true).describe("Run pnpm install after writing package.json. Defaults to true."),
822
- includeBaseline: z6.boolean().optional().default(false).describe(
823
- "When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions."
875
+ runInstall: boolCoerce(z7.boolean().optional().default(true)).describe(
876
+ "Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
877
+ ),
878
+ includeBaseline: boolCoerce(z7.boolean().optional().default(false)).describe(
879
+ "When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions. Pass boolean true/false."
824
880
  )
825
881
  },
826
882
  async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
@@ -978,11 +1034,11 @@ function setupPackages(opts) {
978
1034
  }
979
1035
  }
980
1036
  const raw = readFileSync(realPackageJsonPath, "utf8");
981
- const PackageJsonSchema = z6.object({
1037
+ const PackageJsonSchema = z7.object({
982
1038
  // Zod v4: z.record(keySchema, valueSchema) — two-arg form required
983
- dependencies: z6.record(z6.string(), z6.string()).optional(),
984
- devDependencies: z6.record(z6.string(), z6.string()).optional(),
985
- scripts: z6.record(z6.string(), z6.string()).optional()
1039
+ dependencies: z7.record(z7.string(), z7.string()).optional(),
1040
+ devDependencies: z7.record(z7.string(), z7.string()).optional(),
1041
+ scripts: z7.record(z7.string(), z7.string()).optional()
986
1042
  }).passthrough();
987
1043
  const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
988
1044
  if (!schemaResult.success) {
@@ -1063,9 +1119,10 @@ function setupPackages(opts) {
1063
1119
  }
1064
1120
 
1065
1121
  // src/tools/questions.ts
1066
- import { readFile } from "fs/promises";
1122
+ import { readFile, writeFile } from "fs/promises";
1123
+ import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync, renameSync } from "fs";
1067
1124
  import { join } from "path";
1068
- import { z as z7 } from "zod";
1125
+ import { z as z8 } from "zod";
1069
1126
 
1070
1127
  // src/question-adapter.ts
1071
1128
  function truncate(str, maxLength) {
@@ -1250,23 +1307,30 @@ function answersToManifestFormat(answers, questions) {
1250
1307
  return result;
1251
1308
  }
1252
1309
 
1310
+ // src/validation.ts
1311
+ var SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1312
+ var SAFE_QUESTION_ID = /^[a-z0-9][a-z0-9-]{0,63}$/i;
1313
+ function isValidPhase(phase) {
1314
+ return SAFE_PHASE.test(phase);
1315
+ }
1316
+
1253
1317
  // src/tools/questions.ts
1254
- var ManifestQuestionSchema = z7.object({
1255
- id: z7.string(),
1256
- question: z7.string(),
1257
- type: z7.enum(["text", "select", "multi-select", "confirm"]),
1258
- required: z7.boolean().optional(),
1259
- options: z7.array(
1260
- z7.object({
1261
- label: z7.string(),
1262
- value: z7.string()
1318
+ var ManifestQuestionSchema = z8.object({
1319
+ id: z8.string(),
1320
+ question: z8.string(),
1321
+ type: z8.enum(["text", "select", "multi-select", "confirm"]),
1322
+ required: z8.boolean().optional(),
1323
+ options: z8.array(
1324
+ z8.object({
1325
+ label: z8.string(),
1326
+ value: z8.string()
1263
1327
  })
1264
1328
  ).optional(),
1265
- default: z7.union([z7.string(), z7.boolean(), z7.array(z7.string())]).optional(),
1266
- help: z7.string().optional(),
1267
- dependsOn: z7.object({
1268
- questionId: z7.string(),
1269
- value: z7.union([z7.string(), z7.array(z7.string())])
1329
+ default: z8.union([z8.string(), z8.boolean(), z8.array(z8.string())]).optional(),
1330
+ help: z8.string().optional(),
1331
+ dependsOn: z8.object({
1332
+ questionId: z8.string(),
1333
+ value: z8.union([z8.string(), z8.array(z8.string())])
1270
1334
  }).optional()
1271
1335
  });
1272
1336
  function registerQuestionTools(server2) {
@@ -1274,15 +1338,16 @@ function registerQuestionTools(server2) {
1274
1338
  "stackwright_pro_present_phase_questions",
1275
1339
  "Adapt manifest-format questions from a specialist otter and present them to the user via ask_user_question. Pass only the phase name \u2014 this tool reads questions from .stackwright/question-manifest.json automatically. The questions parameter is optional and only needed if the manifest has not been written yet. Use this instead of calling ask_user_question directly \u2014 it handles label truncation (50-char limit), header generation, confirm/text defaults, and correct array formatting automatically. IMPORTANT: This is the ONLY approved way to prepare questions before calling ask_user_question. Never call ask_user_question with raw manifest questions. Never retry ask_user_question validation errors by calling it directly \u2014 always re-call this tool.",
1276
1340
  {
1277
- phase: z7.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1278
- questions: z7.array(ManifestQuestionSchema).optional().describe(
1341
+ phase: z8.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1342
+ questions: jsonCoerce(z8.array(ManifestQuestionSchema).optional()).describe(
1279
1343
  "Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
1280
1344
  ),
1281
- answers: z7.record(z7.union([z7.string(), z7.array(z7.string()), z7.boolean()])).optional().describe("Previously collected answers used to resolve dependsOn conditions")
1345
+ answers: jsonCoerce(
1346
+ z8.record(z8.string(), z8.union([z8.string(), z8.array(z8.string()), z8.boolean()])).optional()
1347
+ ).describe("Previously collected answers used to resolve dependsOn conditions")
1282
1348
  },
1283
1349
  async ({ phase, questions, answers }) => {
1284
1350
  let resolvedQuestions;
1285
- const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1286
1351
  if (!SAFE_PHASE.test(phase)) {
1287
1352
  return {
1288
1353
  content: [
@@ -1329,17 +1394,36 @@ function registerQuestionTools(server2) {
1329
1394
  }
1330
1395
  }
1331
1396
  const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
1397
+ const labelSchema = z8.string().max(50, "Value should have at most 50 characters");
1398
+ for (const q of adapted) {
1399
+ for (const opt of q.options) {
1400
+ const check = labelSchema.safeParse(opt.label);
1401
+ if (!check.success) {
1402
+ return {
1403
+ content: [
1404
+ {
1405
+ type: "text",
1406
+ text: JSON.stringify({
1407
+ error: `Option label for phase "${phase}" exceeds 50 characters: ${check.error.issues[0]?.message ?? "label too long"}. Truncate option labels to \u226450 characters before calling this tool.`
1408
+ })
1409
+ }
1410
+ ],
1411
+ isError: true
1412
+ };
1413
+ }
1414
+ }
1415
+ }
1332
1416
  if (adapted.length === 0) {
1333
1417
  return {
1334
1418
  content: [
1335
1419
  {
1336
1420
  type: "text",
1337
- text: JSON.stringify({
1338
- phase,
1339
- skipped: true,
1340
- reason: "No questions to present (all filtered by dependsOn conditions)",
1341
- answers: []
1342
- })
1421
+ text: `Phase "${phase}" has no questions to present. Do NOT call ask_user_question. Call stackwright_pro_save_phase_answers({ phase: "${phase}", rawAnswers: [] }) directly, then proceed to the execution step for this phase.`
1422
+ },
1423
+ {
1424
+ type: "text",
1425
+ // Empty array — second block always present so the foreman's two-block contract holds
1426
+ text: JSON.stringify([])
1343
1427
  }
1344
1428
  ],
1345
1429
  isError: false
@@ -1360,31 +1444,175 @@ function registerQuestionTools(server2) {
1360
1444
  };
1361
1445
  }
1362
1446
  );
1447
+ server2.tool(
1448
+ "stackwright_pro_get_next_question",
1449
+ "Returns the next unanswered question for a phase as a plain JSON object \u2014 one question at a time. Returns { done: true } when all questions are answered or the phase has no questions. Call this in a loop: present the question in plain chat, get user reply, call record_answer, repeat.",
1450
+ { phase: z8.string().describe('Phase name e.g. "designer", "api", "auth"') },
1451
+ async ({ phase }) => {
1452
+ if (!SAFE_PHASE.test(phase)) {
1453
+ return {
1454
+ content: [
1455
+ {
1456
+ type: "text",
1457
+ text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
1458
+ }
1459
+ ],
1460
+ isError: true
1461
+ };
1462
+ }
1463
+ const cwd = process.cwd();
1464
+ const questionsPath = join(cwd, ".stackwright", "questions", `${phase}.json`);
1465
+ let questions = [];
1466
+ try {
1467
+ const raw = await readFile(questionsPath, "utf-8");
1468
+ const parsed = JSON.parse(raw);
1469
+ questions = parsed.questions ?? [];
1470
+ } catch {
1471
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1472
+ }
1473
+ if (questions.length === 0) {
1474
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1475
+ }
1476
+ const answersPath = join(cwd, ".stackwright", "answers", `${phase}.json`);
1477
+ let answeredIds = /* @__PURE__ */ new Set();
1478
+ try {
1479
+ const raw = await readFile(answersPath, "utf-8");
1480
+ const parsed = JSON.parse(raw);
1481
+ answeredIds = new Set(Object.keys(parsed.answers ?? {}));
1482
+ } catch {
1483
+ }
1484
+ const next = questions.find((q) => !answeredIds.has(q.id));
1485
+ if (!next) {
1486
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1487
+ }
1488
+ return {
1489
+ content: [
1490
+ {
1491
+ type: "text",
1492
+ text: JSON.stringify({
1493
+ done: false,
1494
+ questionId: next.id,
1495
+ question: next.question,
1496
+ type: next.type,
1497
+ options: next.options ?? null,
1498
+ help: next.help ?? null,
1499
+ index: questions.indexOf(next) + 1,
1500
+ total: questions.length
1501
+ })
1502
+ }
1503
+ ]
1504
+ };
1505
+ }
1506
+ );
1507
+ server2.tool(
1508
+ "stackwright_pro_record_answer",
1509
+ "Records a single answer to a phase question. Appends to .stackwright/answers/{phase}.json incrementally. Idempotent \u2014 calling twice for the same questionId overwrites. Call after receiving each user reply in the conversational question loop.",
1510
+ {
1511
+ phase: z8.string().describe('Phase name e.g. "designer"'),
1512
+ questionId: z8.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
1513
+ answer: z8.string().describe("The user's free-text answer")
1514
+ },
1515
+ async ({ phase, questionId, answer }) => {
1516
+ if (!SAFE_PHASE.test(phase)) {
1517
+ return {
1518
+ content: [
1519
+ { type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
1520
+ ],
1521
+ isError: true
1522
+ };
1523
+ }
1524
+ if (!SAFE_QUESTION_ID.test(questionId)) {
1525
+ return {
1526
+ content: [
1527
+ { type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
1528
+ ],
1529
+ isError: true
1530
+ };
1531
+ }
1532
+ const safeAnswer = answer.slice(0, 2e3);
1533
+ const cwd = process.cwd();
1534
+ const answersDir = join(cwd, ".stackwright", "answers");
1535
+ const answersPath = join(answersDir, `${phase}.json`);
1536
+ if (existsSync2(answersDir) && lstatSync2(answersDir).isSymbolicLink()) {
1537
+ return {
1538
+ content: [
1539
+ {
1540
+ type: "text",
1541
+ text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
1542
+ }
1543
+ ],
1544
+ isError: true
1545
+ };
1546
+ }
1547
+ mkdirSync(answersDir, { recursive: true });
1548
+ let existing = {
1549
+ version: "1.0",
1550
+ phase,
1551
+ answers: {}
1552
+ };
1553
+ try {
1554
+ if (existsSync2(answersPath)) {
1555
+ if (lstatSync2(answersPath).isSymbolicLink()) {
1556
+ return {
1557
+ content: [
1558
+ {
1559
+ type: "text",
1560
+ text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
1561
+ }
1562
+ ],
1563
+ isError: true
1564
+ };
1565
+ }
1566
+ const raw = await readFile(answersPath, "utf-8");
1567
+ existing = JSON.parse(raw);
1568
+ }
1569
+ } catch {
1570
+ }
1571
+ existing.answers[questionId] = safeAnswer;
1572
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1573
+ const tmp = `${answersPath}.tmp`;
1574
+ await writeFile(tmp, JSON.stringify(existing, null, 2), "utf-8");
1575
+ renameSync(tmp, answersPath);
1576
+ return {
1577
+ content: [
1578
+ { type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
1579
+ ]
1580
+ };
1581
+ }
1582
+ );
1363
1583
  }
1364
1584
 
1365
1585
  // src/tools/orchestration.ts
1366
- import { z as z8 } from "zod";
1367
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync, lstatSync as lstatSync2 } from "fs";
1586
+ import { z as z9 } from "zod";
1587
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1368
1588
  import { join as join2 } from "path";
1369
1589
  var OTTER_NAME_TO_PHASE = [
1370
1590
  ["designer", "designer"],
1371
1591
  ["theme", "theme"],
1592
+ ["scaffold", "scaffold"],
1372
1593
  ["api", "api"],
1373
1594
  ["auth", "auth"],
1374
1595
  ["dashboard", "dashboard"],
1375
1596
  ["data", "data"],
1376
1597
  ["page", "pages"],
1377
- ["workflow", "workflow"]
1598
+ ["workflow", "workflow"],
1599
+ ["services", "services"],
1600
+ ["polish", "polish"],
1601
+ ["geo", "geo"]
1378
1602
  ];
1379
1603
  var PHASE_TO_OTTER = {
1380
1604
  designer: "stackwright-pro-designer-otter",
1381
1605
  theme: "stackwright-pro-theme-otter",
1606
+ scaffold: "stackwright-pro-scaffold-otter",
1382
1607
  api: "stackwright-pro-api-otter",
1383
1608
  auth: "stackwright-pro-auth-otter",
1384
1609
  pages: "stackwright-pro-page-otter",
1385
1610
  dashboard: "stackwright-pro-dashboard-otter",
1386
1611
  data: "stackwright-pro-data-otter",
1387
- workflow: "stackwright-pro-workflow-otter"
1612
+ workflow: "stackwright-pro-workflow-otter",
1613
+ services: "stackwright-services-otter",
1614
+ polish: "stackwright-pro-polish-otter",
1615
+ geo: "stackwright-pro-geo-otter"
1388
1616
  };
1389
1617
  function detectPhase(otterName) {
1390
1618
  const lower = otterName.toLowerCase();
@@ -1420,9 +1648,9 @@ function handleSaveManifest(input) {
1420
1648
  const dir = join2(cwd, ".stackwright");
1421
1649
  const filePath = join2(dir, "question-manifest.json");
1422
1650
  try {
1423
- mkdirSync(dir, { recursive: true });
1424
- if (existsSync2(filePath)) {
1425
- const stat = lstatSync2(filePath);
1651
+ mkdirSync2(dir, { recursive: true });
1652
+ if (existsSync3(filePath)) {
1653
+ const stat = lstatSync3(filePath);
1426
1654
  if (stat.isSymbolicLink()) {
1427
1655
  const message = `Refusing to write to symlink: ${filePath}`;
1428
1656
  return {
@@ -1450,14 +1678,78 @@ function handleSaveManifest(input) {
1450
1678
  }
1451
1679
  }
1452
1680
  function handleSavePhaseAnswers(input) {
1681
+ if (!isValidPhase(input.phase)) {
1682
+ return {
1683
+ text: JSON.stringify({
1684
+ success: false,
1685
+ error: `Invalid phase name: "${input.phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
1686
+ }),
1687
+ isError: true
1688
+ };
1689
+ }
1690
+ for (let i = 0; i < input.rawAnswers.length; i++) {
1691
+ const a = input.rawAnswers[i];
1692
+ if (!a.question_header || a.question_header.trim().length === 0) {
1693
+ return {
1694
+ text: JSON.stringify({
1695
+ success: false,
1696
+ error: `rawAnswers[${i}].question_header is empty \u2014 every answer must have a non-empty question_header.`
1697
+ }),
1698
+ isError: true
1699
+ };
1700
+ }
1701
+ if (!a.selected_options || a.selected_options.length === 0) {
1702
+ return {
1703
+ text: JSON.stringify({
1704
+ success: false,
1705
+ error: `rawAnswers[${i}].selected_options is empty for question_header "${a.question_header}" \u2014 every answer must have at least one selected option.`
1706
+ }),
1707
+ isError: true
1708
+ };
1709
+ }
1710
+ }
1711
+ if (input.questions && input.questions.length > 0 && input.rawAnswers.length === 0) {
1712
+ return {
1713
+ text: JSON.stringify({
1714
+ success: false,
1715
+ error: `${input.questions.length} questions provided but rawAnswers is empty \u2014 this is a malformed payload. If the phase truly has no questions, omit the questions parameter.`
1716
+ }),
1717
+ isError: true
1718
+ };
1719
+ }
1453
1720
  const cwd = input._cwd ?? process.cwd();
1454
1721
  const dir = join2(cwd, ".stackwright", "answers");
1455
1722
  const filePath = join2(dir, `${input.phase}.json`);
1456
1723
  try {
1457
- mkdirSync(dir, { recursive: true });
1724
+ mkdirSync2(dir, { recursive: true });
1725
+ const warnings = [];
1458
1726
  let answers;
1459
1727
  if (input.questions && input.questions.length > 0) {
1460
- answers = answersToManifestFormat(input.rawAnswers, input.questions);
1728
+ try {
1729
+ answers = answersToManifestFormat(input.rawAnswers, input.questions);
1730
+ } catch (mapErr) {
1731
+ answers = {};
1732
+ warnings.push(
1733
+ `Reverse-mapping threw (${mapErr instanceof Error ? mapErr.message : String(mapErr)}) \u2014 falling back to direct key mapping.`
1734
+ );
1735
+ }
1736
+ if (Object.keys(answers).length === 0 && input.rawAnswers.length > 0) {
1737
+ answers = Object.fromEntries(
1738
+ input.rawAnswers.map((a) => [
1739
+ a.question_header,
1740
+ a.selected_options.length > 1 ? a.selected_options : a.selected_options[0] ?? ""
1741
+ ])
1742
+ );
1743
+ warnings.push(
1744
+ `Reverse-mapping produced empty answers despite ${input.rawAnswers.length} rawAnswers \u2014 used direct key mapping as fallback. Ensure question_header values match the manifest header format (e.g. "DESI-1", not descriptive keys).`
1745
+ );
1746
+ }
1747
+ const requiredCount = input.questions.filter((q) => q.required !== false).length;
1748
+ if (input.rawAnswers.length < requiredCount) {
1749
+ warnings.push(
1750
+ `Only ${input.rawAnswers.length} answers provided for ${requiredCount} required questions (${input.questions.length} total) \u2014 answers may be incomplete.`
1751
+ );
1752
+ }
1461
1753
  } else {
1462
1754
  answers = Object.fromEntries(
1463
1755
  input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
@@ -1469,8 +1761,8 @@ function handleSavePhaseAnswers(input) {
1469
1761
  completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1470
1762
  answers
1471
1763
  };
1472
- if (existsSync2(filePath)) {
1473
- const stat = lstatSync2(filePath);
1764
+ if (existsSync3(filePath)) {
1765
+ const stat = lstatSync3(filePath);
1474
1766
  if (stat.isSymbolicLink()) {
1475
1767
  const message = `Refusing to write to symlink: ${filePath}`;
1476
1768
  return {
@@ -1484,7 +1776,8 @@ function handleSavePhaseAnswers(input) {
1484
1776
  text: JSON.stringify({
1485
1777
  success: true,
1486
1778
  path: filePath,
1487
- answersCount: Object.keys(answers).length
1779
+ answersCount: Object.keys(answers).length,
1780
+ ...warnings.length > 0 ? { warnings } : {}
1488
1781
  }),
1489
1782
  isError: false
1490
1783
  };
@@ -1499,7 +1792,7 @@ function handleSavePhaseAnswers(input) {
1499
1792
  function handleReadPhaseAnswers(input) {
1500
1793
  const cwd = input._cwd ?? process.cwd();
1501
1794
  const filePath = join2(cwd, ".stackwright", "answers", `${input.phase}.json`);
1502
- if (!existsSync2(filePath)) {
1795
+ if (!existsSync3(filePath)) {
1503
1796
  return {
1504
1797
  text: JSON.stringify({ missing: true, phase: input.phase }),
1505
1798
  isError: false
@@ -1531,13 +1824,63 @@ function handleGetOtterName(input) {
1531
1824
  isError: false
1532
1825
  };
1533
1826
  }
1827
+ function handleSaveBuildContext(input) {
1828
+ const cwd = input._cwd ?? process.cwd();
1829
+ const dir = join2(cwd, ".stackwright");
1830
+ const filePath = join2(dir, "build-context.json");
1831
+ try {
1832
+ mkdirSync2(dir, { recursive: true });
1833
+ if (existsSync3(filePath)) {
1834
+ const stat = lstatSync3(filePath);
1835
+ if (stat.isSymbolicLink()) {
1836
+ return {
1837
+ text: JSON.stringify({
1838
+ success: false,
1839
+ error: `Refusing to write to symlink: ${filePath}`
1840
+ }),
1841
+ isError: true
1842
+ };
1843
+ }
1844
+ }
1845
+ const payload = {
1846
+ version: "1.0",
1847
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1848
+ buildContext: input.buildContext
1849
+ };
1850
+ writeFileSync2(filePath, JSON.stringify(payload, null, 2) + "\n");
1851
+ return {
1852
+ text: JSON.stringify({ success: true, path: filePath }),
1853
+ isError: false
1854
+ };
1855
+ } catch (err) {
1856
+ const message = err instanceof Error ? err.message : String(err);
1857
+ return {
1858
+ text: JSON.stringify({ success: false, error: message }),
1859
+ isError: true
1860
+ };
1861
+ }
1862
+ }
1534
1863
  function registerOrchestrationTools(server2) {
1864
+ server2.tool(
1865
+ "stackwright_pro_save_build_context",
1866
+ `Save the user's initial build description to .stackwright/build-context.json. Call this once at startup after the user answers the opening "what are you building" question. The saved context is automatically prepended to specialist prompts by stackwright_pro_build_specialist_prompt.`,
1867
+ {
1868
+ buildContext: z9.string().describe("Free-text description of what the user wants to build")
1869
+ },
1870
+ async ({ buildContext }) => {
1871
+ const { text, isError } = handleSaveBuildContext({ buildContext });
1872
+ return {
1873
+ content: [{ type: "text", text }],
1874
+ isError
1875
+ };
1876
+ }
1877
+ );
1535
1878
  server2.tool(
1536
1879
  "stackwright_pro_parse_otter_response",
1537
1880
  "Parse and validate a specialist otter's QUESTION_COLLECTION_MODE JSON response. Handles JSON extraction from LLM responses (strips markdown, fixes single quotes, trailing commas). Detects the phase from the otter name. Use this immediately after invoke_agent() to get a validated manifest phase object.",
1538
1881
  {
1539
- otterName: z8.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1540
- responseText: z8.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1882
+ otterName: z9.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1883
+ responseText: z9.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1541
1884
  },
1542
1885
  async ({ otterName, responseText }) => {
1543
1886
  const { result, isError } = handleParseOtterResponse({ otterName, responseText });
@@ -1551,16 +1894,18 @@ function registerOrchestrationTools(server2) {
1551
1894
  "stackwright_pro_save_manifest",
1552
1895
  "Write the question manifest to .stackwright/question-manifest.json. Call this after collecting and parsing questions from all otters via stackwright_pro_parse_otter_response.",
1553
1896
  {
1554
- phases: z8.array(
1555
- z8.object({
1556
- phase: z8.string(),
1557
- otter: z8.string(),
1558
- questions: z8.array(z8.any()),
1559
- requiredPackages: z8.object({
1560
- dependencies: z8.record(z8.string(), z8.string()).optional(),
1561
- devPackages: z8.record(z8.string(), z8.string()).optional()
1562
- }).optional()
1563
- })
1897
+ phases: jsonCoerce(
1898
+ z9.array(
1899
+ z9.object({
1900
+ phase: z9.string(),
1901
+ otter: z9.string(),
1902
+ questions: z9.array(z9.any()),
1903
+ requiredPackages: z9.object({
1904
+ dependencies: z9.record(z9.string(), z9.string()).optional(),
1905
+ devPackages: z9.record(z9.string(), z9.string()).optional()
1906
+ }).optional()
1907
+ })
1908
+ )
1564
1909
  ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1565
1910
  },
1566
1911
  async ({ phases }) => {
@@ -1575,15 +1920,37 @@ function registerOrchestrationTools(server2) {
1575
1920
  "stackwright_pro_save_phase_answers",
1576
1921
  "Save user answers for a phase to .stackwright/answers/{phase}.json. Pass rawAnswers directly from ask_user_question and the original manifest questions for label-to-value reverse mapping.",
1577
1922
  {
1578
- phase: z8.string().describe('Phase name, e.g. "designer"'),
1579
- rawAnswers: z8.array(
1580
- z8.object({
1581
- question_header: z8.string(),
1582
- selected_options: z8.array(z8.string()),
1583
- other_text: z8.string().nullable().optional()
1584
- })
1585
- ).describe("Answers as returned by ask_user_question"),
1586
- questions: z8.array(z8.any()).optional().describe("Original manifest questions for label\u2192value reverse-mapping")
1923
+ phase: z9.string().describe('Phase name, e.g. "designer"'),
1924
+ rawAnswers: jsonCoerce(
1925
+ z9.array(
1926
+ z9.object({
1927
+ question_header: z9.string().min(1, "question_header must not be empty"),
1928
+ selected_options: z9.array(z9.string()).min(1, "selected_options must have at least one entry"),
1929
+ other_text: z9.string().nullable().optional()
1930
+ })
1931
+ )
1932
+ ).describe(
1933
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1934
+ ),
1935
+ questions: jsonCoerce(
1936
+ z9.array(
1937
+ z9.object({
1938
+ id: z9.string(),
1939
+ question: z9.string(),
1940
+ type: z9.string(),
1941
+ options: z9.array(z9.object({ label: z9.string(), value: z9.string() })).optional(),
1942
+ required: z9.boolean().optional(),
1943
+ default: z9.union([z9.string(), z9.boolean(), z9.array(z9.string())]).optional(),
1944
+ help: z9.string().optional(),
1945
+ dependsOn: z9.object({
1946
+ questionId: z9.string(),
1947
+ value: z9.union([z9.string(), z9.array(z9.string())])
1948
+ }).optional()
1949
+ }).passthrough()
1950
+ ).optional()
1951
+ ).describe(
1952
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1953
+ )
1587
1954
  },
1588
1955
  async ({ phase, rawAnswers, questions }) => {
1589
1956
  const { text, isError } = handleSavePhaseAnswers({
@@ -1601,7 +1968,7 @@ function registerOrchestrationTools(server2) {
1601
1968
  "stackwright_pro_read_phase_answers",
1602
1969
  "Read saved answers for a phase from .stackwright/answers/{phase}.json. Returns { missing: true } when no answers exist yet \u2014 use this to skip phases safely in the execution loop.",
1603
1970
  {
1604
- phase: z8.string().describe('Phase name, e.g. "designer"')
1971
+ phase: z9.string().describe('Phase name, e.g. "designer"')
1605
1972
  },
1606
1973
  async ({ phase }) => {
1607
1974
  const { text, isError } = handleReadPhaseAnswers({ phase });
@@ -1615,7 +1982,7 @@ function registerOrchestrationTools(server2) {
1615
1982
  "stackwright_pro_get_otter_name",
1616
1983
  "Get the agent name for a phase (e.g. 'designer' \u2192 'stackwright-pro-designer-otter'). Use this in the execution loop to invoke the correct specialist otter without hardcoding names in the prompt.",
1617
1984
  {
1618
- phase: z8.string().describe('Phase name, e.g. "designer", "api", "pages"')
1985
+ phase: z9.string().describe('Phase name, e.g. "designer", "api", "pages"')
1619
1986
  },
1620
1987
  async ({ phase }) => {
1621
1988
  const { text, isError } = handleGetOtterName({ phase });
@@ -1628,53 +1995,777 @@ function registerOrchestrationTools(server2) {
1628
1995
  }
1629
1996
 
1630
1997
  // src/tools/pipeline.ts
1631
- import { z as z9 } from "zod";
1632
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1998
+ import { z as z13 } from "zod";
1999
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync4, existsSync as existsSync5, mkdirSync as mkdirSync4, lstatSync as lstatSync5 } from "fs";
2000
+ import { join as join4 } from "path";
2001
+ import { createHash as createHash3 } from "crypto";
2002
+
2003
+ // src/artifact-signing.ts
2004
+ import {
2005
+ createHash as createHash2,
2006
+ generateKeyPairSync,
2007
+ createPublicKey,
2008
+ createPrivateKey,
2009
+ sign,
2010
+ verify,
2011
+ timingSafeEqual
2012
+ } from "crypto";
2013
+ import {
2014
+ readFileSync as readFileSync3,
2015
+ writeFileSync as writeFileSync3,
2016
+ existsSync as existsSync4,
2017
+ mkdirSync as mkdirSync3,
2018
+ lstatSync as lstatSync4,
2019
+ unlinkSync,
2020
+ readdirSync
2021
+ } from "fs";
1633
2022
  import { join as join3 } from "path";
1634
- var PHASE_ORDER = [
1635
- "designer",
1636
- "theme",
1637
- "api",
1638
- "auth",
1639
- "data",
1640
- "pages",
1641
- "dashboard",
1642
- "workflow"
1643
- ];
1644
- var PHASE_DEPENDENCIES = {
1645
- designer: [],
1646
- theme: ["designer"],
1647
- api: [],
1648
- auth: [],
1649
- data: ["api"],
1650
- pages: ["designer", "theme", "api", "data", "auth"],
1651
- dashboard: ["designer", "theme", "api", "data"],
1652
- workflow: ["auth"]
1653
- };
1654
- var PHASE_ARTIFACT = {
1655
- designer: "design-language.json",
1656
- theme: "theme-tokens.json",
1657
- api: "api-config.json",
1658
- auth: "auth-config.json",
1659
- data: "data-config.json",
1660
- pages: "pages-manifest.json",
1661
- dashboard: "dashboard-manifest.json",
1662
- workflow: "workflow-config.json"
1663
- };
1664
- var PHASE_TO_OTTER2 = {
1665
- designer: "stackwright-pro-designer-otter",
1666
- theme: "stackwright-pro-theme-otter",
1667
- api: "stackwright-pro-api-otter",
1668
- auth: "stackwright-pro-auth-otter",
1669
- data: "stackwright-pro-data-otter",
1670
- pages: "stackwright-pro-page-otter",
1671
- dashboard: "stackwright-pro-dashboard-otter",
1672
- workflow: "stackwright-pro-workflow-otter"
1673
- };
1674
- function isValidPhase(phase) {
1675
- return PHASE_ORDER.includes(phase);
1676
- }
1677
- function defaultPhaseStatus() {
2023
+ import { z as z10 } from "zod";
2024
+ var ALGORITHM = "ECDSA-P384-SHA384";
2025
+ var KEY_FILE = "pipeline-keys.json";
2026
+ var KEY_DIR = ".stackwright";
2027
+ var SIGNATURE_MANIFEST = "signatures.json";
2028
+ var ARTIFACTS_DIR = ".stackwright/artifacts";
2029
+ function rejectSymlink(filePath, context) {
2030
+ if (!existsSync4(filePath)) return;
2031
+ const stat = lstatSync4(filePath);
2032
+ if (stat.isSymbolicLink()) {
2033
+ throw new Error(`Security: refusing to follow symlink at ${context}: ${filePath}`);
2034
+ }
2035
+ }
2036
+ function computeSha384(data) {
2037
+ return createHash2("sha384").update(data).digest("hex");
2038
+ }
2039
+ function safeDigestEqual(a, b) {
2040
+ if (a.length !== b.length) return false;
2041
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2042
+ }
2043
+ function emptyManifest() {
2044
+ return {
2045
+ version: "1.0",
2046
+ algorithm: ALGORITHM,
2047
+ signatures: {}
2048
+ };
2049
+ }
2050
+ function initPipelineKeys(cwd) {
2051
+ const keyDir = join3(cwd, KEY_DIR);
2052
+ const keyPath = join3(keyDir, KEY_FILE);
2053
+ rejectSymlink(keyPath, "pipeline-keys.json");
2054
+ mkdirSync3(keyDir, { recursive: true });
2055
+ const { publicKey, privateKey } = generateKeyPairSync("ec", {
2056
+ namedCurve: "P-384"
2057
+ });
2058
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
2059
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
2060
+ const fingerprint = createHash2("sha256").update(publicKeyPem).digest("hex");
2061
+ const keyFile = {
2062
+ version: "1.0",
2063
+ algorithm: ALGORITHM,
2064
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2065
+ publicKeyPem,
2066
+ privateKeyPem
2067
+ };
2068
+ writeFileSync3(keyPath, JSON.stringify(keyFile, null, 2), { encoding: "utf-8" });
2069
+ return { publicKeyPem, fingerprint };
2070
+ }
2071
+ function loadPipelineKeys(cwd) {
2072
+ const keyPath = join3(cwd, KEY_DIR, KEY_FILE);
2073
+ rejectSymlink(keyPath, "pipeline-keys.json");
2074
+ if (!existsSync4(keyPath)) {
2075
+ throw new Error("Pipeline keys not found \u2014 call initPipelineKeys() first");
2076
+ }
2077
+ let raw;
2078
+ try {
2079
+ raw = readFileSync3(keyPath, "utf-8");
2080
+ } catch (err) {
2081
+ const msg = err instanceof Error ? err.message : String(err);
2082
+ throw new Error(`Cannot read pipeline keys: ${msg}`, { cause: err });
2083
+ }
2084
+ let parsed;
2085
+ try {
2086
+ parsed = JSON.parse(raw);
2087
+ } catch {
2088
+ throw new Error("Pipeline keys file is not valid JSON");
2089
+ }
2090
+ if (typeof parsed.publicKeyPem !== "string" || !parsed.publicKeyPem.includes("-----BEGIN PUBLIC KEY-----")) {
2091
+ throw new Error("Invalid public key PEM in pipeline keys file");
2092
+ }
2093
+ if (typeof parsed.privateKeyPem !== "string" || !parsed.privateKeyPem.includes("-----BEGIN")) {
2094
+ throw new Error("Invalid private key PEM in pipeline keys file");
2095
+ }
2096
+ const publicKey = createPublicKey(parsed.publicKeyPem);
2097
+ const privateKey = createPrivateKey(parsed.privateKeyPem);
2098
+ return { privateKey, publicKey };
2099
+ }
2100
+ function signArtifact(artifactBytes, privateKey) {
2101
+ const digest = computeSha384(artifactBytes);
2102
+ const sig = sign("SHA384", artifactBytes, privateKey);
2103
+ return {
2104
+ digest,
2105
+ signature: sig.toString("base64"),
2106
+ algorithm: ALGORITHM,
2107
+ signedAt: (/* @__PURE__ */ new Date()).toISOString()
2108
+ };
2109
+ }
2110
+ function verifyArtifact(artifactBytes, signature, publicKey) {
2111
+ const sigValid = verify(
2112
+ "SHA384",
2113
+ artifactBytes,
2114
+ publicKey,
2115
+ Buffer.from(signature.signature, "base64")
2116
+ );
2117
+ if (!sigValid) return false;
2118
+ const actualDigest = computeSha384(artifactBytes);
2119
+ return safeDigestEqual(actualDigest, signature.digest);
2120
+ }
2121
+ function loadSignatureManifest(cwd) {
2122
+ const manifestPath = join3(cwd, ARTIFACTS_DIR, SIGNATURE_MANIFEST);
2123
+ rejectSymlink(manifestPath, "signatures.json");
2124
+ if (!existsSync4(manifestPath)) return emptyManifest();
2125
+ let raw;
2126
+ try {
2127
+ raw = readFileSync3(manifestPath, "utf-8");
2128
+ } catch (err) {
2129
+ const msg = err instanceof Error ? err.message : String(err);
2130
+ throw new Error(`Cannot read signature manifest: ${msg}`, { cause: err });
2131
+ }
2132
+ try {
2133
+ const parsed = JSON.parse(raw);
2134
+ if (parsed.version !== "1.0" || typeof parsed.signatures !== "object") {
2135
+ throw new Error("Malformed signature manifest: invalid version or missing signatures object");
2136
+ }
2137
+ return parsed;
2138
+ } catch (err) {
2139
+ if (err instanceof Error && err.message.startsWith("Malformed")) throw err;
2140
+ throw new Error("Signature manifest is not valid JSON", { cause: err });
2141
+ }
2142
+ }
2143
+ function saveArtifactSignature(cwd, artifactFilename, sig, signerOtter) {
2144
+ const artifactsDir = join3(cwd, ARTIFACTS_DIR);
2145
+ const manifestPath = join3(artifactsDir, SIGNATURE_MANIFEST);
2146
+ rejectSymlink(manifestPath, "signatures.json (save)");
2147
+ mkdirSync3(artifactsDir, { recursive: true });
2148
+ const manifest = loadSignatureManifest(cwd);
2149
+ manifest.signatures[artifactFilename] = {
2150
+ ...sig,
2151
+ signedBy: signerOtter
2152
+ };
2153
+ writeFileSync3(manifestPath, JSON.stringify(manifest, null, 2), { encoding: "utf-8" });
2154
+ }
2155
+ function getArtifactSignature(cwd, artifactFilename) {
2156
+ const manifest = loadSignatureManifest(cwd);
2157
+ const entry = manifest.signatures[artifactFilename];
2158
+ if (!entry) return null;
2159
+ return {
2160
+ digest: entry.digest,
2161
+ signature: entry.signature,
2162
+ algorithm: entry.algorithm,
2163
+ signedAt: entry.signedAt
2164
+ };
2165
+ }
2166
+ function emitSignatureAuditEvent(params) {
2167
+ const record = JSON.stringify({
2168
+ level: "AUDIT",
2169
+ event: "ARTIFACT_SIGNATURE_FAIL",
2170
+ timestamp: params.timestamp,
2171
+ source: params.source,
2172
+ artifactFilename: params.artifactFilename,
2173
+ expectedDigest: params.expectedDigest,
2174
+ actualDigest: params.actualDigest,
2175
+ phase: params.phase
2176
+ });
2177
+ process.stderr.write(`ARTIFACT_SIGNATURE_FAIL ${record}
2178
+ `);
2179
+ }
2180
+ function registerArtifactSigningTools(server2) {
2181
+ server2.tool(
2182
+ "stackwright_pro_verify_artifact_signatures",
2183
+ "Verify ECDSA P-384 signatures for all pipeline artifacts in .stackwright/artifacts/. Auto-discovers keys from .stackwright/pipeline-keys.json. Returns per-artifact verification status.",
2184
+ {
2185
+ cwd: z10.string().optional().describe("Project root directory. Defaults to process.cwd().")
2186
+ },
2187
+ async ({ cwd: cwdParam }) => {
2188
+ const cwd = cwdParam ?? process.cwd();
2189
+ let publicKey;
2190
+ try {
2191
+ const keys = loadPipelineKeys(cwd);
2192
+ publicKey = keys.publicKey;
2193
+ } catch (err) {
2194
+ const msg = err instanceof Error ? err.message : String(err);
2195
+ return {
2196
+ content: [
2197
+ {
2198
+ type: "text",
2199
+ text: JSON.stringify({
2200
+ error: true,
2201
+ message: `Cannot load pipeline keys: ${msg}`
2202
+ })
2203
+ }
2204
+ ],
2205
+ isError: true
2206
+ };
2207
+ }
2208
+ let manifest;
2209
+ try {
2210
+ manifest = loadSignatureManifest(cwd);
2211
+ } catch (err) {
2212
+ const msg = err instanceof Error ? err.message : String(err);
2213
+ return {
2214
+ content: [
2215
+ {
2216
+ type: "text",
2217
+ text: JSON.stringify({
2218
+ error: true,
2219
+ message: `Cannot load signature manifest: ${msg}`
2220
+ })
2221
+ }
2222
+ ],
2223
+ isError: true
2224
+ };
2225
+ }
2226
+ const artifactsPath = join3(cwd, ARTIFACTS_DIR);
2227
+ let artifactFiles = [];
2228
+ try {
2229
+ if (existsSync4(artifactsPath)) {
2230
+ artifactFiles = readdirSync(artifactsPath).filter(
2231
+ (f) => f.endsWith(".json") && f !== SIGNATURE_MANIFEST
2232
+ );
2233
+ }
2234
+ } catch {
2235
+ }
2236
+ const results = [];
2237
+ let hasFailure = false;
2238
+ for (const filename of artifactFiles) {
2239
+ const filePath = join3(artifactsPath, filename);
2240
+ try {
2241
+ rejectSymlink(filePath, `artifact ${filename}`);
2242
+ } catch {
2243
+ results.push({
2244
+ filename,
2245
+ verified: false,
2246
+ error: "Refusing to verify symlink"
2247
+ });
2248
+ hasFailure = true;
2249
+ continue;
2250
+ }
2251
+ let artifactBytes;
2252
+ try {
2253
+ artifactBytes = readFileSync3(filePath);
2254
+ } catch (err) {
2255
+ const msg = err instanceof Error ? err.message : String(err);
2256
+ results.push({
2257
+ filename,
2258
+ verified: false,
2259
+ error: `Cannot read artifact: ${msg}`
2260
+ });
2261
+ hasFailure = true;
2262
+ continue;
2263
+ }
2264
+ const entry = manifest.signatures[filename];
2265
+ if (!entry) {
2266
+ results.push({
2267
+ filename,
2268
+ verified: false,
2269
+ error: "No signature found in manifest"
2270
+ });
2271
+ hasFailure = true;
2272
+ continue;
2273
+ }
2274
+ const sig = {
2275
+ digest: entry.digest,
2276
+ signature: entry.signature,
2277
+ algorithm: entry.algorithm,
2278
+ signedAt: entry.signedAt
2279
+ };
2280
+ const verified = verifyArtifact(artifactBytes, sig, publicKey);
2281
+ if (!verified) {
2282
+ const actualDigest = computeSha384(artifactBytes);
2283
+ emitSignatureAuditEvent({
2284
+ artifactFilename: filename,
2285
+ expectedDigest: sig.digest,
2286
+ actualDigest,
2287
+ phase: entry.signedBy ?? "unknown",
2288
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2289
+ source: "stackwright_pro_verify_artifact_signatures"
2290
+ });
2291
+ results.push({
2292
+ filename,
2293
+ verified: false,
2294
+ error: `Signature verification failed \u2014 artifact may have been tampered with`,
2295
+ signedBy: entry.signedBy,
2296
+ signedAt: entry.signedAt
2297
+ });
2298
+ hasFailure = true;
2299
+ } else {
2300
+ results.push({
2301
+ filename,
2302
+ verified: true,
2303
+ signedBy: entry.signedBy,
2304
+ signedAt: entry.signedAt
2305
+ });
2306
+ }
2307
+ }
2308
+ for (const manifestFilename of Object.keys(manifest.signatures)) {
2309
+ if (!artifactFiles.includes(manifestFilename)) {
2310
+ results.push({
2311
+ filename: manifestFilename,
2312
+ verified: false,
2313
+ error: "Artifact referenced in manifest but missing from disk"
2314
+ });
2315
+ hasFailure = true;
2316
+ }
2317
+ }
2318
+ const verifiedCount = results.filter((r) => r.verified).length;
2319
+ const failedCount = results.filter((r) => !r.verified).length;
2320
+ return {
2321
+ content: [
2322
+ {
2323
+ type: "text",
2324
+ text: JSON.stringify({
2325
+ totalArtifacts: artifactFiles.length,
2326
+ verifiedCount,
2327
+ failedCount,
2328
+ results,
2329
+ ...hasFailure ? {
2330
+ error: "SIGNATURE VERIFICATION FAILED: One or more artifact signatures are invalid. Do not proceed \u2014 artifacts may have been tampered with."
2331
+ } : {}
2332
+ })
2333
+ }
2334
+ ],
2335
+ isError: hasFailure
2336
+ };
2337
+ }
2338
+ );
2339
+ }
2340
+
2341
+ // src/tools/pipeline.ts
2342
+ import { WorkflowFileSchema, authConfigSchema as authConfigSchema3 } from "@stackwright-pro/types";
2343
+
2344
+ // src/tools/get-schema.ts
2345
+ import { z as z12 } from "zod";
2346
+ import {
2347
+ WorkflowStepSchema as WorkflowStepSchema2,
2348
+ WorkflowDefinitionSchema as WorkflowDefinitionSchema2,
2349
+ WorkflowFieldSchema as WorkflowFieldSchema2,
2350
+ WorkflowActionSchema as WorkflowActionSchema2,
2351
+ authConfigSchema as authConfigSchema2
2352
+ } from "@stackwright-pro/types";
2353
+
2354
+ // src/tools/validate-yaml-fragment.ts
2355
+ import { z as z11 } from "zod";
2356
+ import { load as yamlLoad } from "js-yaml";
2357
+ import {
2358
+ WorkflowStepSchema,
2359
+ WorkflowDefinitionSchema,
2360
+ WorkflowFieldSchema,
2361
+ WorkflowActionSchema,
2362
+ authConfigSchema
2363
+ } from "@stackwright-pro/types";
2364
+ var SUPPORTED_SCHEMA_NAMES = [
2365
+ "workflow_step",
2366
+ "workflow_definition",
2367
+ "workflow_field",
2368
+ "workflow_action",
2369
+ "navigation_item",
2370
+ "auth_config"
2371
+ ];
2372
+ var NavigationLinkSchema = z11.lazy(
2373
+ () => z11.object({
2374
+ label: z11.string().min(1),
2375
+ href: z11.string().min(1),
2376
+ children: z11.array(NavigationLinkSchema).optional()
2377
+ })
2378
+ );
2379
+ var NavigationSectionSchema = z11.object({
2380
+ section: z11.string().min(1),
2381
+ items: z11.array(NavigationLinkSchema)
2382
+ });
2383
+ var NavigationItemSchema = z11.union([
2384
+ NavigationLinkSchema,
2385
+ NavigationSectionSchema
2386
+ ]);
2387
+ var FIELD_SYNONYMS = {
2388
+ workflow_step: {
2389
+ title: "label",
2390
+ name: "label (at step level, use label: not name:)",
2391
+ description: "message (use message: for step-level descriptive text)",
2392
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2393
+ transitions: 'on_submit.transition \u2014 use on_submit: { transition: "next_step" } not transitions: [{then:...}]'
2394
+ },
2395
+ workflow_definition: {
2396
+ title: "label",
2397
+ name: "label (workflow-level label, not name:)",
2398
+ description: "description is valid here \u2014 but message: is not (that is a step field)",
2399
+ type: "id (workflows are identified by id:, not type:)"
2400
+ },
2401
+ workflow_field: {
2402
+ id: "name (field-level identifier is name:, NOT id:)",
2403
+ title: "label (field display text is label:, NOT title:)",
2404
+ description: "placeholder or label (no description field on WorkflowField)"
2405
+ },
2406
+ workflow_action: {
2407
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2408
+ then: "transition (action-level next-step is transition:, NOT then:)",
2409
+ on_click: 'action: "service:..." (extract the service reference from on_click.action)',
2410
+ title: "label (action display text is label:, NOT title:)",
2411
+ name: "label (action display text is label:, NOT name:)"
2412
+ },
2413
+ navigation_item: {
2414
+ children: "items (NavigationSection uses items: not children: \u2014 also use section: instead of label: for section headers)",
2415
+ label: 'section (if this is a nav group/section, use section: "Title" and items: [...], not label:)',
2416
+ title: "section (NavigationSection header field is section:, NOT title:)"
2417
+ },
2418
+ auth_config: {
2419
+ method: 'type \u2014 auth config discriminates on type: "oidc" | "pki", NOT method:',
2420
+ provider_type: 'type \u2014 use type: "oidc" or type: "pki"',
2421
+ strategy: "type \u2014 top-level discriminator is type:, not strategy:"
2422
+ }
2423
+ };
2424
+ function getSchema(name) {
2425
+ switch (name) {
2426
+ case "workflow_step":
2427
+ return WorkflowStepSchema;
2428
+ case "workflow_definition":
2429
+ return WorkflowDefinitionSchema;
2430
+ case "workflow_field":
2431
+ return WorkflowFieldSchema;
2432
+ case "workflow_action":
2433
+ return WorkflowActionSchema;
2434
+ case "navigation_item":
2435
+ return NavigationItemSchema;
2436
+ case "auth_config":
2437
+ return authConfigSchema;
2438
+ }
2439
+ }
2440
+ function enrichErrors(issues, synonyms) {
2441
+ return issues.map((issue) => {
2442
+ const pathStr = issue.path.join(".");
2443
+ const lastSegment = issue.path[issue.path.length - 1];
2444
+ const fieldName = typeof lastSegment === "string" ? lastSegment : void 0;
2445
+ const didYouMean = fieldName ? synonyms[fieldName] : void 0;
2446
+ return {
2447
+ path: pathStr || "(root)",
2448
+ message: issue.message,
2449
+ ...didYouMean ? { didYouMean } : {}
2450
+ };
2451
+ });
2452
+ }
2453
+ function handleValidateYamlFragment(input) {
2454
+ const { schemaName, yaml } = input;
2455
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2456
+ return {
2457
+ valid: false,
2458
+ parseError: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2459
+ };
2460
+ }
2461
+ const name = schemaName;
2462
+ let parsed;
2463
+ try {
2464
+ parsed = yamlLoad(yaml);
2465
+ } catch (err) {
2466
+ return {
2467
+ valid: false,
2468
+ parseError: `YAML parse error: ${err instanceof Error ? err.message : String(err)}`
2469
+ };
2470
+ }
2471
+ const schema = getSchema(name);
2472
+ const result = schema.safeParse(parsed);
2473
+ if (result.success) {
2474
+ return { valid: true };
2475
+ }
2476
+ const synonyms = FIELD_SYNONYMS[name];
2477
+ const errors = enrichErrors(result.error.issues, synonyms);
2478
+ return { valid: false, errors };
2479
+ }
2480
+ function registerValidateYamlFragmentTool(server2) {
2481
+ server2.tool(
2482
+ "stackwright_pro_validate_yaml_fragment",
2483
+ 'Validates a YAML snippet against a canonical Zod schema before writing to disk. Returns actionable errors with "did you mean?" suggestions for common field-name drift (title vs label, id vs name, style vs theme.variant, etc.). Call this before stackwright_pro_safe_write to catch schema violations in-session.',
2484
+ {
2485
+ schemaName: z11.enum(SUPPORTED_SCHEMA_NAMES).describe(
2486
+ "Schema to validate against. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2487
+ ),
2488
+ yaml: z11.string().describe("YAML string to validate (can also be JSON \u2014 js-yaml parses both)")
2489
+ },
2490
+ async ({ schemaName, yaml }) => {
2491
+ const result = handleValidateYamlFragment({ schemaName, yaml });
2492
+ return {
2493
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2494
+ };
2495
+ }
2496
+ );
2497
+ }
2498
+
2499
+ // src/tools/get-schema.ts
2500
+ var NavigationLinkSchema2 = z12.lazy(
2501
+ () => z12.object({
2502
+ label: z12.string().min(1),
2503
+ href: z12.string().min(1),
2504
+ children: z12.array(NavigationLinkSchema2).optional()
2505
+ })
2506
+ );
2507
+ var NavigationSectionSchema2 = z12.object({
2508
+ section: z12.string().min(1),
2509
+ items: z12.array(NavigationLinkSchema2)
2510
+ });
2511
+ var NavigationItemSchema2 = z12.union([
2512
+ NavigationLinkSchema2,
2513
+ NavigationSectionSchema2
2514
+ ]);
2515
+ function getZodSchema(name) {
2516
+ switch (name) {
2517
+ case "workflow_step":
2518
+ return WorkflowStepSchema2;
2519
+ case "workflow_definition":
2520
+ return WorkflowDefinitionSchema2;
2521
+ case "workflow_field":
2522
+ return WorkflowFieldSchema2;
2523
+ case "workflow_action":
2524
+ return WorkflowActionSchema2;
2525
+ case "navigation_item":
2526
+ return NavigationItemSchema2;
2527
+ case "auth_config":
2528
+ return authConfigSchema2;
2529
+ }
2530
+ }
2531
+ function formatType(node, depth = 0) {
2532
+ if (node.const !== void 0) return JSON.stringify(node.const);
2533
+ if (node.enum) return node.enum.map((v) => JSON.stringify(v)).join(" | ");
2534
+ if (node.oneOf || node.anyOf) {
2535
+ const branches = node.oneOf ?? node.anyOf ?? [];
2536
+ return branches.map((b) => {
2537
+ const disc = b.properties ? Object.entries(b.properties).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ") : "";
2538
+ return disc ? `{ ${disc}, ... }` : "{ ... }";
2539
+ }).join(" | ");
2540
+ }
2541
+ if (node.type === "array" && node.items) {
2542
+ return `${formatType(node.items, depth)}[]`;
2543
+ }
2544
+ if (node.type === "object" && node.properties && depth < 2) {
2545
+ const inner = Object.entries(node.properties).map(([k, v]) => `${k}: ${formatType(v, depth + 1)}`).join(", ");
2546
+ return `{ ${inner} }`;
2547
+ }
2548
+ const base = Array.isArray(node.type) ? node.type.join(" | ") : node.type ?? "unknown";
2549
+ const constraints = [];
2550
+ if (node.maxLength !== void 0) constraints.push(`max ${node.maxLength} chars`);
2551
+ if (node.minLength !== void 0) constraints.push(`min ${node.minLength} chars`);
2552
+ if (node.pattern) constraints.push(`pattern: ${node.pattern}`);
2553
+ if (node.minimum !== void 0) constraints.push(`min ${node.minimum}`);
2554
+ if (node.maximum !== void 0) constraints.push(`max ${node.maximum}`);
2555
+ return constraints.length > 0 ? `${base} (${constraints.join(", ")})` : base;
2556
+ }
2557
+ function formatObjectSchema(node, schemaName, synonyms) {
2558
+ const lines = [];
2559
+ const displayName = schemaName.split("_").map((w) => w[0].toUpperCase() + w.slice(1)).join("");
2560
+ lines.push(`${displayName}:`);
2561
+ if (node.oneOf || node.anyOf) {
2562
+ const branches = node.oneOf ?? node.anyOf ?? [];
2563
+ lines.push(" Discriminated union \u2014 choose one variant:");
2564
+ for (const branch of branches) {
2565
+ const req = new Set(branch.required ?? []);
2566
+ const disc = Object.entries(branch.properties ?? {}).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ");
2567
+ lines.push(` VARIANT (${disc}):`);
2568
+ for (const [field, fieldNode] of Object.entries(branch.properties ?? {})) {
2569
+ if (fieldNode.const !== void 0) continue;
2570
+ const isRequired = req.has(field);
2571
+ const hint = synonyms[field] ? ` -- WARNING: use ${field}: not ${synonyms[field]}` : "";
2572
+ lines.push(
2573
+ ` ${isRequired ? "REQUIRED" : "optional"}: ${field}: ${formatType(fieldNode)}${hint}`
2574
+ );
2575
+ }
2576
+ }
2577
+ return lines.join("\n");
2578
+ }
2579
+ const required = new Set(node.required ?? []);
2580
+ const properties = node.properties ?? {};
2581
+ const requiredFields = Object.entries(properties).filter(([k]) => required.has(k));
2582
+ const optionalFields = Object.entries(properties).filter(([k]) => !required.has(k));
2583
+ if (requiredFields.length > 0) {
2584
+ lines.push(" REQUIRED:");
2585
+ for (const [field, fieldNode] of requiredFields) {
2586
+ const typeStr = formatType(fieldNode);
2587
+ const warn = synonyms[field] ? ` -- CAUTION: this schema uses ${field}` : "";
2588
+ lines.push(` ${field}: ${typeStr}${warn}`);
2589
+ }
2590
+ }
2591
+ if (optionalFields.length > 0) {
2592
+ lines.push(" OPTIONAL:");
2593
+ for (const [field, fieldNode] of optionalFields) {
2594
+ const typeStr = formatType(fieldNode);
2595
+ lines.push(` ${field}: ${typeStr}`);
2596
+ }
2597
+ }
2598
+ return lines.join("\n");
2599
+ }
2600
+ function handleGetSchema(input) {
2601
+ const { schemaName } = input;
2602
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2603
+ return {
2604
+ error: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2605
+ };
2606
+ }
2607
+ const name = schemaName;
2608
+ const schema = getZodSchema(name);
2609
+ const synonyms = FIELD_SYNONYMS[name];
2610
+ let jsonSchema;
2611
+ try {
2612
+ const raw = z12.toJSONSchema(schema, { unrepresentable: "any" });
2613
+ jsonSchema = raw;
2614
+ } catch {
2615
+ jsonSchema = { type: "object", description: "Schema introspection unavailable for this type" };
2616
+ }
2617
+ const summary = formatObjectSchema(jsonSchema, name, synonyms);
2618
+ const synonymWarnings = Object.entries(synonyms).map(
2619
+ ([wrong, correct]) => ` WARNING: use "${correct}" \u2014 NOT "${wrong}"`
2620
+ );
2621
+ const fullText = [
2622
+ summary,
2623
+ "",
2624
+ "FIELD NAME WARNINGS (common drift patterns):",
2625
+ ...synonymWarnings
2626
+ ].join("\n");
2627
+ const tokenEstimate = Math.ceil(fullText.length / 4);
2628
+ return {
2629
+ schemaName: name,
2630
+ summary,
2631
+ synonymWarnings,
2632
+ tokenEstimate
2633
+ };
2634
+ }
2635
+ var PHASE_SCHEMA_NAMES = {
2636
+ workflow: ["workflow_step", "workflow_definition", "workflow_field", "workflow_action"],
2637
+ pages: ["navigation_item"],
2638
+ dashboard: ["navigation_item"],
2639
+ polish: ["navigation_item"],
2640
+ auth: ["auth_config"]
2641
+ };
2642
+ function buildSchemaReferenceBlock(phase) {
2643
+ const schemaNames = PHASE_SCHEMA_NAMES[phase];
2644
+ if (!schemaNames || schemaNames.length === 0) return null;
2645
+ const sections = [
2646
+ "CANONICAL_SCHEMA_REFERENCE (authoritative \u2014 use exact field names below):",
2647
+ ""
2648
+ ];
2649
+ for (const name of schemaNames) {
2650
+ const result = handleGetSchema({ schemaName: name });
2651
+ if ("error" in result) continue;
2652
+ sections.push(result.summary);
2653
+ if (result.synonymWarnings.length > 0) {
2654
+ sections.push(" Common mistakes to avoid:");
2655
+ sections.push(...result.synonymWarnings);
2656
+ }
2657
+ sections.push("");
2658
+ }
2659
+ return sections.join("\n");
2660
+ }
2661
+ function registerGetSchemaTool(server2) {
2662
+ server2.tool(
2663
+ "stackwright_pro_get_schema",
2664
+ 'Returns a compact, LLM-friendly summary of a canonical schema derived programmatically from Zod. Includes required/optional fields, types, constraints, and "did you mean?" warnings for common field-name drift. Use before authoring YAML to confirm exact field names.',
2665
+ {
2666
+ schemaName: z12.enum(SUPPORTED_SCHEMA_NAMES).describe(
2667
+ "Schema to summarize. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2668
+ )
2669
+ },
2670
+ async ({ schemaName }) => {
2671
+ const result = handleGetSchema({ schemaName });
2672
+ if ("error" in result) {
2673
+ return {
2674
+ content: [{ type: "text", text: JSON.stringify({ error: result.error }) }],
2675
+ isError: true
2676
+ };
2677
+ }
2678
+ return {
2679
+ content: [
2680
+ {
2681
+ type: "text",
2682
+ text: JSON.stringify(result, null, 2)
2683
+ }
2684
+ ]
2685
+ };
2686
+ }
2687
+ );
2688
+ }
2689
+
2690
+ // src/tools/pipeline.ts
2691
+ var PHASE_ORDER = [
2692
+ "designer",
2693
+ "theme",
2694
+ "scaffold",
2695
+ // generates app/ directory from config
2696
+ "api",
2697
+ "data",
2698
+ "geo",
2699
+ "workflow",
2700
+ "services",
2701
+ "pages",
2702
+ "dashboard",
2703
+ "auth",
2704
+ "polish"
2705
+ ];
2706
+ var PHASE_DEPENDENCIES = {
2707
+ designer: [],
2708
+ theme: ["designer"],
2709
+ scaffold: ["designer", "theme"],
2710
+ // needs stackwright.yml + theme-tokens
2711
+ api: [],
2712
+ data: ["api"],
2713
+ geo: ["data"],
2714
+ // workflow: no hard deps — uses service: references with Prism mock fallback
2715
+ // when API artifacts aren't available; roles come from user answers
2716
+ workflow: [],
2717
+ // services: needs API endpoints to know what to wire, and optionally
2718
+ // workflow states as trigger sources. Produces OpenAPI specs consumed
2719
+ // by pages and dashboard for typed data wiring.
2720
+ services: ["api", "workflow"],
2721
+ // pages/dashboard: depend on services for typed endpoint wiring (OpenAPI
2722
+ // specs) and on geo so the specialist prompt includes geo-manifest.json
2723
+ // — page/dashboard otters see which page slugs are already claimed and
2724
+ // won't attempt to overwrite them (swp-73c). 'api' is still transitive
2725
+ // through 'data'; auth removed — page-otter has graceful fallback.
2726
+ pages: ["designer", "theme", "data", "services", "geo", "scaffold"],
2727
+ dashboard: ["designer", "theme", "data", "services", "geo", "scaffold"],
2728
+ // auth is the penultimate phase — runs after all content-producing phases
2729
+ // so it can read pages, dashboard, workflow, and geo artifacts for route
2730
+ // protection and RBAC wiring. Skipped upstream phases still satisfy deps
2731
+ // (the foreman marks them executed=true), so auth always runs.
2732
+ auth: ["pages", "dashboard", "workflow", "geo"],
2733
+ // polish is the terminal phase — runs after auth so the landing page and
2734
+ // nav reflect the final set of protected routes and all generated pages.
2735
+ polish: ["auth"]
2736
+ };
2737
+ var PHASE_ARTIFACT = {
2738
+ designer: "design-language.json",
2739
+ theme: "theme-tokens.json",
2740
+ scaffold: "scaffold-manifest.json",
2741
+ api: "api-config.json",
2742
+ auth: "auth-config.json",
2743
+ data: "data-config.json",
2744
+ pages: "pages-manifest.json",
2745
+ dashboard: "dashboard-manifest.json",
2746
+ workflow: "workflow-config.json",
2747
+ services: "services-config.json",
2748
+ polish: "polish-manifest.json",
2749
+ geo: "geo-manifest.json"
2750
+ };
2751
+ var PHASE_TO_OTTER2 = {
2752
+ designer: "stackwright-pro-designer-otter",
2753
+ theme: "stackwright-pro-theme-otter",
2754
+ scaffold: "stackwright-pro-scaffold-otter",
2755
+ api: "stackwright-pro-api-otter",
2756
+ auth: "stackwright-pro-auth-otter",
2757
+ data: "stackwright-pro-data-otter",
2758
+ pages: "stackwright-pro-page-otter",
2759
+ dashboard: "stackwright-pro-dashboard-otter",
2760
+ workflow: "stackwright-pro-workflow-otter",
2761
+ services: "stackwright-services-otter",
2762
+ polish: "stackwright-pro-polish-otter",
2763
+ geo: "stackwright-pro-geo-otter"
2764
+ };
2765
+ function isValidPhase2(phase) {
2766
+ return PHASE_ORDER.includes(phase);
2767
+ }
2768
+ function defaultPhaseStatus() {
1678
2769
  return {
1679
2770
  questionsCollected: false,
1680
2771
  answered: false,
@@ -1699,11 +2790,11 @@ function createDefaultState() {
1699
2790
  };
1700
2791
  }
1701
2792
  function statePath(cwd) {
1702
- return join3(cwd, ".stackwright", "pipeline-state.json");
2793
+ return join4(cwd, ".stackwright", "pipeline-state.json");
1703
2794
  }
1704
2795
  function readState(cwd) {
1705
2796
  const p = statePath(cwd);
1706
- if (!existsSync3(p)) return createDefaultState();
2797
+ if (!existsSync5(p)) return createDefaultState();
1707
2798
  const raw = JSON.parse(safeReadSync(p));
1708
2799
  if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1709
2800
  return createDefaultState();
@@ -1711,26 +2802,26 @@ function readState(cwd) {
1711
2802
  return raw;
1712
2803
  }
1713
2804
  function safeWriteSync(filePath, content) {
1714
- if (existsSync3(filePath)) {
1715
- const stat = lstatSync3(filePath);
2805
+ if (existsSync5(filePath)) {
2806
+ const stat = lstatSync5(filePath);
1716
2807
  if (stat.isSymbolicLink()) {
1717
2808
  throw new Error(`Refusing to write to symlink: ${filePath}`);
1718
2809
  }
1719
2810
  }
1720
- writeFileSync3(filePath, content);
2811
+ writeFileSync4(filePath, content);
1721
2812
  }
1722
2813
  function safeReadSync(filePath) {
1723
- if (existsSync3(filePath)) {
1724
- const stat = lstatSync3(filePath);
2814
+ if (existsSync5(filePath)) {
2815
+ const stat = lstatSync5(filePath);
1725
2816
  if (stat.isSymbolicLink()) {
1726
2817
  throw new Error(`Refusing to read symlink: ${filePath}`);
1727
2818
  }
1728
2819
  }
1729
- return readFileSync3(filePath, "utf-8");
2820
+ return readFileSync4(filePath, "utf-8");
1730
2821
  }
1731
2822
  function writeState(cwd, state) {
1732
- const dir = join3(cwd, ".stackwright");
1733
- mkdirSync2(dir, { recursive: true });
2823
+ const dir = join4(cwd, ".stackwright");
2824
+ mkdirSync4(dir, { recursive: true });
1734
2825
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1735
2826
  safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1736
2827
  }
@@ -1751,6 +2842,15 @@ function handleGetPipelineState(_cwd) {
1751
2842
  const cwd = _cwd ?? process.cwd();
1752
2843
  try {
1753
2844
  const state = readState(cwd);
2845
+ const keyPath = join4(cwd, ".stackwright", "pipeline-keys.json");
2846
+ if (!existsSync5(keyPath)) {
2847
+ try {
2848
+ const { fingerprint } = initPipelineKeys(cwd);
2849
+ state["signingKeyFingerprint"] = fingerprint;
2850
+ writeState(cwd, state);
2851
+ } catch {
2852
+ }
2853
+ }
1754
2854
  return { text: JSON.stringify(state), isError: false };
1755
2855
  } catch (err) {
1756
2856
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
@@ -1758,7 +2858,7 @@ function handleGetPipelineState(_cwd) {
1758
2858
  }
1759
2859
  function handleSetPipelineState(input) {
1760
2860
  const cwd = input._cwd ?? process.cwd();
1761
- if (input.phase && !isValidPhase(input.phase)) {
2861
+ if (input.phase && !isValidPhase2(input.phase)) {
1762
2862
  return {
1763
2863
  text: JSON.stringify({
1764
2864
  error: true,
@@ -1777,6 +2877,28 @@ function handleSetPipelineState(input) {
1777
2877
  isError: true
1778
2878
  };
1779
2879
  }
2880
+ if (input.updates && input.updates.length > 0) {
2881
+ for (const update of input.updates) {
2882
+ if (!isValidPhase2(update.phase)) {
2883
+ return {
2884
+ text: JSON.stringify({
2885
+ error: true,
2886
+ message: `Invalid phase in batch update: ${update.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2887
+ }),
2888
+ isError: true
2889
+ };
2890
+ }
2891
+ if (!VALID_FIELDS.includes(update.field)) {
2892
+ return {
2893
+ text: JSON.stringify({
2894
+ error: true,
2895
+ message: `Invalid field in batch update: ${update.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
2896
+ }),
2897
+ isError: true
2898
+ };
2899
+ }
2900
+ }
2901
+ }
1780
2902
  try {
1781
2903
  const state = readState(cwd);
1782
2904
  if (input.status) {
@@ -1796,34 +2918,78 @@ function handleSetPipelineState(input) {
1796
2918
  }
1797
2919
  state.currentPhase = phase;
1798
2920
  }
2921
+ if (input.updates && input.updates.length > 0) {
2922
+ for (const update of input.updates) {
2923
+ if (!state.phases[update.phase]) {
2924
+ state.phases[update.phase] = defaultPhaseStatus();
2925
+ }
2926
+ const batchPhaseState = state.phases[update.phase];
2927
+ batchPhaseState[update.field] = update.value;
2928
+ state.currentPhase = update.phase;
2929
+ }
2930
+ }
1799
2931
  writeState(cwd, state);
1800
2932
  return { text: JSON.stringify(state), isError: false };
1801
2933
  } catch (err) {
1802
2934
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1803
2935
  }
1804
2936
  }
1805
- function handleCheckExecutionReady(_cwd) {
2937
+ function handleCheckExecutionReady(_cwd, phase) {
1806
2938
  const cwd = _cwd ?? process.cwd();
2939
+ if (phase) {
2940
+ if (!isValidPhase2(phase)) {
2941
+ return {
2942
+ text: JSON.stringify({
2943
+ error: true,
2944
+ message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2945
+ }),
2946
+ isError: true
2947
+ };
2948
+ }
2949
+ const answerFile = join4(cwd, ".stackwright", "answers", `${phase}.json`);
2950
+ if (!existsSync5(answerFile)) {
2951
+ return {
2952
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
2953
+ isError: false
2954
+ };
2955
+ }
2956
+ try {
2957
+ const raw = safeReadSync(answerFile);
2958
+ const parsed = JSON.parse(raw);
2959
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2960
+ return {
2961
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
2962
+ isError: false
2963
+ };
2964
+ }
2965
+ return { text: JSON.stringify({ ready: true, phase }), isError: false };
2966
+ } catch {
2967
+ return {
2968
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
2969
+ isError: false
2970
+ };
2971
+ }
2972
+ }
1807
2973
  try {
1808
- const answersDir = join3(cwd, ".stackwright", "answers");
2974
+ const answersDir = join4(cwd, ".stackwright", "answers");
1809
2975
  const answeredPhases = [];
1810
2976
  const missingPhases = [];
1811
- for (const phase of PHASE_ORDER) {
1812
- const answerFile = join3(answersDir, `${phase}.json`);
1813
- if (existsSync3(answerFile)) {
2977
+ for (const phase2 of PHASE_ORDER) {
2978
+ const answerFile = join4(answersDir, `${phase2}.json`);
2979
+ if (existsSync5(answerFile)) {
1814
2980
  try {
1815
2981
  const raw = safeReadSync(answerFile);
1816
2982
  const parsed = JSON.parse(raw);
1817
2983
  if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
1818
- missingPhases.push(phase);
2984
+ missingPhases.push(phase2);
1819
2985
  continue;
1820
2986
  }
1821
- answeredPhases.push(phase);
2987
+ answeredPhases.push(phase2);
1822
2988
  } catch {
1823
- missingPhases.push(phase);
2989
+ missingPhases.push(phase2);
1824
2990
  }
1825
2991
  } else {
1826
- missingPhases.push(phase);
2992
+ missingPhases.push(phase2);
1827
2993
  }
1828
2994
  }
1829
2995
  return {
@@ -1839,18 +3005,74 @@ function handleCheckExecutionReady(_cwd) {
1839
3005
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1840
3006
  }
1841
3007
  }
3008
+ function handleGetReadyPhases(_cwd) {
3009
+ const cwd = _cwd ?? process.cwd();
3010
+ try {
3011
+ const state = readState(cwd);
3012
+ const completed = [];
3013
+ const ready = [];
3014
+ const blocked = [];
3015
+ for (const phase of PHASE_ORDER) {
3016
+ const ps = state.phases[phase];
3017
+ if (ps?.executed) {
3018
+ completed.push(phase);
3019
+ continue;
3020
+ }
3021
+ const deps = PHASE_DEPENDENCIES[phase];
3022
+ const unmetDeps = deps.filter((dep) => !state.phases[dep]?.executed);
3023
+ if (unmetDeps.length === 0) {
3024
+ ready.push(phase);
3025
+ } else {
3026
+ blocked.push(phase);
3027
+ }
3028
+ }
3029
+ return {
3030
+ text: JSON.stringify({
3031
+ readyPhases: ready,
3032
+ completedPhases: completed,
3033
+ blockedPhases: blocked,
3034
+ waveSize: ready.length,
3035
+ allComplete: ready.length === 0 && blocked.length === 0
3036
+ }),
3037
+ isError: false
3038
+ };
3039
+ } catch (err) {
3040
+ const message = err instanceof Error ? err.message : String(err);
3041
+ return { text: JSON.stringify({ error: true, message }), isError: true };
3042
+ }
3043
+ }
1842
3044
  function handleListArtifacts(_cwd) {
1843
3045
  const cwd = _cwd ?? process.cwd();
1844
3046
  try {
1845
- const artifactsDir = join3(cwd, ".stackwright", "artifacts");
3047
+ const artifactsDir = join4(cwd, ".stackwright", "artifacts");
3048
+ let manifest = null;
3049
+ try {
3050
+ manifest = loadSignatureManifest(cwd);
3051
+ } catch {
3052
+ }
1846
3053
  const artifacts = [];
1847
3054
  let completedCount = 0;
1848
3055
  for (const phase of PHASE_ORDER) {
1849
3056
  const expectedFile = PHASE_ARTIFACT[phase];
1850
- const fullPath = join3(artifactsDir, expectedFile);
1851
- const exists = existsSync3(fullPath);
3057
+ const fullPath = join4(artifactsDir, expectedFile);
3058
+ const exists = existsSync5(fullPath);
1852
3059
  if (exists) completedCount++;
1853
- artifacts.push({ phase, expectedFile, exists, path: fullPath });
3060
+ let signed = false;
3061
+ let signatureValid = null;
3062
+ if (exists && manifest) {
3063
+ const entry = manifest.signatures[expectedFile];
3064
+ if (entry) {
3065
+ signed = true;
3066
+ try {
3067
+ const rawBytes = Buffer.from(safeReadSync(fullPath), "utf-8");
3068
+ const { publicKey } = loadPipelineKeys(cwd);
3069
+ signatureValid = verifyArtifact(rawBytes, entry, publicKey);
3070
+ } catch {
3071
+ signatureValid = null;
3072
+ }
3073
+ }
3074
+ }
3075
+ artifacts.push({ phase, expectedFile, exists, path: fullPath, signed, signatureValid });
1854
3076
  }
1855
3077
  return {
1856
3078
  text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
@@ -1863,7 +3085,7 @@ function handleListArtifacts(_cwd) {
1863
3085
  function handleWritePhaseQuestions(input) {
1864
3086
  const cwd = input._cwd ?? process.cwd();
1865
3087
  const { phase, responseText } = input;
1866
- if (!isValidPhase(phase)) {
3088
+ if (!isValidPhase2(phase)) {
1867
3089
  return {
1868
3090
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1869
3091
  isError: true
@@ -1886,9 +3108,9 @@ function handleWritePhaseQuestions(input) {
1886
3108
  }
1887
3109
  } catch {
1888
3110
  }
1889
- const questionsDir = join3(cwd, ".stackwright", "questions");
1890
- mkdirSync2(questionsDir, { recursive: true });
1891
- const filePath = join3(questionsDir, `${phase}.json`);
3111
+ const questionsDir = join4(cwd, ".stackwright", "questions");
3112
+ mkdirSync4(questionsDir, { recursive: true });
3113
+ const filePath = join4(questionsDir, `${phase}.json`);
1892
3114
  const payload = {
1893
3115
  version: "1.0",
1894
3116
  phase,
@@ -1921,43 +3143,88 @@ function handleWritePhaseQuestions(input) {
1921
3143
  function handleBuildSpecialistPrompt(input) {
1922
3144
  const cwd = input._cwd ?? process.cwd();
1923
3145
  const { phase } = input;
1924
- if (!isValidPhase(phase)) {
3146
+ if (!isValidPhase2(phase)) {
1925
3147
  return {
1926
3148
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1927
3149
  isError: true
1928
3150
  };
1929
3151
  }
1930
3152
  try {
1931
- const answersPath = join3(cwd, ".stackwright", "answers", `${phase}.json`);
3153
+ const answersPath = join4(cwd, ".stackwright", "answers", `${phase}.json`);
1932
3154
  let answers = {};
1933
- if (existsSync3(answersPath)) {
3155
+ if (existsSync5(answersPath)) {
1934
3156
  answers = JSON.parse(safeReadSync(answersPath));
1935
3157
  }
3158
+ let buildContextText = "";
3159
+ const buildContextPath = join4(cwd, ".stackwright", "build-context.json");
3160
+ if (existsSync5(buildContextPath)) {
3161
+ try {
3162
+ const bcRaw = JSON.parse(safeReadSync(buildContextPath));
3163
+ if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
3164
+ buildContextText = bcRaw.buildContext.trim();
3165
+ }
3166
+ } catch {
3167
+ }
3168
+ }
1936
3169
  const deps = PHASE_DEPENDENCIES[phase];
1937
3170
  const artifactSections = [];
1938
3171
  const missingDependencies = [];
1939
3172
  for (const dep of deps) {
1940
3173
  const artifactFile = PHASE_ARTIFACT[dep];
1941
- const artifactPath = join3(cwd, ".stackwright", "artifacts", artifactFile);
1942
- if (existsSync3(artifactPath)) {
1943
- const content = JSON.parse(safeReadSync(artifactPath));
3174
+ const artifactPath = join4(cwd, ".stackwright", "artifacts", artifactFile);
3175
+ if (existsSync5(artifactPath)) {
3176
+ const rawContent = safeReadSync(artifactPath);
3177
+ const rawBytes = Buffer.from(rawContent, "utf-8");
3178
+ const content = JSON.parse(rawContent);
3179
+ let signatureVerified = false;
3180
+ let signatureAvailable = false;
3181
+ try {
3182
+ const sig = getArtifactSignature(cwd, artifactFile);
3183
+ if (sig) {
3184
+ signatureAvailable = true;
3185
+ const { publicKey } = loadPipelineKeys(cwd);
3186
+ signatureVerified = verifyArtifact(rawBytes, sig, publicKey);
3187
+ if (!signatureVerified) {
3188
+ const actualDigest = createHash3("sha384").update(rawBytes).digest("hex");
3189
+ emitSignatureAuditEvent({
3190
+ artifactFilename: artifactFile,
3191
+ expectedDigest: sig.digest,
3192
+ actualDigest,
3193
+ phase: dep,
3194
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3195
+ source: "stackwright_pro_build_specialist_prompt"
3196
+ });
3197
+ missingDependencies.push(dep);
3198
+ artifactSections.push(
3199
+ `[${artifactFile}]:
3200
+ (integrity check failed: ECDSA-P384 signature verification failed \u2014 artifact may have been tampered with)`
3201
+ );
3202
+ continue;
3203
+ }
3204
+ }
3205
+ } catch {
3206
+ }
1944
3207
  const expectedOtter = PHASE_TO_OTTER2[dep];
1945
3208
  const artifactOtter = content["generatedBy"];
3209
+ const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
1946
3210
  if (!artifactOtter) {
1947
3211
  missingDependencies.push(dep);
1948
3212
  artifactSections.push(
1949
3213
  `[${artifactFile}]:
1950
3214
  (integrity check failed: missing generatedBy field)`
1951
3215
  );
1952
- } else if (artifactOtter !== expectedOtter) {
3216
+ } else if (normalizedOtter !== expectedOtter) {
1953
3217
  missingDependencies.push(dep);
1954
3218
  artifactSections.push(
1955
3219
  `[${artifactFile}]:
1956
3220
  (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
1957
3221
  );
1958
3222
  } else {
1959
- artifactSections.push(`[${artifactFile}]:
1960
- ${JSON.stringify(content, null, 2)}`);
3223
+ const sigStatus = signatureAvailable ? signatureVerified ? " [signature verified]" : " [signature check skipped]" : " [unsigned]";
3224
+ artifactSections.push(
3225
+ `[${artifactFile}]${sigStatus}:
3226
+ ${JSON.stringify(content, null, 2)}`
3227
+ );
1961
3228
  }
1962
3229
  } else {
1963
3230
  missingDependencies.push(dep);
@@ -1965,10 +3232,33 @@ ${JSON.stringify(content, null, 2)}`);
1965
3232
  (not yet available)`);
1966
3233
  }
1967
3234
  }
1968
- const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
3235
+ const parts = [];
3236
+ if (buildContextText) {
3237
+ parts.push("BUILD_CONTEXT:", buildContextText, "");
3238
+ }
3239
+ if (phase === "auth") {
3240
+ const initContextPath = join4(cwd, ".stackwright", "init-context.json");
3241
+ if (existsSync5(initContextPath)) {
3242
+ try {
3243
+ const initContext = JSON.parse(safeReadSync(initContextPath));
3244
+ if (initContext.devOnly === true || initContext.nonInteractive === true) {
3245
+ answers["devOnly"] = true;
3246
+ }
3247
+ } catch {
3248
+ }
3249
+ }
3250
+ }
3251
+ parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
1969
3252
  if (artifactSections.length > 0) {
1970
3253
  parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
1971
3254
  }
3255
+ const artifactSchema = PHASE_ARTIFACT_SCHEMA[phase];
3256
+ parts.push("", "REQUIRED_ARTIFACT_SCHEMA:");
3257
+ parts.push(artifactSchema);
3258
+ const schemaRef = buildSchemaReferenceBlock(phase);
3259
+ if (schemaRef) {
3260
+ parts.push("", schemaRef);
3261
+ }
1972
3262
  parts.push("", "Execute using these answers and the upstream artifacts provided.");
1973
3263
  const prompt = parts.join("\n");
1974
3264
  const dependenciesSatisfied = missingDependencies.length === 0;
@@ -2003,45 +3293,322 @@ var OFF_SCRIPT_PATTERNS = [
2003
3293
  var PHASE_REQUIRED_KEYS = {
2004
3294
  designer: ["designLanguage", "themeTokenSeeds"],
2005
3295
  theme: ["tokens"],
2006
- api: ["entities"],
3296
+ api: ["entities", "version", "generatedBy"],
2007
3297
  auth: ["version", "generatedBy"],
2008
- data: ["version", "generatedBy"],
3298
+ data: ["version", "generatedBy", "strategy", "collections"],
2009
3299
  pages: ["version", "generatedBy"],
2010
3300
  dashboard: ["version", "generatedBy"],
2011
- workflow: ["version", "generatedBy"]
3301
+ workflow: ["version", "generatedBy"],
3302
+ services: ["version", "generatedBy", "flows"],
3303
+ polish: ["version", "generatedBy"],
3304
+ geo: ["version", "generatedBy", "geoCollections"]
3305
+ };
3306
+ var PHASE_ARTIFACT_SCHEMA = {
3307
+ designer: JSON.stringify(
3308
+ {
3309
+ version: "1.0",
3310
+ generatedBy: "stackwright-pro-designer-otter",
3311
+ application: {
3312
+ type: "<operational|data-explorer|admin|logistics|general>",
3313
+ environment: "<workstation|field|control-room|mixed>",
3314
+ density: "<compact|balanced|spacious>",
3315
+ accessibility: "<wcag-aa|section-508|none>",
3316
+ colorScheme: "<light|dark|both>"
3317
+ },
3318
+ designLanguage: {
3319
+ rationale: "<design rationale>",
3320
+ spacingScale: { base: 8, scale: [0, 4, 8, 16, 24, 32, 48, 64] },
3321
+ colorSemantics: { primary: "#1a365d", accent: "#e53e3e" },
3322
+ typography: {
3323
+ dataFont: "Inter",
3324
+ headingFont: "Inter",
3325
+ monoFont: "monospace",
3326
+ dataSizePx: 12,
3327
+ bodySizePx: 14
3328
+ },
3329
+ contrastRatio: "4.5",
3330
+ borderRadius: "4",
3331
+ shadowElevation: "standard"
3332
+ },
3333
+ themeTokenSeeds: {
3334
+ light: {
3335
+ background: "#ffffff",
3336
+ foreground: "#1a1a1a",
3337
+ primary: "#1a365d",
3338
+ surface: "#f7f7f7",
3339
+ border: "#e2e8f0"
3340
+ },
3341
+ dark: {
3342
+ background: "#1a1a1a",
3343
+ foreground: "#ffffff",
3344
+ primary: "#90cdf4",
3345
+ surface: "#2d2d2d",
3346
+ border: "#4a5568"
3347
+ }
3348
+ },
3349
+ conformsTo: null,
3350
+ operationalNotes: []
3351
+ },
3352
+ null,
3353
+ 2
3354
+ ),
3355
+ theme: JSON.stringify(
3356
+ {
3357
+ version: "1.0",
3358
+ generatedBy: "stackwright-pro-theme-otter",
3359
+ componentLibrary: "shadcn",
3360
+ colorScheme: "<light|dark|both>",
3361
+ tokens: {
3362
+ colors: { "primary-500": "#1a365d", background: "#ffffff" },
3363
+ spacing: { "spacing-1": "8px", "spacing-2": "16px" },
3364
+ typography: { "font-data": "Inter", "text-sm": "12px" },
3365
+ shape: { "radius-sm": "4px", "radius-md": "8px" },
3366
+ shadows: { "shadow-sm": "0 1px 2px rgba(0,0,0,0.08)" }
3367
+ },
3368
+ cssVariables: {
3369
+ "--background": "0 0% 100%",
3370
+ "--foreground": "222.2 84% 4.9%",
3371
+ "--primary": "222.2 47.4% 11.2%",
3372
+ "--primary-foreground": "210 40% 98%",
3373
+ "--surface": "210 40% 98%",
3374
+ "--border": "214.3 31.8% 91.4%"
3375
+ },
3376
+ dark: { "--background": "222.2 84% 4.9%", "--foreground": "210 40% 98%" }
3377
+ },
3378
+ null,
3379
+ 2
3380
+ ),
3381
+ api: JSON.stringify(
3382
+ {
3383
+ version: "1.0",
3384
+ generatedBy: "stackwright-pro-api-otter",
3385
+ entities: [
3386
+ {
3387
+ name: "Shipment",
3388
+ endpoint: "/shipments",
3389
+ method: "GET",
3390
+ revalidate: 60,
3391
+ mutationType: null
3392
+ }
3393
+ ],
3394
+ skipped: [
3395
+ {
3396
+ spec: "ais-message-models.yaml",
3397
+ format: "asyncapi",
3398
+ reason: "AsyncAPI spec \u2014 WebSocket/event integration required (no REST endpoints)"
3399
+ }
3400
+ ],
3401
+ warnings: [
3402
+ "Spec contains external $ref URLs \u2014 recommend bundle: true in stackwright.yml integration config"
3403
+ ],
3404
+ auth: { type: "bearer", header: "Authorization", envVar: "API_TOKEN" },
3405
+ baseUrl: "https://api.example.mil/v2",
3406
+ specPath: "./specs/api.yaml"
3407
+ },
3408
+ null,
3409
+ 2
3410
+ ),
3411
+ data: JSON.stringify(
3412
+ {
3413
+ version: "1.0",
3414
+ generatedBy: "stackwright-pro-data-otter",
3415
+ strategy: "<pulse-fast|isr-fast|isr-standard|isr-slow>",
3416
+ pulseMode: false,
3417
+ collections: [{ name: "equipment", revalidate: 60, pulse: false }],
3418
+ endpoints: { included: ["/equipment/**"], excluded: ["/admin/**"] },
3419
+ requiredPackages: { dependencies: {}, devPackages: {} }
3420
+ },
3421
+ null,
3422
+ 2
3423
+ ),
3424
+ geo: JSON.stringify(
3425
+ {
3426
+ version: "1.0",
3427
+ generatedBy: "stackwright-pro-geo-otter",
3428
+ geoCollections: [
3429
+ {
3430
+ collection: "vessels",
3431
+ latField: "latitude",
3432
+ lngField: "longitude",
3433
+ labelField: "vesselName",
3434
+ colorField: "navigationStatus"
3435
+ }
3436
+ ],
3437
+ pages: [
3438
+ {
3439
+ slug: "fleet-tracker",
3440
+ type: "<tracker|zone|route|combined>",
3441
+ collections: ["vessels"],
3442
+ hasLayers: false
3443
+ }
3444
+ ]
3445
+ },
3446
+ null,
3447
+ 2
3448
+ ),
3449
+ workflow: JSON.stringify(
3450
+ {
3451
+ version: "1.0",
3452
+ generatedBy: "stackwright-pro-workflow-otter",
3453
+ workflowConfig: {
3454
+ id: "procurement-approval",
3455
+ route: "/procurement",
3456
+ files: ["workflows/procurement-approval.yml"],
3457
+ serviceDependencies: ["service:workflow-state"],
3458
+ warnings: []
3459
+ }
3460
+ },
3461
+ null,
3462
+ 2
3463
+ ),
3464
+ services: JSON.stringify(
3465
+ {
3466
+ version: "1.0",
3467
+ generatedBy: "stackwright-services-otter",
3468
+ flows: [
3469
+ {
3470
+ name: "at-risk-patients",
3471
+ trigger: "<http|event|schedule|queue>",
3472
+ steps: 3,
3473
+ outputSpec: "at-risk-patients.openapi.json"
3474
+ }
3475
+ ],
3476
+ workflows: [
3477
+ {
3478
+ name: "evacuation-coordination",
3479
+ states: 4,
3480
+ transitions: 5
3481
+ }
3482
+ ],
3483
+ openApiSpecs: ["at-risk-patients.openapi.json"],
3484
+ capabilitiesUsed: ["service.call", "collection.join", "collection.filter"]
3485
+ },
3486
+ null,
3487
+ 2
3488
+ ),
3489
+ pages: JSON.stringify(
3490
+ {
3491
+ version: "1.0",
3492
+ generatedBy: "stackwright-pro-page-otter",
3493
+ pages: [
3494
+ {
3495
+ slug: "catalog",
3496
+ type: "collection_listing",
3497
+ collection: "products",
3498
+ themeApplied: true,
3499
+ authRequired: false
3500
+ },
3501
+ {
3502
+ slug: "admin",
3503
+ type: "protected",
3504
+ collection: null,
3505
+ themeApplied: true,
3506
+ authRequired: true
3507
+ }
3508
+ ]
3509
+ },
3510
+ null,
3511
+ 2
3512
+ ),
3513
+ dashboard: JSON.stringify(
3514
+ {
3515
+ version: "1.0",
3516
+ generatedBy: "stackwright-pro-dashboard-otter",
3517
+ pages: [
3518
+ {
3519
+ slug: "dashboard",
3520
+ layout: "<grid|table|mixed>",
3521
+ collections: ["equipment", "supplies"],
3522
+ mode: "<ISR|Pulse>"
3523
+ }
3524
+ ]
3525
+ },
3526
+ null,
3527
+ 2
3528
+ ),
3529
+ // type: 'pki' = CAC/DoD certificate auth | 'oidc' = enterprise SSO
3530
+ // For dev-only mock auth: use type: 'oidc' with devOnly: true (Zod strips devOnly — it's a convention only)
3531
+ auth: JSON.stringify(
3532
+ {
3533
+ version: "1.0",
3534
+ generatedBy: "stackwright-pro-auth-otter",
3535
+ authConfig: {
3536
+ type: "<pki|oidc>",
3537
+ // OIDC-only fields (omit for pki):
3538
+ provider: "<azure_ad|okta|cognito|auth0|authentik|keycloak|custom>",
3539
+ discoveryUrl: "<IdP OIDC discovery URL>",
3540
+ clientId: "<OIDC client ID>",
3541
+ clientSecret: "<OIDC client secret>",
3542
+ rbacRoles: ["ADMIN", "ANALYST"],
3543
+ rbacDefaultRole: "ANALYST",
3544
+ protectedRoutes: ["/dashboard/:path*", "/procurement/:path*"],
3545
+ auditEnabled: true,
3546
+ auditRetentionDays: 90
3547
+ },
3548
+ // devScripts is OPTIONAL — only present when devOnly: true was used
3549
+ // Polish otter and foreman MUST check devScripts.written before referencing scripts
3550
+ devScripts: {
3551
+ written: true,
3552
+ scripts: { "dev:admin": "MOCK_USER=admin next dev" }
3553
+ }
3554
+ },
3555
+ null,
3556
+ 2
3557
+ ),
3558
+ polish: JSON.stringify(
3559
+ {
3560
+ version: "1.0",
3561
+ generatedBy: "stackwright-pro-polish-otter",
3562
+ landingPage: { slug: "", rewritten: true },
3563
+ navigation: { itemCount: 5, items: ["/dashboard", "/equipment", "/workflows"] },
3564
+ gettingStarted: "<rewritten|redirected|not-found>",
3565
+ scaffoldCleanup: {
3566
+ deleted: ["content/posts/getting-started.yaml"],
3567
+ rewritten: ["app/not-found.tsx"],
3568
+ skipped: []
3569
+ }
3570
+ },
3571
+ null,
3572
+ 2
3573
+ )
2012
3574
  };
2013
3575
  function handleValidateArtifact(input) {
2014
3576
  const cwd = input._cwd ?? process.cwd();
2015
- const { phase, responseText } = input;
2016
- if (!isValidPhase(phase)) {
3577
+ const { phase, responseText, artifact: directArtifact } = input;
3578
+ if (!isValidPhase2(phase)) {
2017
3579
  return {
2018
3580
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2019
3581
  isError: true
2020
3582
  };
2021
3583
  }
2022
- for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2023
- if (pattern.test(responseText)) {
3584
+ let artifact;
3585
+ if (directArtifact) {
3586
+ artifact = directArtifact;
3587
+ } else {
3588
+ const text = responseText ?? "";
3589
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
3590
+ if (pattern.test(text)) {
3591
+ const result = {
3592
+ valid: false,
3593
+ phase,
3594
+ violation: "off-script",
3595
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3596
+ };
3597
+ return { text: JSON.stringify(result), isError: false };
3598
+ }
3599
+ }
3600
+ try {
3601
+ artifact = extractJsonFromResponse(text);
3602
+ } catch {
2024
3603
  const result = {
2025
3604
  valid: false,
2026
3605
  phase,
2027
- violation: "off-script",
2028
- retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3606
+ violation: "invalid-json",
3607
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2029
3608
  };
2030
3609
  return { text: JSON.stringify(result), isError: false };
2031
3610
  }
2032
3611
  }
2033
- let artifact;
2034
- try {
2035
- artifact = extractJsonFromResponse(responseText);
2036
- } catch {
2037
- const result = {
2038
- valid: false,
2039
- phase,
2040
- violation: "invalid-json",
2041
- retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2042
- };
2043
- return { text: JSON.stringify(result), isError: false };
2044
- }
2045
3612
  if (!artifact.version || !artifact.generatedBy) {
2046
3613
  const result = {
2047
3614
  valid: false,
@@ -2062,12 +3629,58 @@ function handleValidateArtifact(input) {
2062
3629
  };
2063
3630
  return { text: JSON.stringify(result), isError: false };
2064
3631
  }
3632
+ const PHASE_ZOD_VALIDATORS = {
3633
+ workflow: (artifact2) => {
3634
+ const workflowConfig = artifact2["workflowConfig"];
3635
+ if (!workflowConfig) return { success: true };
3636
+ const result = WorkflowFileSchema.safeParse(workflowConfig);
3637
+ if (!result.success) {
3638
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3639
+ return { success: false, error: { message: issues } };
3640
+ }
3641
+ return { success: true };
3642
+ },
3643
+ auth: (artifact2) => {
3644
+ const authConfig = artifact2["authConfig"];
3645
+ if (!authConfig) return { success: true };
3646
+ const result = authConfigSchema3.safeParse(authConfig);
3647
+ if (!result.success) {
3648
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3649
+ return { success: false, error: { message: issues } };
3650
+ }
3651
+ return { success: true };
3652
+ }
3653
+ };
3654
+ const zodValidator = PHASE_ZOD_VALIDATORS[phase];
3655
+ if (zodValidator) {
3656
+ const zodResult = zodValidator(artifact);
3657
+ if (!zodResult.success) {
3658
+ const result = {
3659
+ valid: false,
3660
+ phase,
3661
+ violation: "schema-mismatch",
3662
+ retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
3663
+ };
3664
+ return { text: JSON.stringify(result), isError: false };
3665
+ }
3666
+ }
2065
3667
  try {
2066
- const artifactsDir = join3(cwd, ".stackwright", "artifacts");
2067
- mkdirSync2(artifactsDir, { recursive: true });
3668
+ const artifactsDir = join4(cwd, ".stackwright", "artifacts");
3669
+ mkdirSync4(artifactsDir, { recursive: true });
2068
3670
  const artifactFile = PHASE_ARTIFACT[phase];
2069
- const artifactPath = join3(artifactsDir, artifactFile);
2070
- safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
3671
+ const artifactPath = join4(artifactsDir, artifactFile);
3672
+ const serialized = JSON.stringify(artifact, null, 2) + "\n";
3673
+ const artifactBytes = Buffer.from(serialized, "utf-8");
3674
+ safeWriteSync(artifactPath, serialized);
3675
+ let signed = false;
3676
+ try {
3677
+ const { privateKey } = loadPipelineKeys(cwd);
3678
+ const sig = signArtifact(artifactBytes, privateKey);
3679
+ const signerOtter = PHASE_TO_OTTER2[phase];
3680
+ saveArtifactSignature(cwd, artifactFile, sig, signerOtter);
3681
+ signed = true;
3682
+ } catch {
3683
+ }
2071
3684
  const state = readState(cwd);
2072
3685
  if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2073
3686
  const ps = state.phases[phase];
@@ -2078,7 +3691,7 @@ function handleValidateArtifact(input) {
2078
3691
  valid: true,
2079
3692
  phase,
2080
3693
  artifactPath,
2081
- summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
3694
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})${signed ? " [signed]" : ""}`
2082
3695
  };
2083
3696
  return { text: JSON.stringify(result), isError: false };
2084
3697
  } catch (err) {
@@ -2102,11 +3715,24 @@ function registerPipelineTools(server2) {
2102
3715
  "stackwright_pro_set_pipeline_state",
2103
3716
  `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2104
3717
  {
2105
- phase: z9.string().optional().describe('Phase to update, e.g. "designer"'),
2106
- field: z9.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
2107
- value: z9.boolean().optional().describe("Value for the field"),
2108
- status: z9.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
2109
- incrementRetry: z9.boolean().optional().describe("Bump retryCount by 1")
3718
+ phase: z13.string().optional().describe('Phase to update, e.g. "designer"'),
3719
+ field: z13.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
3720
+ value: boolCoerce(z13.boolean().optional()).describe(
3721
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
3722
+ ),
3723
+ status: z13.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
3724
+ incrementRetry: boolCoerce(z13.boolean().optional()).describe(
3725
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
3726
+ ),
3727
+ updates: jsonCoerce(
3728
+ z13.array(
3729
+ z13.object({
3730
+ phase: z13.string(),
3731
+ field: z13.enum(["questionsCollected", "answered", "executed", "artifactWritten"]),
3732
+ value: z13.boolean()
3733
+ })
3734
+ ).optional()
3735
+ ).describe("Batch updates \u2014 apply multiple field changes in one atomic read\u2192modify\u2192write")
2110
3736
  },
2111
3737
  async (args) => res(
2112
3738
  handleSetPipelineState({
@@ -2114,15 +3740,24 @@ function registerPipelineTools(server2) {
2114
3740
  ...args.field != null ? { field: args.field } : {},
2115
3741
  ...args.value != null ? { value: args.value } : {},
2116
3742
  ...args.status != null ? { status: args.status } : {},
2117
- ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
3743
+ ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {},
3744
+ ...args.updates != null ? { updates: args.updates } : {}
2118
3745
  })
2119
3746
  )
2120
3747
  );
2121
3748
  server2.tool(
2122
3749
  "stackwright_pro_check_execution_ready",
2123
- `Check all phases have answer files in .stackwright/answers/. ${DESC}`,
3750
+ `Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
3751
+ {
3752
+ phase: z13.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
3753
+ },
3754
+ async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
3755
+ );
3756
+ server2.tool(
3757
+ "stackwright_pro_get_ready_phases",
3758
+ `Return phases whose dependencies are all satisfied (executed=true). Use to determine which phases can run next \u2014 enables wave-based execution. ${DESC}`,
2124
3759
  {},
2125
- async () => res(handleCheckExecutionReady())
3760
+ async () => res(handleGetReadyPhases())
2126
3761
  );
2127
3762
  server2.tool(
2128
3763
  "stackwright_pro_list_artifacts",
@@ -2132,40 +3767,91 @@ function registerPipelineTools(server2) {
2132
3767
  );
2133
3768
  server2.tool(
2134
3769
  "stackwright_pro_write_phase_questions",
2135
- `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
3770
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
2136
3771
  {
2137
- phase: z9.string().describe('Phase name, e.g. "designer"'),
2138
- responseText: z9.string().describe("Raw LLM response from QUESTION_COLLECTION_MODE")
3772
+ phase: z13.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
3773
+ responseText: z13.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
3774
+ questions: jsonCoerce(z13.array(z13.any()).optional()).describe(
3775
+ "Questions array for direct specialist write"
3776
+ )
2139
3777
  },
2140
- async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
3778
+ async ({ phase, responseText, questions }) => {
3779
+ if (phase && questions && Array.isArray(questions)) {
3780
+ if (!SAFE_PHASE.test(phase)) {
3781
+ return {
3782
+ content: [
3783
+ { type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
3784
+ ],
3785
+ isError: true
3786
+ };
3787
+ }
3788
+ const questionsDir = join4(process.cwd(), ".stackwright", "questions");
3789
+ mkdirSync4(questionsDir, { recursive: true });
3790
+ const outPath = join4(questionsDir, `${phase}.json`);
3791
+ writeFileSync4(
3792
+ outPath,
3793
+ JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
3794
+ );
3795
+ return {
3796
+ content: [
3797
+ {
3798
+ type: "text",
3799
+ text: JSON.stringify({
3800
+ written: true,
3801
+ phase,
3802
+ count: questions.length
3803
+ })
3804
+ }
3805
+ ]
3806
+ };
3807
+ }
3808
+ return res(
3809
+ handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
3810
+ );
3811
+ }
2141
3812
  );
2142
3813
  server2.tool(
2143
3814
  "stackwright_pro_build_specialist_prompt",
2144
3815
  `Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
2145
- { phase: z9.string().describe('Phase to build prompt for, e.g. "pages"') },
3816
+ { phase: z13.string().describe('Phase to build prompt for, e.g. "pages"') },
2146
3817
  async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2147
3818
  );
2148
3819
  server2.tool(
2149
3820
  "stackwright_pro_validate_artifact",
2150
- `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
3821
+ `Validate and write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2151
3822
  {
2152
- phase: z9.string().describe('Phase that produced this artifact, e.g. "designer"'),
2153
- responseText: z9.string().describe("Raw response text from the specialist otter")
3823
+ phase: z13.string().describe('Phase that produced this artifact, e.g. "designer"'),
3824
+ responseText: z13.string().optional().describe("Raw response text from the specialist otter (Foreman-mediated path, legacy)"),
3825
+ artifact: jsonCoerce(z13.record(z13.string(), z13.unknown()).optional()).describe(
3826
+ "Artifact object to validate and write directly (specialist direct path \u2014 skips off-script detection and JSON parsing)"
3827
+ )
2154
3828
  },
2155
- async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
3829
+ async ({ phase, responseText, artifact }) => {
3830
+ if (artifact) {
3831
+ return res(
3832
+ handleValidateArtifact({ phase, artifact })
3833
+ );
3834
+ }
3835
+ return res(handleValidateArtifact({ phase, responseText: responseText ?? "" }));
3836
+ }
2156
3837
  );
2157
3838
  }
2158
3839
 
2159
3840
  // src/tools/safe-write.ts
2160
- import { z as z10 } from "zod";
2161
- import { writeFileSync as writeFileSync4, existsSync as existsSync4, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "fs";
2162
- import { normalize, isAbsolute, dirname, join as join4 } from "path";
3841
+ import { z as z14 } from "zod";
3842
+ import { writeFileSync as writeFileSync5, readFileSync as readFileSync5, existsSync as existsSync6, mkdirSync as mkdirSync5, lstatSync as lstatSync6 } from "fs";
3843
+ import { normalize, isAbsolute, dirname, join as join5 } from "path";
2163
3844
  var OTTER_WRITE_ALLOWLISTS = {
2164
3845
  "stackwright-pro-designer-otter": [
2165
3846
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2166
3847
  ],
2167
3848
  "stackwright-pro-theme-otter": [
2168
- { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
3849
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" },
3850
+ {
3851
+ prefix: "stackwright.theme.",
3852
+ suffix: ".yml",
3853
+ description: "Theme config YAML (merged at build time)"
3854
+ }
2169
3855
  ],
2170
3856
  "stackwright-pro-auth-otter": [
2171
3857
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
@@ -2175,6 +3861,16 @@ var OTTER_WRITE_ALLOWLISTS = {
2175
3861
  prefix: ".env",
2176
3862
  suffix: "",
2177
3863
  description: "Dotenv files (.env, .env.local, .env.production, etc.)"
3864
+ },
3865
+ {
3866
+ prefix: "lib/mock-auth",
3867
+ suffix: ".ts",
3868
+ description: "Mock auth module (DEV_ONLY_MODE role updates)"
3869
+ },
3870
+ {
3871
+ prefix: "package.json",
3872
+ suffix: ".json",
3873
+ description: "Project package.json (DEV_ONLY_MODE script cleanup)"
2178
3874
  }
2179
3875
  ],
2180
3876
  "stackwright-pro-data-otter": [
@@ -2196,15 +3892,119 @@ var OTTER_WRITE_ALLOWLISTS = {
2196
3892
  { prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
2197
3893
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
2198
3894
  ],
3895
+ "stackwright-pro-scaffold-otter": [
3896
+ { prefix: "app/", suffix: ".tsx", description: "Next.js App Router shell files" },
3897
+ {
3898
+ prefix: ".stackwright/artifacts/",
3899
+ suffix: ".json",
3900
+ description: "Scaffold manifest artifact"
3901
+ }
3902
+ ],
2199
3903
  "stackwright-pro-api-otter": [
2200
3904
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
3905
+ ],
3906
+ "stackwright-pro-geo-otter": [
3907
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Geo manifest artifact" },
3908
+ { prefix: "pages/", suffix: "/content.yml", description: "Map page content" },
3909
+ { prefix: "pages/", suffix: "/content.yaml", description: "Map page content" }
3910
+ ],
3911
+ "stackwright-pro-polish-otter": [
3912
+ {
3913
+ prefix: "stackwright.yml",
3914
+ suffix: "",
3915
+ description: "Stackwright config (navigation updates)"
3916
+ },
3917
+ { prefix: "pages/", suffix: "/content.yml", description: "Landing page content" },
3918
+ { prefix: "pages/", suffix: "/content.yaml", description: "Landing page content" },
3919
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Polish artifact" },
3920
+ { prefix: "README.md", suffix: "", description: "Project README rewrite" }
3921
+ ],
3922
+ "stackwright-services-otter": [
3923
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Services config artifact" },
3924
+ { prefix: "services/", suffix: ".ts", description: "Service implementation files" },
3925
+ { prefix: "services/", suffix: ".yaml", description: "Service flow definitions" },
3926
+ { prefix: "services/", suffix: ".yml", description: "Service flow definitions" },
3927
+ { prefix: "lib/seeds/", suffix: ".ts", description: "Seed data files" },
3928
+ { prefix: "specs/", suffix: ".json", description: "Generated OpenAPI specs" },
3929
+ { prefix: "specs/", suffix: ".yaml", description: "Generated OpenAPI specs" },
3930
+ { prefix: "stackwright-generated/", suffix: ".json", description: "Services manifest" }
2201
3931
  ]
2202
3932
  };
2203
3933
  var PROTECTED_PATH_PREFIXES = [
2204
3934
  ".stackwright/pipeline-state.json",
3935
+ ".stackwright/pipeline-keys.json",
3936
+ // ephemeral signing keys
3937
+ ".stackwright/artifacts/signatures.json",
3938
+ // artifact signature manifest
2205
3939
  ".stackwright/questions/",
2206
- ".stackwright/answers/"
3940
+ ".stackwright/answers/",
3941
+ ".stackwright/page-registry.json"
3942
+ // page ownership — managed by safe_write internally
2207
3943
  ];
3944
+ var MAX_SAFE_WRITE_BYTES_JSON = 512 * 1024;
3945
+ var MAX_SAFE_WRITE_BYTES_YAML = 256 * 1024;
3946
+ var MAX_SAFE_WRITE_BYTES_ENV = 4 * 1024;
3947
+ var MAX_SAFE_WRITE_BYTES_DEFAULT = 256 * 1024;
3948
+ function getMaxBytesForPath(filePath) {
3949
+ if (filePath.endsWith(".json")) return { limit: MAX_SAFE_WRITE_BYTES_JSON, label: "JSON" };
3950
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml"))
3951
+ return { limit: MAX_SAFE_WRITE_BYTES_YAML, label: "YAML" };
3952
+ if (filePath === ".env" || /^\.env\.[a-zA-Z0-9]+/.test(filePath))
3953
+ return { limit: MAX_SAFE_WRITE_BYTES_ENV, label: "env" };
3954
+ return { limit: MAX_SAFE_WRITE_BYTES_DEFAULT, label: "default" };
3955
+ }
3956
+ var PAGE_REGISTRY_FILE = ".stackwright/page-registry.json";
3957
+ function extractPageSlug(filePath) {
3958
+ const match = normalize(filePath).match(/^pages\/(.+?)\/content\.ya?ml$/);
3959
+ return match?.[1] ?? null;
3960
+ }
3961
+ function extractContentTypes(yamlContent) {
3962
+ const typePattern = /^\s*-?\s*type:\s*(\S+)/gm;
3963
+ const types = [];
3964
+ let m;
3965
+ while ((m = typePattern.exec(yamlContent)) !== null) {
3966
+ const typeName = m[1];
3967
+ if (typeName && !types.includes(typeName)) {
3968
+ types.push(typeName);
3969
+ }
3970
+ }
3971
+ return types.length > 0 ? types : ["unknown"];
3972
+ }
3973
+ function readPageRegistry(cwd) {
3974
+ const regPath = join5(cwd, PAGE_REGISTRY_FILE);
3975
+ if (!existsSync6(regPath)) return {};
3976
+ try {
3977
+ const stat = lstatSync6(regPath);
3978
+ if (stat.isSymbolicLink()) return {};
3979
+ return JSON.parse(readFileSync5(regPath, "utf-8"));
3980
+ } catch {
3981
+ return {};
3982
+ }
3983
+ }
3984
+ function writePageRegistry(cwd, registry) {
3985
+ const dir = join5(cwd, ".stackwright");
3986
+ mkdirSync5(dir, { recursive: true });
3987
+ const regPath = join5(cwd, PAGE_REGISTRY_FILE);
3988
+ if (existsSync6(regPath)) {
3989
+ const stat = lstatSync6(regPath);
3990
+ if (stat.isSymbolicLink()) {
3991
+ throw new Error("Refusing to write page registry through symlink");
3992
+ }
3993
+ }
3994
+ writeFileSync5(regPath, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8" });
3995
+ }
3996
+ function checkPageOwnership(cwd, slug, callerOtter) {
3997
+ const registry = readPageRegistry(cwd);
3998
+ const existing = registry[slug];
3999
+ if (!existing || existing.claimedBy === callerOtter) {
4000
+ return { allowed: true };
4001
+ }
4002
+ return {
4003
+ allowed: false,
4004
+ owner: existing.claimedBy,
4005
+ contentTypes: existing.contentTypes
4006
+ };
4007
+ }
2208
4008
  function checkPathAllowed(callerOtter, filePath) {
2209
4009
  const normalized = normalize(filePath);
2210
4010
  if (normalized.includes("..")) {
@@ -2246,6 +4046,16 @@ function checkPathAllowed(callerOtter, filePath) {
2246
4046
  continue;
2247
4047
  }
2248
4048
  }
4049
+ if (rule.prefix === "lib/mock-auth" && rule.suffix === ".ts") {
4050
+ if (normalized !== "lib/mock-auth.ts") {
4051
+ continue;
4052
+ }
4053
+ }
4054
+ if (rule.prefix === "package.json" && rule.suffix === ".json") {
4055
+ if (normalized !== "package.json") {
4056
+ continue;
4057
+ }
4058
+ }
2249
4059
  return { allowed: true, rule: rule.description };
2250
4060
  }
2251
4061
  }
@@ -2330,11 +4140,23 @@ function handleSafeWrite(input) {
2330
4140
  };
2331
4141
  return { text: JSON.stringify(result), isError: true };
2332
4142
  }
4143
+ const contentBytes = Buffer.byteLength(content, "utf-8");
4144
+ const { limit: maxBytes, label: fileTypeLabel } = getMaxBytesForPath(filePath);
4145
+ if (contentBytes > maxBytes) {
4146
+ const result = {
4147
+ success: false,
4148
+ error: `Content size ${contentBytes} bytes exceeds ${fileTypeLabel} limit of ${maxBytes} bytes (${maxBytes / 1024} KB)`,
4149
+ callerOtter,
4150
+ attemptedPath: filePath,
4151
+ allowedPaths: []
4152
+ };
4153
+ return { text: JSON.stringify(result), isError: true };
4154
+ }
2333
4155
  const normalized = normalize(filePath);
2334
- const fullPath = join4(cwd, normalized);
2335
- if (existsSync4(fullPath)) {
4156
+ const fullPath = join5(cwd, normalized);
4157
+ if (existsSync6(fullPath)) {
2336
4158
  try {
2337
- const stat = lstatSync4(fullPath);
4159
+ const stat = lstatSync6(fullPath);
2338
4160
  if (stat.isSymbolicLink()) {
2339
4161
  const result = {
2340
4162
  success: false,
@@ -2359,11 +4181,38 @@ function handleSafeWrite(input) {
2359
4181
  };
2360
4182
  return { text: JSON.stringify(result), isError: true };
2361
4183
  }
4184
+ const pageSlug = extractPageSlug(normalized);
4185
+ if (pageSlug) {
4186
+ const ownership = checkPageOwnership(cwd, pageSlug, callerOtter);
4187
+ if (!ownership.allowed) {
4188
+ const result = {
4189
+ success: false,
4190
+ error: `Page slug "${pageSlug}" is already claimed by ${ownership.owner} (content types: ${ownership.contentTypes.join(", ")}). Use a different slug or coordinate with the owning otter.`,
4191
+ callerOtter,
4192
+ attemptedPath: filePath,
4193
+ allowedPaths: []
4194
+ };
4195
+ return { text: JSON.stringify(result), isError: true };
4196
+ }
4197
+ }
2362
4198
  try {
2363
4199
  if (createDirectories) {
2364
- mkdirSync3(dirname(fullPath), { recursive: true });
4200
+ mkdirSync5(dirname(fullPath), { recursive: true });
4201
+ }
4202
+ writeFileSync5(fullPath, content, { encoding: "utf-8" });
4203
+ if (pageSlug) {
4204
+ try {
4205
+ const registry = readPageRegistry(cwd);
4206
+ registry[pageSlug] = {
4207
+ slug: pageSlug,
4208
+ claimedBy: callerOtter,
4209
+ contentTypes: extractContentTypes(content),
4210
+ writtenAt: (/* @__PURE__ */ new Date()).toISOString()
4211
+ };
4212
+ writePageRegistry(cwd, registry);
4213
+ } catch {
4214
+ }
2365
4215
  }
2366
- writeFileSync4(fullPath, content, { encoding: "utf-8" });
2367
4216
  const result = {
2368
4217
  success: true,
2369
4218
  path: normalized,
@@ -2389,10 +4238,12 @@ function registerSafeWriteTools(server2) {
2389
4238
  "stackwright_pro_safe_write",
2390
4239
  DESC,
2391
4240
  {
2392
- callerOtter: z10.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
2393
- filePath: z10.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
2394
- content: z10.string().describe("File content to write"),
2395
- createDirectories: z10.boolean().optional().describe("Create parent directories if they don't exist. Default: true")
4241
+ callerOtter: z14.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
4242
+ filePath: z14.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
4243
+ content: z14.string().describe("File content to write"),
4244
+ createDirectories: boolCoerce(z14.boolean().optional().default(true)).describe(
4245
+ "Create parent directories if they don't exist. Default: true"
4246
+ )
2396
4247
  },
2397
4248
  async ({ callerOtter, filePath, content, createDirectories }) => {
2398
4249
  const result = handleSafeWrite({
@@ -2407,9 +4258,9 @@ function registerSafeWriteTools(server2) {
2407
4258
  }
2408
4259
 
2409
4260
  // src/tools/auth.ts
2410
- import { z as z11 } from "zod";
2411
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync5 } from "fs";
2412
- import { join as join5 } from "path";
4261
+ import { z as z15 } from "zod";
4262
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync6, existsSync as existsSync7, mkdirSync as mkdirSync6 } from "fs";
4263
+ import { join as join6 } from "path";
2413
4264
  function buildHierarchy(roles) {
2414
4265
  const h = {};
2415
4266
  for (let i = 0; i < roles.length - 1; i++) {
@@ -2429,6 +4280,19 @@ function routesToYaml(routes, defaultRole, indent) {
2429
4280
  return routes.map((r) => `${indent}- pattern: ${r}
2430
4281
  ${indent} requiredRole: ${defaultRole}`).join("\n");
2431
4282
  }
4283
+ function detectNextMajorVersion(cwd) {
4284
+ try {
4285
+ const pkgPath = join6(cwd, "package.json");
4286
+ if (!existsSync7(pkgPath)) return null;
4287
+ const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
4288
+ const nextVersion = pkg.dependencies?.next ?? pkg.devDependencies?.next;
4289
+ if (!nextVersion) return null;
4290
+ const match = nextVersion.match(/(\d+)/);
4291
+ return match ? parseInt(match[1], 10) : null;
4292
+ } catch {
4293
+ return null;
4294
+ }
4295
+ }
2432
4296
  function upsertAuthBlock(existing, authYaml) {
2433
4297
  const lines = existing.split("\n");
2434
4298
  let authStart = -1;
@@ -2441,14 +4305,99 @@ function upsertAuthBlock(existing, authYaml) {
2441
4305
  break;
2442
4306
  }
2443
4307
  }
2444
- if (authStart < 0) {
2445
- return existing.trimEnd() + "\n" + authYaml + "\n";
4308
+ if (authStart < 0) {
4309
+ return existing.trimEnd() + "\n" + authYaml + "\n";
4310
+ }
4311
+ const before = lines.slice(0, authStart);
4312
+ const after = lines.slice(authEnd);
4313
+ return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4314
+ }
4315
+ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4316
+ const rbacBlock = ` rbac: {
4317
+ roles: ${JSON.stringify(roles)},
4318
+ defaultRole: '${defaultRole}',
4319
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4320
+ },`;
4321
+ const auditBlock = ` audit: {
4322
+ enabled: ${auditEnabled},
4323
+ retentionDays: ${auditRetentionDays},
4324
+ },`;
4325
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4326
+ const configBlock = `export const config = {
4327
+ matcher: ${JSON.stringify(protectedRoutes)},
4328
+ };`;
4329
+ if (method === "cac") {
4330
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4331
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4332
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4333
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4334
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth
4335
+ // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4336
+ // DoD security officer review required before production deployment.
4337
+ // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
4338
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4339
+
4340
+ export const middleware = createProMiddleware({
4341
+ method: 'cac',
4342
+ cac: {
4343
+ caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
4344
+ edipiLookup: '${edipiLookup}',
4345
+ ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
4346
+ certHeader: '${certHeader}',
4347
+ },
4348
+ ${rbacBlock}
4349
+ ${auditBlock}
4350
+ ${routesBlock}
4351
+ });
4352
+
4353
+ ${configBlock}
4354
+ `;
4355
+ }
4356
+ if (method === "oidc") {
4357
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4358
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4359
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4360
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4361
+
4362
+ export const middleware = createProMiddleware({
4363
+ method: 'oidc',
4364
+ oidc: {
4365
+ discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
4366
+ clientId: process.env.OIDC_CLIENT_ID!,
4367
+ clientSecret: process.env.OIDC_CLIENT_SECRET!,
4368
+ scopes: '${scopes2}',
4369
+ roleClaim: '${roleClaim}',
4370
+ },
4371
+ ${rbacBlock}
4372
+ ${auditBlock}
4373
+ ${routesBlock}
4374
+ });
4375
+
4376
+ ${configBlock}
4377
+ `;
2446
4378
  }
2447
- const before = lines.slice(0, authStart);
2448
- const after = lines.slice(authEnd);
2449
- return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4379
+ const scopes = params.oauth2Scopes ?? "read write";
4380
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4381
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4382
+
4383
+ export const middleware = createProMiddleware({
4384
+ method: 'oauth2',
4385
+ oauth2: {
4386
+ authorizationUrl: process.env.OAUTH2_AUTH_URL!,
4387
+ tokenUrl: process.env.OAUTH2_TOKEN_URL!,
4388
+ clientId: process.env.OAUTH2_CLIENT_ID!,
4389
+ clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
4390
+ scopes: '${scopes}',
4391
+ },
4392
+ ${rbacBlock}
4393
+ ${auditBlock}
4394
+ ${routesBlock}
4395
+ });
4396
+
4397
+ ${configBlock}
4398
+ `;
2450
4399
  }
2451
- function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4400
+ function generateProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2452
4401
  const rbacBlock = ` rbac: {
2453
4402
  roles: ${JSON.stringify(roles)},
2454
4403
  defaultRole: '${defaultRole}',
@@ -2467,13 +4416,13 @@ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy
2467
4416
  const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2468
4417
  const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2469
4418
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2470
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth
2471
- // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4419
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4420
+ // SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
2472
4421
  // DoD security officer review required before production deployment.
2473
4422
  // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
2474
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4423
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2475
4424
 
2476
- export const middleware = createProMiddleware({
4425
+ export const proxy = createProProxy({
2477
4426
  method: 'cac',
2478
4427
  cac: {
2479
4428
  caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
@@ -2492,10 +4441,10 @@ ${configBlock}
2492
4441
  if (method === "oidc") {
2493
4442
  const scopes2 = params.oidcScopes ?? "openid profile email";
2494
4443
  const roleClaim = params.oidcRoleClaim ?? "roles";
2495
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2496
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4444
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4445
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2497
4446
 
2498
- export const middleware = createProMiddleware({
4447
+ export const proxy = createProProxy({
2499
4448
  method: 'oidc',
2500
4449
  oidc: {
2501
4450
  discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
@@ -2513,10 +4462,10 @@ ${configBlock}
2513
4462
  `;
2514
4463
  }
2515
4464
  const scopes = params.oauth2Scopes ?? "read write";
2516
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2517
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4465
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4466
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2518
4467
 
2519
- export const middleware = createProMiddleware({
4468
+ export const proxy = createProProxy({
2520
4469
  method: 'oauth2',
2521
4470
  oauth2: {
2522
4471
  authorizationUrl: process.env.OAUTH2_AUTH_URL!,
@@ -2559,7 +4508,7 @@ OAUTH2_CLIENT_ID=your-client-id
2559
4508
  OAUTH2_CLIENT_SECRET=your-client-secret
2560
4509
  `;
2561
4510
  }
2562
- function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4511
+ function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
2563
4512
  const rbacSection = ` rbac:
2564
4513
  roles:
2565
4514
  ${rolesToYaml(roles, " ")}
@@ -2582,7 +4531,7 @@ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
2582
4531
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2583
4532
  return `auth:
2584
4533
  method: cac
2585
- ${providerLine} middleware: ./middleware.ts
4534
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2586
4535
  cac:
2587
4536
  caBundle: \${CAC_CA_BUNDLE}
2588
4537
  edipiLookup: ${edipiLookup}
@@ -2599,7 +4548,7 @@ ${auditSection}
2599
4548
  const roleClaim = params.oidcRoleClaim ?? "roles";
2600
4549
  return `auth:
2601
4550
  method: oidc
2602
- ${providerLine} middleware: ./middleware.ts
4551
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2603
4552
  oidc:
2604
4553
  discoveryUrl: \${OIDC_DISCOVERY_URL}
2605
4554
  clientId: \${OIDC_CLIENT_ID}
@@ -2615,7 +4564,7 @@ ${auditSection}
2615
4564
  const scopes = params.oauth2Scopes ?? "read write";
2616
4565
  return `auth:
2617
4566
  method: oauth2
2618
- ${providerLine} middleware: ./middleware.ts
4567
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2619
4568
  oauth2:
2620
4569
  authorizationUrl: \${OAUTH2_AUTH_URL}
2621
4570
  tokenUrl: \${OAUTH2_TOKEN_URL}
@@ -2628,10 +4577,321 @@ ${routeLines}
2628
4577
  ${auditSection}
2629
4578
  `;
2630
4579
  }
4580
+ function generateDevOnlyMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4581
+ const rbacBlock = ` rbac: {
4582
+ roles: ${JSON.stringify(roles)},
4583
+ defaultRole: '${defaultRole}',
4584
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4585
+ },`;
4586
+ const auditBlock = ` audit: {
4587
+ enabled: ${auditEnabled},
4588
+ retentionDays: ${auditRetentionDays},
4589
+ },`;
4590
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4591
+ const configBlock = `export const config = {
4592
+ matcher: ${JSON.stringify(protectedRoutes)},
4593
+ };`;
4594
+ const devHeader = [
4595
+ "// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs (dev-only mock)",
4596
+ "// DEV ONLY \u2014 uses mock authentication from lib/mock-auth.ts",
4597
+ "// Do NOT deploy to production.",
4598
+ "import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';",
4599
+ "import { mockAuthProvider } from './lib/mock-auth';"
4600
+ ].join("\n");
4601
+ if (method === "cac") {
4602
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4603
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4604
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4605
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4606
+ return `${devHeader}
4607
+
4608
+ export const middleware = createProMiddleware({
4609
+ method: 'cac',
4610
+ cac: {
4611
+ caBundle: '${caBundle}',
4612
+ edipiLookup: '${edipiLookup}',
4613
+ ocspEndpoint: '${ocspEndpoint}',
4614
+ certHeader: '${certHeader}',
4615
+ provider: mockAuthProvider,
4616
+ },
4617
+ ${rbacBlock}
4618
+ ${auditBlock}
4619
+ ${routesBlock}
4620
+ });
4621
+
4622
+ ${configBlock}
4623
+ `;
4624
+ }
4625
+ if (method === "oidc") {
4626
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4627
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4628
+ return `${devHeader}
4629
+
4630
+ export const middleware = createProMiddleware({
4631
+ method: 'oidc',
4632
+ oidc: {
4633
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4634
+ clientId: 'dev-mock-client',
4635
+ clientSecret: 'dev-mock-secret',
4636
+ scopes: '${scopes2}',
4637
+ roleClaim: '${roleClaim}',
4638
+ provider: mockAuthProvider,
4639
+ },
4640
+ ${rbacBlock}
4641
+ ${auditBlock}
4642
+ ${routesBlock}
4643
+ });
4644
+
4645
+ ${configBlock}
4646
+ `;
4647
+ }
4648
+ const scopes = params.oauth2Scopes ?? "read write";
4649
+ return `${devHeader}
4650
+
4651
+ export const middleware = createProMiddleware({
4652
+ method: 'oauth2',
4653
+ oauth2: {
4654
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4655
+ tokenUrl: 'https://dev-mock-oauth2/token',
4656
+ clientId: 'dev-mock-client',
4657
+ clientSecret: 'dev-mock-secret',
4658
+ scopes: '${scopes}',
4659
+ provider: mockAuthProvider,
4660
+ },
4661
+ ${rbacBlock}
4662
+ ${auditBlock}
4663
+ ${routesBlock}
4664
+ });
4665
+
4666
+ ${configBlock}
4667
+ `;
4668
+ }
4669
+ function generateDevOnlyProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4670
+ const rbacBlock = ` rbac: {
4671
+ roles: ${JSON.stringify(roles)},
4672
+ defaultRole: '${defaultRole}',
4673
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4674
+ },`;
4675
+ const auditBlock = ` audit: {
4676
+ enabled: ${auditEnabled},
4677
+ retentionDays: ${auditRetentionDays},
4678
+ },`;
4679
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4680
+ const configBlock = `export const config = {
4681
+ matcher: ${JSON.stringify(protectedRoutes)},
4682
+ };`;
4683
+ const devHeader = [
4684
+ "// proxy.ts -- generated by @stackwright-pro/auth (Next.js >=16, dev-only mock)",
4685
+ "// DEV ONLY -- uses mock authentication from lib/mock-auth.ts",
4686
+ "// Do NOT deploy to production.",
4687
+ "import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';",
4688
+ "import { mockAuthProvider } from './lib/mock-auth';"
4689
+ ].join("\n");
4690
+ if (method === "cac") {
4691
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4692
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4693
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4694
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4695
+ return `${devHeader}
4696
+
4697
+ export const proxy = createProProxy({
4698
+ method: 'cac',
4699
+ cac: {
4700
+ caBundle: '${caBundle}',
4701
+ edipiLookup: '${edipiLookup}',
4702
+ ocspEndpoint: '${ocspEndpoint}',
4703
+ certHeader: '${certHeader}',
4704
+ provider: mockAuthProvider,
4705
+ },
4706
+ ${rbacBlock}
4707
+ ${auditBlock}
4708
+ ${routesBlock}
4709
+ });
4710
+
4711
+ ${configBlock}
4712
+ `;
4713
+ }
4714
+ if (method === "oidc") {
4715
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4716
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4717
+ return `${devHeader}
4718
+
4719
+ export const proxy = createProProxy({
4720
+ method: 'oidc',
4721
+ oidc: {
4722
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4723
+ clientId: 'dev-mock-client',
4724
+ clientSecret: 'dev-mock-secret',
4725
+ scopes: '${scopes2}',
4726
+ roleClaim: '${roleClaim}',
4727
+ provider: mockAuthProvider,
4728
+ },
4729
+ ${rbacBlock}
4730
+ ${auditBlock}
4731
+ ${routesBlock}
4732
+ });
4733
+
4734
+ ${configBlock}
4735
+ `;
4736
+ }
4737
+ const scopes = params.oauth2Scopes ?? "read write";
4738
+ return `${devHeader}
4739
+
4740
+ export const proxy = createProProxy({
4741
+ method: 'oauth2',
4742
+ oauth2: {
4743
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4744
+ tokenUrl: 'https://dev-mock-oauth2/token',
4745
+ clientId: 'dev-mock-client',
4746
+ clientSecret: 'dev-mock-secret',
4747
+ scopes: '${scopes}',
4748
+ provider: mockAuthProvider,
4749
+ },
4750
+ ${rbacBlock}
4751
+ ${auditBlock}
4752
+ ${routesBlock}
4753
+ });
4754
+
4755
+ ${configBlock}
4756
+ `;
4757
+ }
4758
+ function generateDevOnlyYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
4759
+ const rbacSection = ` rbac:
4760
+ roles:
4761
+ ${rolesToYaml(roles, " ")}
4762
+ defaultRole: ${defaultRole}
4763
+ hierarchy:
4764
+ ${hierarchyToYaml(hierarchy, " ")}`;
4765
+ const auditSection = ` audit:
4766
+ enabled: ${auditEnabled}
4767
+ retentionDays: ${auditRetentionDays}`;
4768
+ const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
4769
+ requiredRole: ${defaultRole}`).join("\n");
4770
+ const providerLine = params.provider ? ` provider: ${params.provider}
4771
+ ` : "";
4772
+ if (method === "cac") {
4773
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4774
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4775
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4776
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4777
+ return `auth:
4778
+ method: cac
4779
+ devOnly: true
4780
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4781
+ cac:
4782
+ caBundle: ${caBundle}
4783
+ edipiLookup: ${edipiLookup}
4784
+ ocspEndpoint: ${ocspEndpoint}
4785
+ certHeader: ${certHeader}
4786
+ ${rbacSection}
4787
+ protectedRoutes:
4788
+ ${routeLines}
4789
+ ${auditSection}
4790
+ `;
4791
+ }
4792
+ if (method === "oidc") {
4793
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4794
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4795
+ return `auth:
4796
+ method: oidc
4797
+ devOnly: true
4798
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4799
+ oidc:
4800
+ discoveryUrl: https://dev-mock-oidc/.well-known/openid-configuration
4801
+ clientId: dev-mock-client
4802
+ clientSecret: dev-mock-secret
4803
+ scopes: ${scopes2}
4804
+ roleClaim: ${roleClaim}
4805
+ ${rbacSection}
4806
+ protectedRoutes:
4807
+ ${routeLines}
4808
+ ${auditSection}
4809
+ `;
4810
+ }
4811
+ const scopes = params.oauth2Scopes ?? "read write";
4812
+ return `auth:
4813
+ method: oauth2
4814
+ devOnly: true
4815
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4816
+ oauth2:
4817
+ authorizationUrl: https://dev-mock-oauth2/authorize
4818
+ tokenUrl: https://dev-mock-oauth2/token
4819
+ clientId: dev-mock-client
4820
+ clientSecret: dev-mock-secret
4821
+ scopes: ${scopes}
4822
+ ${rbacSection}
4823
+ protectedRoutes:
4824
+ ${routeLines}
4825
+ ${auditSection}
4826
+ `;
4827
+ }
4828
+ function deriveDevKey(roleName) {
4829
+ const segment = roleName.split("_")[0];
4830
+ return (segment ?? roleName).toLowerCase();
4831
+ }
4832
+ function generateMockAuthContent(roles, mockUsers) {
4833
+ const entries = [];
4834
+ const scriptLines = [];
4835
+ for (let i = 0; i < roles.length; i++) {
4836
+ const role = roles[i];
4837
+ const devKey = deriveDevKey(role);
4838
+ const persona = mockUsers?.[i];
4839
+ const name = persona?.name ?? `Dev ${role}`;
4840
+ const email = persona?.email ?? `dev-${devKey}@example.mil`;
4841
+ const edipi = String(i + 1).padStart(10, "0");
4842
+ entries.push(` ${devKey}: {
4843
+ id: 'mock-${devKey}-${String(i + 1).padStart(3, "0")}',
4844
+ name: '${name}',
4845
+ email: '${email}',
4846
+ roles: ['${role}'],
4847
+ edipi: '${edipi}',
4848
+ }`);
4849
+ scriptLines.push(` * pnpm dev:${devKey} \u2014 ${name}`);
4850
+ }
4851
+ return `/**
4852
+ * Mock authentication for development mode.
4853
+ *
4854
+ * DEV_ONLY_MODE \u2014 no real auth provider. Select a persona via MOCK_USER env var
4855
+ * or use the convenience scripts in package.json:
4856
+ ${scriptLines.join("\n")}
4857
+ */
4858
+
4859
+ export const MOCK_USERS = {
4860
+ ${entries.join(",\n")}
4861
+ } as const;
4862
+
4863
+ export type MockRole = keyof typeof MOCK_USERS;
4864
+
4865
+ export function getMockUser(role?: string) {
4866
+ const key = (role ?? process.env.MOCK_USER) as MockRole | undefined;
4867
+ if (!key) return null;
4868
+ return MOCK_USERS[key] ?? null;
4869
+ }
4870
+
4871
+ export function mockAuthProvider() {
4872
+ return getMockUser();
4873
+ }
4874
+ `;
4875
+ }
4876
+ function updatePackageJsonScripts(existingJson, roles, mockUsers) {
4877
+ const pkg = JSON.parse(existingJson);
4878
+ const scripts = pkg.scripts ?? {};
4879
+ delete scripts["dev:admin"];
4880
+ delete scripts["dev:analyst"];
4881
+ delete scripts["dev:viewer"];
4882
+ for (let i = 0; i < roles.length; i++) {
4883
+ const devKey = deriveDevKey(roles[i]);
4884
+ scripts[`dev:${devKey}`] = `MOCK_USER=${devKey} next dev`;
4885
+ }
4886
+ pkg.scripts = scripts;
4887
+ return JSON.stringify(pkg, null, 2) + "\n";
4888
+ }
2631
4889
  async function configureAuthHandler(params, cwd) {
2632
4890
  const {
2633
4891
  method,
2634
4892
  provider,
4893
+ devOnly = false,
4894
+ mockUsers,
2635
4895
  rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
2636
4896
  auditEnabled = true,
2637
4897
  auditRetentionDays = 90,
@@ -2640,6 +4900,9 @@ async function configureAuthHandler(params, cwd) {
2640
4900
  const roles = rbacRoles;
2641
4901
  const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
2642
4902
  const hierarchy = buildHierarchy(roles);
4903
+ const detectedVersion = params.nextMajorVersion ?? detectNextMajorVersion(cwd);
4904
+ const useProxy = (detectedVersion ?? 0) >= 16;
4905
+ const conventionFile = useProxy ? "proxy.ts" : "middleware.ts";
2643
4906
  if (method === "none") {
2644
4907
  return {
2645
4908
  content: [
@@ -2661,7 +4924,34 @@ async function configureAuthHandler(params, cwd) {
2661
4924
  }
2662
4925
  const filesWritten = [];
2663
4926
  try {
2664
- const middlewareContent = generateMiddlewareContent(
4927
+ const authFileContent = devOnly ? useProxy ? generateDevOnlyProxyContent(
4928
+ method,
4929
+ params,
4930
+ roles,
4931
+ defaultRole,
4932
+ hierarchy,
4933
+ auditEnabled,
4934
+ auditRetentionDays,
4935
+ protectedRoutes
4936
+ ) : generateDevOnlyMiddlewareContent(
4937
+ method,
4938
+ params,
4939
+ roles,
4940
+ defaultRole,
4941
+ hierarchy,
4942
+ auditEnabled,
4943
+ auditRetentionDays,
4944
+ protectedRoutes
4945
+ ) : useProxy ? generateProxyContent(
4946
+ method,
4947
+ params,
4948
+ roles,
4949
+ defaultRole,
4950
+ hierarchy,
4951
+ auditEnabled,
4952
+ auditRetentionDays,
4953
+ protectedRoutes
4954
+ ) : generateMiddlewareContent(
2665
4955
  method,
2666
4956
  params,
2667
4957
  roles,
@@ -2671,44 +4961,95 @@ async function configureAuthHandler(params, cwd) {
2671
4961
  auditRetentionDays,
2672
4962
  protectedRoutes
2673
4963
  );
2674
- writeFileSync5(join5(cwd, "middleware.ts"), middlewareContent, "utf8");
2675
- filesWritten.push("middleware.ts");
4964
+ writeFileSync6(join6(cwd, conventionFile), authFileContent, "utf8");
4965
+ filesWritten.push(conventionFile);
2676
4966
  } catch (err) {
2677
4967
  const msg = err instanceof Error ? err.message : String(err);
2678
4968
  return {
2679
4969
  content: [
2680
4970
  {
2681
4971
  type: "text",
2682
- text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
4972
+ text: JSON.stringify({
4973
+ success: false,
4974
+ error: `Failed writing ${conventionFile}: ${msg}`
4975
+ })
2683
4976
  }
2684
4977
  ],
2685
4978
  isError: true
2686
4979
  };
2687
4980
  }
2688
- try {
2689
- const envBlock = generateEnvBlock(method, params);
2690
- const envPath = join5(cwd, ".env.example");
2691
- if (existsSync5(envPath)) {
2692
- const existing = readFileSync4(envPath, "utf8");
2693
- writeFileSync5(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
2694
- } else {
2695
- writeFileSync5(envPath, envBlock, "utf8");
4981
+ if (!devOnly) {
4982
+ try {
4983
+ const envBlock = generateEnvBlock(method, params);
4984
+ const envPath = join6(cwd, ".env.example");
4985
+ if (existsSync7(envPath)) {
4986
+ const existing = readFileSync6(envPath, "utf8");
4987
+ writeFileSync6(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
4988
+ } else {
4989
+ writeFileSync6(envPath, envBlock, "utf8");
4990
+ }
4991
+ filesWritten.push(".env.example");
4992
+ } catch (err) {
4993
+ const msg = err instanceof Error ? err.message : String(err);
4994
+ return {
4995
+ content: [
4996
+ {
4997
+ type: "text",
4998
+ text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
4999
+ }
5000
+ ],
5001
+ isError: true
5002
+ };
5003
+ }
5004
+ }
5005
+ if (devOnly) {
5006
+ try {
5007
+ const mockAuthDir = join6(cwd, "lib");
5008
+ mkdirSync6(mockAuthDir, { recursive: true });
5009
+ const mockAuthContent = generateMockAuthContent(roles, mockUsers);
5010
+ writeFileSync6(join6(mockAuthDir, "mock-auth.ts"), mockAuthContent, "utf8");
5011
+ filesWritten.push("lib/mock-auth.ts");
5012
+ } catch (err) {
5013
+ const msg = err instanceof Error ? err.message : String(err);
5014
+ return {
5015
+ content: [
5016
+ {
5017
+ type: "text",
5018
+ text: JSON.stringify({
5019
+ success: false,
5020
+ error: `Failed writing lib/mock-auth.ts: ${msg}`
5021
+ })
5022
+ }
5023
+ ],
5024
+ isError: true
5025
+ };
5026
+ }
5027
+ try {
5028
+ const pkgPath = join6(cwd, "package.json");
5029
+ if (existsSync7(pkgPath)) {
5030
+ const existingPkg = readFileSync6(pkgPath, "utf8");
5031
+ const updatedPkg = updatePackageJsonScripts(existingPkg, roles, mockUsers);
5032
+ writeFileSync6(pkgPath, updatedPkg, "utf8");
5033
+ filesWritten.push("package.json");
5034
+ }
5035
+ } catch (err) {
5036
+ const msg = err instanceof Error ? err.message : String(err);
5037
+ return {
5038
+ content: [
5039
+ {
5040
+ type: "text",
5041
+ text: JSON.stringify({
5042
+ success: false,
5043
+ error: `Failed updating package.json: ${msg}`
5044
+ })
5045
+ }
5046
+ ],
5047
+ isError: true
5048
+ };
2696
5049
  }
2697
- filesWritten.push(".env.example");
2698
- } catch (err) {
2699
- const msg = err instanceof Error ? err.message : String(err);
2700
- return {
2701
- content: [
2702
- {
2703
- type: "text",
2704
- text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
2705
- }
2706
- ],
2707
- isError: true
2708
- };
2709
5050
  }
2710
5051
  try {
2711
- const authYaml = generateYamlBlock(
5052
+ const authYaml = devOnly ? generateDevOnlyYamlBlock(
2712
5053
  method,
2713
5054
  params,
2714
5055
  roles,
@@ -2716,14 +5057,25 @@ async function configureAuthHandler(params, cwd) {
2716
5057
  hierarchy,
2717
5058
  auditEnabled,
2718
5059
  auditRetentionDays,
2719
- protectedRoutes
5060
+ protectedRoutes,
5061
+ useProxy
5062
+ ) : generateYamlBlock(
5063
+ method,
5064
+ params,
5065
+ roles,
5066
+ defaultRole,
5067
+ hierarchy,
5068
+ auditEnabled,
5069
+ auditRetentionDays,
5070
+ protectedRoutes,
5071
+ useProxy
2720
5072
  );
2721
- const ymlPath = join5(cwd, "stackwright.yml");
2722
- if (!existsSync5(ymlPath)) {
2723
- writeFileSync5(ymlPath, authYaml, "utf8");
5073
+ const ymlPath = join6(cwd, "stackwright.yml");
5074
+ if (!existsSync7(ymlPath)) {
5075
+ writeFileSync6(ymlPath, authYaml, "utf8");
2724
5076
  } else {
2725
- const existing = readFileSync4(ymlPath, "utf8");
2726
- writeFileSync5(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
5077
+ const existing = readFileSync6(ymlPath, "utf8");
5078
+ writeFileSync6(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
2727
5079
  }
2728
5080
  filesWritten.push("stackwright.yml");
2729
5081
  } catch (err) {
@@ -2751,7 +5103,23 @@ async function configureAuthHandler(params, cwd) {
2751
5103
  rbacDefaultRole: defaultRole,
2752
5104
  protectedRoutesCount: protectedRoutes.length,
2753
5105
  filesWritten,
2754
- securityWarning
5106
+ convention: useProxy ? "proxy" : "middleware",
5107
+ nextMajorVersion: params.nextMajorVersion ?? null,
5108
+ securityWarning,
5109
+ ...devOnly ? {
5110
+ devScripts: {
5111
+ written: filesWritten.includes("package.json"),
5112
+ scripts: filesWritten.includes("package.json") ? Object.fromEntries(
5113
+ roles.map((r) => {
5114
+ const k = deriveDevKey(r);
5115
+ return [`dev:${k}`, `MOCK_USER=${k} next dev`];
5116
+ })
5117
+ ) : {},
5118
+ ...filesWritten.includes("package.json") ? {} : {
5119
+ warning: "package.json not found \u2014 dev scripts were not written. Run the auth phase again after scaffolding creates package.json."
5120
+ }
5121
+ }
5122
+ } : {}
2755
5123
  })
2756
5124
  }
2757
5125
  ]
@@ -2762,35 +5130,38 @@ function registerAuthTools(server2) {
2762
5130
  "stackwright_pro_configure_auth",
2763
5131
  "Generate authentication middleware and configuration for a Next.js Stackwright application. Writes `middleware.ts` from a secure template, appends/updates the `auth:` section in `stackwright.yml`, and generates `.env.example` with required environment variables. \u26A0\uFE0F For CAC/PKI: generated `middleware.ts` carries a SECURITY REVIEW REQUIRED comment \u2014 certificate chain validation must be verified by a DoD security officer before production deployment. This is the ONLY approved path to generating `middleware.ts`. Never write TypeScript auth files directly.",
2764
5132
  {
2765
- method: z11.enum(["cac", "oidc", "oauth2", "none"]),
2766
- provider: z11.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
5133
+ method: z15.enum(["cac", "oidc", "oauth2", "none"]),
5134
+ provider: z15.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
2767
5135
  // CAC
2768
- cacCaBundle: z11.string().optional(),
2769
- cacEdipiLookup: z11.string().optional(),
2770
- cacOcspEndpoint: z11.string().optional(),
2771
- cacCertHeader: z11.string().optional(),
5136
+ cacCaBundle: z15.string().optional(),
5137
+ cacEdipiLookup: z15.string().optional(),
5138
+ cacOcspEndpoint: z15.string().optional(),
5139
+ cacCertHeader: z15.string().optional(),
2772
5140
  // OIDC
2773
- oidcDiscoveryUrl: z11.string().optional(),
2774
- oidcClientId: z11.string().optional(),
2775
- oidcClientSecret: z11.string().optional(),
2776
- oidcScopes: z11.string().optional(),
2777
- oidcRoleClaim: z11.string().optional(),
5141
+ oidcDiscoveryUrl: z15.string().optional(),
5142
+ oidcClientId: z15.string().optional(),
5143
+ oidcClientSecret: z15.string().optional(),
5144
+ oidcScopes: z15.string().optional(),
5145
+ oidcRoleClaim: z15.string().optional(),
2778
5146
  // OAuth2
2779
- oauth2AuthUrl: z11.string().optional(),
2780
- oauth2TokenUrl: z11.string().optional(),
2781
- oauth2ClientId: z11.string().optional(),
2782
- oauth2ClientSecret: z11.string().optional(),
2783
- oauth2Scopes: z11.string().optional(),
5147
+ oauth2AuthUrl: z15.string().optional(),
5148
+ oauth2TokenUrl: z15.string().optional(),
5149
+ oauth2ClientId: z15.string().optional(),
5150
+ oauth2ClientSecret: z15.string().optional(),
5151
+ oauth2Scopes: z15.string().optional(),
2784
5152
  // RBAC
2785
- rbacRoles: z11.array(z11.string()).optional(),
2786
- rbacDefaultRole: z11.string().optional(),
5153
+ rbacRoles: jsonCoerce(z15.array(z15.string()).optional()),
5154
+ rbacDefaultRole: z15.string().optional(),
2787
5155
  // Audit
2788
- auditEnabled: z11.boolean().optional(),
2789
- auditRetentionDays: z11.number().int().positive().optional(),
5156
+ auditEnabled: boolCoerce(z15.boolean().optional()),
5157
+ auditRetentionDays: numCoerce(z15.number().int().positive().optional()),
2790
5158
  // Routes
2791
- protectedRoutes: z11.array(z11.string()).optional(),
5159
+ protectedRoutes: jsonCoerce(z15.array(z15.string()).optional()),
2792
5160
  // Injection for tests
2793
- _cwd: z11.string().optional()
5161
+ _cwd: z15.string().optional(),
5162
+ devOnly: boolCoerce(z15.boolean().optional()),
5163
+ mockUsers: jsonCoerce(z15.array(z15.object({ name: z15.string(), email: z15.string() })).optional()),
5164
+ nextMajorVersion: numCoerce(z15.number().int().positive().optional())
2794
5165
  },
2795
5166
  async (params) => {
2796
5167
  const cwd = params._cwd ?? process.cwd();
@@ -2800,45 +5171,65 @@ function registerAuthTools(server2) {
2800
5171
  }
2801
5172
 
2802
5173
  // src/integrity.ts
2803
- import { createHash as createHash2, timingSafeEqual } from "crypto";
2804
- import { readFileSync as readFileSync5, readdirSync, lstatSync as lstatSync5 } from "fs";
2805
- import { join as join6, basename } from "path";
5174
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
5175
+ import { readFileSync as readFileSync7, readdirSync as readdirSync2, lstatSync as lstatSync7 } from "fs";
5176
+ import { join as join7, basename } from "path";
2806
5177
  var _checksums = /* @__PURE__ */ new Map([
2807
5178
  [
2808
5179
  "stackwright-pro-api-otter.json",
2809
- "f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
5180
+ "1610b34c2bfd89aa18ef62fe052fe5aaba21cb2aa9c5d58a4fff06af2a1f0e6e"
2810
5181
  ],
2811
5182
  [
2812
5183
  "stackwright-pro-auth-otter.json",
2813
- "a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
5184
+ "5a876d3614e62a7817e69bbe7fe7cc6976035ccaa0e7c29fb1e1a32caf8cea93"
2814
5185
  ],
2815
5186
  [
2816
5187
  "stackwright-pro-dashboard-otter.json",
2817
- "b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
5188
+ "9550e565fb467d7956cf6b50e7b30a481e6e4b26d609dfe1f0d8f991fc6681de"
2818
5189
  ],
2819
5190
  [
2820
5191
  "stackwright-pro-data-otter.json",
2821
- "bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
5192
+ "5cd8caca50bfcc00ebaf1f9a83158e5580e0e51d25495244f8465d9c20f31e17"
2822
5193
  ],
2823
5194
  [
2824
5195
  "stackwright-pro-designer-otter.json",
2825
- "c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
5196
+ "d44b307299c2b65568a708920b819eec7d3b5fe1191ace24b166cbfb2d6e5209"
5197
+ ],
5198
+ [
5199
+ "stackwright-pro-domain-expert-otter.json",
5200
+ "dc060aacdf67ee5758921c72225aa669a76cb962f0f8eedf1741f58f18e870d3"
2826
5201
  ],
2827
5202
  [
2828
5203
  "stackwright-pro-foreman-otter.json",
2829
- "84e9a5d427f0fcdbe92b53ebd956806c88c094bca4cdf11aaa0db023f0a00c08"
5204
+ "ab3d821d9217ccbe112d68ce25798bfe637aef15814168037caa2a98994e8d2d"
5205
+ ],
5206
+ [
5207
+ "stackwright-pro-geo-otter.json",
5208
+ "3c9fc96e79d9ac22be8a293cf3ec904c4ed033842864107515aacdf71285791c"
2830
5209
  ],
2831
5210
  [
2832
5211
  "stackwright-pro-page-otter.json",
2833
- "65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
5212
+ "0057ea97f7c2e33a8673140f59a0237eb627d82c676af3fae4faa31033598e03"
5213
+ ],
5214
+ [
5215
+ "stackwright-pro-polish-otter.json",
5216
+ "1e534dfbc5644a5efbc566d77b512929760715365d54ce030da177a535c23ea6"
5217
+ ],
5218
+ [
5219
+ "stackwright-pro-scaffold-otter.json",
5220
+ "2ed0adb316aaecb849153d44f52b177de539f21d4a7ce5ae4cc1c3c7470e15d4"
2834
5221
  ],
2835
5222
  [
2836
5223
  "stackwright-pro-theme-otter.json",
2837
- "64ffaeeceacd739922788a1d074f6feaffc3f91d09706c2c104f0c0281677732"
5224
+ "730bc16b24b4612552389fe9de662f233044bcbf5ef1e0f27f2cc1e1af4c989f"
2838
5225
  ],
2839
5226
  [
2840
5227
  "stackwright-pro-workflow-otter.json",
2841
- "0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
5228
+ "8ece2a1f1ec30163600b5ce8b666c915ab0d00a1fa70c38ed58d1bb20cbd9979"
5229
+ ],
5230
+ [
5231
+ "stackwright-services-otter.json",
5232
+ "2a36a07eaf34b59a2dab7059f3748a5742ff1f6b80b4bd6a739c59cf114703d6"
2842
5233
  ]
2843
5234
  ]);
2844
5235
  Object.freeze(_checksums);
@@ -2853,11 +5244,11 @@ for (const [name, digest] of CANONICAL_CHECKSUMS) {
2853
5244
  }
2854
5245
  var MAX_OTTER_BYTES = 1 * 1024 * 1024;
2855
5246
  function computeSha256(data) {
2856
- return createHash2("sha256").update(data).digest("hex");
5247
+ return createHash4("sha256").update(data).digest("hex");
2857
5248
  }
2858
5249
  function safeEqual(a, b) {
2859
5250
  if (a.length !== b.length) return false;
2860
- return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
5251
+ return timingSafeEqual2(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2861
5252
  }
2862
5253
  function verifyOtterFile(filePath) {
2863
5254
  const filename = basename(filePath);
@@ -2867,7 +5258,7 @@ function verifyOtterFile(filePath) {
2867
5258
  }
2868
5259
  let stat;
2869
5260
  try {
2870
- stat = lstatSync5(filePath);
5261
+ stat = lstatSync7(filePath);
2871
5262
  } catch (err) {
2872
5263
  const msg = err instanceof Error ? err.message : String(err);
2873
5264
  return { verified: false, filename, error: `Cannot stat file: ${msg}` };
@@ -2885,7 +5276,7 @@ function verifyOtterFile(filePath) {
2885
5276
  }
2886
5277
  let raw;
2887
5278
  try {
2888
- raw = readFileSync5(filePath);
5279
+ raw = readFileSync7(filePath);
2889
5280
  } catch (err) {
2890
5281
  const msg = err instanceof Error ? err.message : String(err);
2891
5282
  return { verified: false, filename, error: `Cannot read file: ${msg}` };
@@ -2918,12 +5309,24 @@ function verifyOtterFile(filePath) {
2918
5309
  return { verified: true, filename };
2919
5310
  }
2920
5311
  function verifyAllOtters(otterDir) {
5312
+ if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
5313
+ return {
5314
+ verified: [],
5315
+ failed: [
5316
+ {
5317
+ filename: "<directory>",
5318
+ error: `Security: path traversal sequence detected in otter directory parameter`
5319
+ }
5320
+ ],
5321
+ unknown: []
5322
+ };
5323
+ }
2921
5324
  const verified = [];
2922
5325
  const failed = [];
2923
5326
  const unknown = [];
2924
5327
  let entries;
2925
5328
  try {
2926
- entries = readdirSync(otterDir);
5329
+ entries = readdirSync2(otterDir);
2927
5330
  } catch (err) {
2928
5331
  const msg = err instanceof Error ? err.message : String(err);
2929
5332
  return {
@@ -2934,9 +5337,9 @@ function verifyAllOtters(otterDir) {
2934
5337
  }
2935
5338
  const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
2936
5339
  for (const filename of otterFiles) {
2937
- const filePath = join6(otterDir, filename);
5340
+ const filePath = join7(otterDir, filename);
2938
5341
  try {
2939
- if (lstatSync5(filePath).isSymbolicLink()) {
5342
+ if (lstatSync7(filePath).isSymbolicLink()) {
2940
5343
  failed.push({ filename, error: "Skipped: symlink" });
2941
5344
  continue;
2942
5345
  }
@@ -2962,15 +5365,30 @@ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packag
2962
5365
  function resolveOtterDir() {
2963
5366
  const cwd = process.cwd();
2964
5367
  for (const relative of DEFAULT_SEARCH_PATHS) {
2965
- const candidate = join6(cwd, relative);
5368
+ const candidate = join7(cwd, relative);
2966
5369
  try {
2967
- lstatSync5(candidate);
5370
+ lstatSync7(candidate);
2968
5371
  return candidate;
2969
5372
  } catch {
2970
5373
  }
2971
5374
  }
2972
5375
  return null;
2973
5376
  }
5377
+ function emitIntegrityAuditEvent(params) {
5378
+ const record = JSON.stringify({
5379
+ level: "AUDIT",
5380
+ event: "INTEGRITY_FAIL",
5381
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5382
+ source: "stackwright_pro_verify_otter_integrity",
5383
+ otterDir: params.otterDir,
5384
+ failedCount: params.failed.length,
5385
+ unknownCount: params.unknown.length,
5386
+ failures: params.failed,
5387
+ unknown: params.unknown
5388
+ });
5389
+ process.stderr.write(`INTEGRITY_FAIL ${record}
5390
+ `);
5391
+ }
2974
5392
  function registerIntegrityTools(server2) {
2975
5393
  server2.tool(
2976
5394
  "stackwright_pro_verify_otter_integrity",
@@ -2994,6 +5412,13 @@ function registerIntegrityTools(server2) {
2994
5412
  }
2995
5413
  const result = verifyAllOtters(resolved);
2996
5414
  const allGood = result.failed.length === 0 && result.unknown.length === 0;
5415
+ if (!allGood) {
5416
+ emitIntegrityAuditEvent({
5417
+ otterDir: resolved,
5418
+ failed: result.failed,
5419
+ unknown: result.unknown
5420
+ });
5421
+ }
2997
5422
  return {
2998
5423
  content: [
2999
5424
  {
@@ -3006,7 +5431,10 @@ function registerIntegrityTools(server2) {
3006
5431
  unknownCount: result.unknown.length,
3007
5432
  verified: result.verified,
3008
5433
  failed: result.failed,
3009
- unknown: result.unknown
5434
+ unknown: result.unknown,
5435
+ ...allGood ? {} : {
5436
+ error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
5437
+ }
3010
5438
  })
3011
5439
  }
3012
5440
  ],
@@ -3017,14 +5445,14 @@ function registerIntegrityTools(server2) {
3017
5445
  }
3018
5446
 
3019
5447
  // src/tools/domain.ts
3020
- import { z as z12 } from "zod";
3021
- import { readFileSync as readFileSync6, existsSync as existsSync6 } from "fs";
3022
- import { join as join7 } from "path";
5448
+ import { z as z16 } from "zod";
5449
+ import { readFileSync as readFileSync8, existsSync as existsSync8 } from "fs";
5450
+ import { join as join8 } from "path";
3023
5451
  function handleListCollections(input) {
3024
5452
  const cwd = input._cwd ?? process.cwd();
3025
5453
  const sources = [
3026
5454
  {
3027
- path: join7(cwd, ".stackwright", "artifacts", "data-config.json"),
5455
+ path: join8(cwd, ".stackwright", "artifacts", "data-config.json"),
3028
5456
  source: "data-config.json",
3029
5457
  parse: (raw) => {
3030
5458
  const parsed = JSON.parse(raw);
@@ -3035,15 +5463,15 @@ function handleListCollections(input) {
3035
5463
  }
3036
5464
  },
3037
5465
  {
3038
- path: join7(cwd, "stackwright.yml"),
5466
+ path: join8(cwd, "stackwright.yml"),
3039
5467
  source: "stackwright.yml",
3040
5468
  parse: extractCollectionsFromYaml
3041
5469
  }
3042
5470
  ];
3043
5471
  for (const { path: path3, source, parse } of sources) {
3044
- if (!existsSync6(path3)) continue;
5472
+ if (!existsSync8(path3)) continue;
3045
5473
  try {
3046
- const collections = parse(readFileSync6(path3, "utf8"));
5474
+ const collections = parse(readFileSync8(path3, "utf8"));
3047
5475
  return {
3048
5476
  text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3049
5477
  isError: false
@@ -3194,8 +5622,8 @@ function handleValidateWorkflow(input) {
3194
5622
  if (input.workflow && Object.keys(input.workflow).length > 0) {
3195
5623
  raw = input.workflow;
3196
5624
  } else {
3197
- const artifactPath = join7(cwd, ".stackwright", "artifacts", "workflow-config.json");
3198
- if (!existsSync6(artifactPath)) {
5625
+ const artifactPath = join8(cwd, ".stackwright", "artifacts", "workflow-config.json");
5626
+ if (!existsSync8(artifactPath)) {
3199
5627
  return fail([
3200
5628
  {
3201
5629
  code: "NO_WORKFLOW",
@@ -3204,7 +5632,7 @@ function handleValidateWorkflow(input) {
3204
5632
  ]);
3205
5633
  }
3206
5634
  try {
3207
- raw = JSON.parse(readFileSync6(artifactPath, "utf8"));
5635
+ raw = JSON.parse(readFileSync8(artifactPath, "utf8"));
3208
5636
  } catch (err) {
3209
5637
  return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3210
5638
  }
@@ -3403,7 +5831,7 @@ function registerDomainTools(server2) {
3403
5831
  "stackwright_pro_resolve_data_strategy",
3404
5832
  "Look up the data freshness strategy configuration from the user's answer. Returns mechanism, revalidation seconds, required packages, and the exact MCP tool call to make. Replaces the strategy table in the data-otter prompt.",
3405
5833
  {
3406
- strategy: z12.string().describe(
5834
+ strategy: z16.string().describe(
3407
5835
  'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3408
5836
  )
3409
5837
  },
@@ -3413,7 +5841,7 @@ function registerDomainTools(server2) {
3413
5841
  "stackwright_pro_validate_workflow",
3414
5842
  "Validate a workflow definition against the Stackwright workflow schema. Checks step ID uniqueness, transition targets, terminal state existence, and service references. Call this after the workflow otter produces output.",
3415
5843
  {
3416
- workflow: z12.record(z12.string(), z12.unknown()).optional().describe(
5844
+ workflow: jsonCoerce(z16.record(z16.string(), z16.unknown()).optional()).describe(
3417
5845
  "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3418
5846
  )
3419
5847
  },
@@ -3421,18 +5849,535 @@ function registerDomainTools(server2) {
3421
5849
  );
3422
5850
  }
3423
5851
 
5852
+ // src/tools/type-schemas.ts
5853
+ import { z as z17 } from "zod";
5854
+ function buildTypeSchemaSummary() {
5855
+ return {
5856
+ version: "1.0",
5857
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
5858
+ domains: {
5859
+ workflow: {
5860
+ description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
5861
+ schemas: [
5862
+ "WorkflowFileSchema",
5863
+ "WorkflowDefinitionSchema",
5864
+ "WorkflowStepSchema",
5865
+ "WorkflowStepTypeSchema",
5866
+ "WorkflowFieldSchema",
5867
+ "WorkflowActionSchema",
5868
+ "WorkflowAuthSchema",
5869
+ "WorkflowThemeSchema",
5870
+ "TransitionConditionSchema",
5871
+ "PersistenceSchema"
5872
+ ],
5873
+ otter: "stackwright-pro-workflow-otter",
5874
+ artifactKey: "workflowConfig"
5875
+ },
5876
+ auth: {
5877
+ description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
5878
+ schemas: [
5879
+ "authConfigSchema",
5880
+ "pkiConfigSchema",
5881
+ "oidcConfigSchema",
5882
+ "rbacConfigSchema",
5883
+ "componentAuthSchema",
5884
+ "authUserSchema",
5885
+ "authSessionSchema"
5886
+ ],
5887
+ otter: "stackwright-pro-auth-otter",
5888
+ artifactKey: "authConfig"
5889
+ },
5890
+ openapi: {
5891
+ description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
5892
+ interfaces: [
5893
+ "OpenAPIConfig",
5894
+ "ActionConfig",
5895
+ "EndpointFilter",
5896
+ "ApprovedSpec",
5897
+ "PrebuildSecurityConfig",
5898
+ "SiteConfig",
5899
+ "ValidationResult"
5900
+ ],
5901
+ otter: "stackwright-pro-api-otter",
5902
+ artifactKey: "apiConfig"
5903
+ },
5904
+ pulse: {
5905
+ description: "Real-time data polling \u2014 source-agnostic polling options and states",
5906
+ interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
5907
+ note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
5908
+ },
5909
+ enterprise: {
5910
+ description: "Enterprise collection access \u2014 multi-tenant provider extension",
5911
+ interfaces: [
5912
+ "EnterpriseCollectionProvider",
5913
+ "CollectionProvider",
5914
+ "CollectionEntry",
5915
+ "CollectionListOptions",
5916
+ "CollectionListResult",
5917
+ "TenantFilter",
5918
+ "Collection"
5919
+ ],
5920
+ note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
5921
+ }
5922
+ }
5923
+ };
5924
+ }
5925
+ function registerTypeSchemasTool(server2) {
5926
+ server2.tool(
5927
+ "stackwright_pro_get_type_schemas",
5928
+ "Returns a structured summary of all canonical @stackwright-pro/types schemas, organized by domain. Use this to determine which otter owns a given schema and what artifact key to expect.",
5929
+ {
5930
+ format: z17.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
5931
+ },
5932
+ async ({ format }) => {
5933
+ const summary = buildTypeSchemaSummary();
5934
+ const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
5935
+ return {
5936
+ content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
5937
+ };
5938
+ }
5939
+ );
5940
+ }
5941
+
5942
+ // src/tools/scaffold-cleanup.ts
5943
+ import {
5944
+ existsSync as existsSync9,
5945
+ lstatSync as lstatSync8,
5946
+ unlinkSync as unlinkSync2,
5947
+ readFileSync as readFileSync9,
5948
+ writeFileSync as writeFileSync7,
5949
+ readdirSync as readdirSync3,
5950
+ rmdirSync,
5951
+ mkdirSync as mkdirSync7
5952
+ } from "fs";
5953
+ import { join as join9, dirname as dirname2 } from "path";
5954
+ var SCAFFOLD_FILES_TO_DELETE = [
5955
+ "content/posts/getting-started.yaml",
5956
+ "content/posts/hello-world.yaml"
5957
+ ];
5958
+ var SCAFFOLD_DIRS_TO_PRUNE = [
5959
+ "content/posts"
5960
+ // Don't prune 'content' — user may have other content directories
5961
+ ];
5962
+ var NOT_FOUND_PATH = "app/not-found.tsx";
5963
+ var FALLBACK_COLORS = {
5964
+ background: "#ffffff",
5965
+ foreground: "#171717",
5966
+ primary: "#525252",
5967
+ mutedForeground: "#737373"
5968
+ };
5969
+ function readThemeColors(cwd) {
5970
+ const tokenPath = join9(cwd, ".stackwright", "artifacts", "theme-tokens.json");
5971
+ if (!existsSync9(tokenPath)) return { ...FALLBACK_COLORS };
5972
+ const stat = lstatSync8(tokenPath);
5973
+ if (stat.isSymbolicLink()) return { ...FALLBACK_COLORS };
5974
+ try {
5975
+ const raw = JSON.parse(readFileSync9(tokenPath, "utf-8"));
5976
+ const css = raw?.cssVariables ?? {};
5977
+ const toHsl = (hslValue) => {
5978
+ if (!hslValue || typeof hslValue !== "string") return null;
5979
+ return `hsl(${hslValue})`;
5980
+ };
5981
+ return {
5982
+ background: toHsl(css["--background"]) ?? FALLBACK_COLORS.background,
5983
+ foreground: toHsl(css["--foreground"]) ?? FALLBACK_COLORS.foreground,
5984
+ primary: toHsl(css["--primary"]) ?? FALLBACK_COLORS.primary,
5985
+ mutedForeground: toHsl(css["--muted-foreground"]) ?? FALLBACK_COLORS.mutedForeground
5986
+ };
5987
+ } catch {
5988
+ return { ...FALLBACK_COLORS };
5989
+ }
5990
+ }
5991
+ function generateNotFoundPage(colors) {
5992
+ return `export default function NotFound() {
5993
+ return (
5994
+ <div
5995
+ style={{
5996
+ display: 'flex',
5997
+ flexDirection: 'column',
5998
+ alignItems: 'center',
5999
+ justifyContent: 'center',
6000
+ minHeight: '100vh',
6001
+ backgroundColor: '${colors.background}',
6002
+ color: '${colors.foreground}',
6003
+ fontFamily: 'system-ui, -apple-system, sans-serif',
6004
+ padding: '2rem',
6005
+ textAlign: 'center',
6006
+ }}
6007
+ >
6008
+ <h1 style={{ fontSize: '4rem', fontWeight: 700, margin: 0, color: '${colors.primary}' }}>
6009
+ 404
6010
+ </h1>
6011
+ <p style={{ fontSize: '1.25rem', color: '${colors.mutedForeground}', marginTop: '0.5rem' }}>
6012
+ Page not found
6013
+ </p>
6014
+ <a
6015
+ href="/"
6016
+ style={{
6017
+ marginTop: '2rem',
6018
+ padding: '0.75rem 1.5rem',
6019
+ backgroundColor: '${colors.primary}',
6020
+ color: '${colors.background}',
6021
+ borderRadius: '0.5rem',
6022
+ textDecoration: 'none',
6023
+ fontSize: '0.875rem',
6024
+ fontWeight: 500,
6025
+ }}
6026
+ >
6027
+ Go Home
6028
+ </a>
6029
+ </div>
6030
+ );
6031
+ }
6032
+ `;
6033
+ }
6034
+ function isSafePath(fullPath) {
6035
+ if (!existsSync9(fullPath)) return true;
6036
+ const stat = lstatSync8(fullPath);
6037
+ return !stat.isSymbolicLink();
6038
+ }
6039
+ function isDirEmpty(dirPath) {
6040
+ if (!existsSync9(dirPath)) return false;
6041
+ const stat = lstatSync8(dirPath);
6042
+ if (!stat.isDirectory()) return false;
6043
+ return readdirSync3(dirPath).length === 0;
6044
+ }
6045
+ function handleCleanupScaffold(_cwd) {
6046
+ const cwd = _cwd ?? process.cwd();
6047
+ const result = {
6048
+ deleted: [],
6049
+ rewritten: [],
6050
+ skipped: [],
6051
+ errors: [],
6052
+ prunedDirs: []
6053
+ };
6054
+ for (const relPath of SCAFFOLD_FILES_TO_DELETE) {
6055
+ const fullPath = join9(cwd, relPath);
6056
+ if (!existsSync9(fullPath)) {
6057
+ result.skipped.push(relPath);
6058
+ continue;
6059
+ }
6060
+ if (!isSafePath(fullPath)) {
6061
+ result.errors.push(`Refusing to delete symlink: ${relPath}`);
6062
+ continue;
6063
+ }
6064
+ try {
6065
+ unlinkSync2(fullPath);
6066
+ result.deleted.push(relPath);
6067
+ } catch (err) {
6068
+ result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
6069
+ }
6070
+ }
6071
+ for (const relDir of SCAFFOLD_DIRS_TO_PRUNE) {
6072
+ const fullDir = join9(cwd, relDir);
6073
+ if (!existsSync9(fullDir)) continue;
6074
+ if (!isSafePath(fullDir)) {
6075
+ result.errors.push(`Refusing to prune symlink directory: ${relDir}`);
6076
+ continue;
6077
+ }
6078
+ if (isDirEmpty(fullDir)) {
6079
+ try {
6080
+ rmdirSync(fullDir);
6081
+ result.prunedDirs.push(relDir);
6082
+ } catch (err) {
6083
+ result.errors.push(`Failed to prune directory ${relDir}: ${String(err)}`);
6084
+ }
6085
+ }
6086
+ }
6087
+ {
6088
+ const fullPath = join9(cwd, NOT_FOUND_PATH);
6089
+ if (!existsSync9(fullPath)) {
6090
+ result.skipped.push(NOT_FOUND_PATH);
6091
+ } else if (!isSafePath(fullPath)) {
6092
+ result.errors.push(`Refusing to rewrite symlink: ${NOT_FOUND_PATH}`);
6093
+ } else {
6094
+ try {
6095
+ const colors = readThemeColors(cwd);
6096
+ const content = generateNotFoundPage(colors);
6097
+ const dir = dirname2(fullPath);
6098
+ mkdirSync7(dir, { recursive: true });
6099
+ writeFileSync7(fullPath, content, "utf-8");
6100
+ result.rewritten.push(NOT_FOUND_PATH);
6101
+ } catch (err) {
6102
+ result.errors.push(`Failed to rewrite ${NOT_FOUND_PATH}: ${String(err)}`);
6103
+ }
6104
+ }
6105
+ }
6106
+ return {
6107
+ text: JSON.stringify(result),
6108
+ isError: false
6109
+ };
6110
+ }
6111
+ function registerScaffoldCleanupTools(server2) {
6112
+ const DESC = "Deterministic scaffold remnant cleanup \u2014 removes stale OSS scaffold files after raft run.";
6113
+ server2.tool(
6114
+ "stackwright_pro_cleanup_scaffold",
6115
+ `Remove/rewrite stale scaffold files (blog posts, hardcoded not-found page) after the raft pipeline completes. ${DESC}`,
6116
+ {},
6117
+ async () => {
6118
+ const r = handleCleanupScaffold();
6119
+ return {
6120
+ content: [{ type: "text", text: r.text }],
6121
+ isError: r.isError
6122
+ };
6123
+ }
6124
+ );
6125
+ }
6126
+
6127
+ // src/tools/contrast.ts
6128
+ import { z as z18 } from "zod";
6129
+ function linearizeChannel(c255) {
6130
+ const c = c255 / 255;
6131
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
6132
+ }
6133
+ function relativeLuminance(r, g, b) {
6134
+ return 0.2126 * linearizeChannel(r) + 0.7152 * linearizeChannel(g) + 0.0722 * linearizeChannel(b);
6135
+ }
6136
+ function contrastRatioFromLuminance(l1, l2) {
6137
+ const lighter = Math.max(l1, l2);
6138
+ const darker = Math.min(l1, l2);
6139
+ return (lighter + 0.05) / (darker + 0.05);
6140
+ }
6141
+ function parseHex(hex) {
6142
+ const clean = hex.replace("#", "").trim().toLowerCase();
6143
+ if (clean.length === 3) {
6144
+ const r = parseInt(clean.charAt(0) + clean.charAt(0), 16);
6145
+ const g = parseInt(clean.charAt(1) + clean.charAt(1), 16);
6146
+ const b = parseInt(clean.charAt(2) + clean.charAt(2), 16);
6147
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6148
+ return [r, g, b];
6149
+ }
6150
+ if (clean.length === 6) {
6151
+ const r = parseInt(clean.slice(0, 2), 16);
6152
+ const g = parseInt(clean.slice(2, 4), 16);
6153
+ const b = parseInt(clean.slice(4, 6), 16);
6154
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6155
+ return [r, g, b];
6156
+ }
6157
+ return null;
6158
+ }
6159
+ function hslToRgb(h, s, l) {
6160
+ const hn = h / 360;
6161
+ const sn = s / 100;
6162
+ const ln = l / 100;
6163
+ const hue2rgb = (p, q, t) => {
6164
+ let tt = t;
6165
+ if (tt < 0) tt += 1;
6166
+ if (tt > 1) tt -= 1;
6167
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
6168
+ if (tt < 1 / 2) return q;
6169
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
6170
+ return p;
6171
+ };
6172
+ let r, g, b;
6173
+ if (sn === 0) {
6174
+ r = g = b = ln;
6175
+ } else {
6176
+ const q = ln < 0.5 ? ln * (1 + sn) : ln + sn - ln * sn;
6177
+ const p = 2 * ln - q;
6178
+ r = hue2rgb(p, q, hn + 1 / 3);
6179
+ g = hue2rgb(p, q, hn);
6180
+ b = hue2rgb(p, q, hn - 1 / 3);
6181
+ }
6182
+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
6183
+ }
6184
+ function parseHsl(hsl) {
6185
+ let str = hsl.replace(/^hsl\s*\(\s*/i, "").replace(/\s*\)$/, "").trim();
6186
+ str = str.replace(/%/g, "");
6187
+ const parts = str.split(/[\s,]+/).filter(Boolean);
6188
+ if (parts.length !== 3) return null;
6189
+ const h = parseFloat(parts[0]);
6190
+ const s = parseFloat(parts[1]);
6191
+ const l = parseFloat(parts[2]);
6192
+ if (isNaN(h) || isNaN(s) || isNaN(l)) return null;
6193
+ return hslToRgb(h, s, l);
6194
+ }
6195
+ function parseColor(color) {
6196
+ const trimmed = color.trim();
6197
+ if (trimmed.startsWith("#")) return parseHex(trimmed);
6198
+ if (/^hsl\s*\(/i.test(trimmed)) return parseHsl(trimmed);
6199
+ if (/^\d[\d.]*[\s,]+\d[\d.]*%?[\s,]+\d[\d.]*%?$/.test(trimmed)) return parseHsl(trimmed);
6200
+ return null;
6201
+ }
6202
+ function rgbToHex(r, g, b) {
6203
+ return "#" + [r, g, b].map(
6204
+ (c) => Math.max(0, Math.min(255, Math.round(c))).toString(16).padStart(2, "0")
6205
+ ).join("");
6206
+ }
6207
+ function handleCheckContrast(fg, bg) {
6208
+ const fgRgb = parseColor(fg);
6209
+ const bgRgb = parseColor(bg);
6210
+ if (!fgRgb) throw new Error(`Cannot parse foreground color: "${fg}"`);
6211
+ if (!bgRgb) throw new Error(`Cannot parse background color: "${bg}"`);
6212
+ const fgL = relativeLuminance(...fgRgb);
6213
+ const bgL = relativeLuminance(...bgRgb);
6214
+ const ratio = parseFloat(contrastRatioFromLuminance(fgL, bgL).toFixed(2));
6215
+ return {
6216
+ fgHex: rgbToHex(...fgRgb),
6217
+ bgHex: rgbToHex(...bgRgb),
6218
+ ratio,
6219
+ aa: ratio >= 4.5,
6220
+ aaLarge: ratio >= 3,
6221
+ aaa: ratio >= 7,
6222
+ aaaLarge: ratio >= 4.5
6223
+ };
6224
+ }
6225
+ function handleDeriveAccessiblePalette(seed, targetRatio) {
6226
+ const seedRgb = parseColor(seed);
6227
+ if (!seedRgb) throw new Error(`Cannot parse seed color: "${seed}"`);
6228
+ const seedHex = rgbToHex(...seedRgb);
6229
+ const seedL = relativeLuminance(...seedRgb);
6230
+ const whiteRatio = parseFloat(contrastRatioFromLuminance(1, seedL).toFixed(2));
6231
+ const blackRatio = parseFloat(contrastRatioFromLuminance(0, seedL).toFixed(2));
6232
+ const whiteWorks = whiteRatio >= targetRatio;
6233
+ const blackWorks = blackRatio >= targetRatio;
6234
+ let strategy;
6235
+ let foreground;
6236
+ let ratio;
6237
+ let alternativeForeground;
6238
+ let alternativeRatio;
6239
+ if (blackWorks && whiteWorks) {
6240
+ if (blackRatio >= whiteRatio) {
6241
+ strategy = "black";
6242
+ foreground = "#000000";
6243
+ ratio = blackRatio;
6244
+ alternativeForeground = "#ffffff";
6245
+ alternativeRatio = whiteRatio;
6246
+ } else {
6247
+ strategy = "white";
6248
+ foreground = "#ffffff";
6249
+ ratio = whiteRatio;
6250
+ alternativeForeground = "#000000";
6251
+ alternativeRatio = blackRatio;
6252
+ }
6253
+ } else if (blackWorks) {
6254
+ strategy = "black";
6255
+ foreground = "#000000";
6256
+ ratio = blackRatio;
6257
+ alternativeForeground = "#ffffff";
6258
+ alternativeRatio = whiteRatio;
6259
+ } else if (whiteWorks) {
6260
+ strategy = "white";
6261
+ foreground = "#ffffff";
6262
+ ratio = whiteRatio;
6263
+ alternativeForeground = "#000000";
6264
+ alternativeRatio = blackRatio;
6265
+ } else {
6266
+ strategy = "unachievable";
6267
+ if (blackRatio >= whiteRatio) {
6268
+ foreground = "#000000";
6269
+ ratio = blackRatio;
6270
+ alternativeForeground = "#ffffff";
6271
+ alternativeRatio = whiteRatio;
6272
+ } else {
6273
+ foreground = "#ffffff";
6274
+ ratio = whiteRatio;
6275
+ alternativeForeground = "#000000";
6276
+ alternativeRatio = blackRatio;
6277
+ }
6278
+ }
6279
+ return {
6280
+ seedHex,
6281
+ foreground,
6282
+ ratio,
6283
+ aa: ratio >= 4.5,
6284
+ aaLarge: ratio >= 3,
6285
+ aaa: ratio >= 7,
6286
+ meetsTarget: ratio >= targetRatio,
6287
+ strategy,
6288
+ alternativeForeground,
6289
+ alternativeRatio
6290
+ };
6291
+ }
6292
+ var PASS = "[PASS]";
6293
+ var FAIL = "[FAIL]";
6294
+ var mark = (ok) => ok ? PASS : FAIL;
6295
+ function registerContrastTools(server2) {
6296
+ server2.tool(
6297
+ "stackwright_pro_check_contrast",
6298
+ 'Compute the exact WCAG 2.1 contrast ratio between a foreground and background color. Returns the ratio and AA/AAA pass/fail flags. Use this to verify any foreground/background color pair before writing it to the token set. Accepts #RGB, #RRGGBB, hsl(...), or shadcn HSL format ("H S% L%").',
6299
+ {
6300
+ fg: z18.string().describe("Foreground (text) color \u2014 hex or HSL"),
6301
+ bg: z18.string().describe("Background color \u2014 hex or HSL")
6302
+ },
6303
+ async ({ fg, bg }) => {
6304
+ let result;
6305
+ try {
6306
+ result = handleCheckContrast(fg, bg);
6307
+ } catch (err) {
6308
+ return {
6309
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6310
+ };
6311
+ }
6312
+ const text = [
6313
+ `WCAG 2.1 Contrast Check`,
6314
+ ``,
6315
+ ` Foreground : ${result.fgHex}`,
6316
+ ` Background : ${result.bgHex}`,
6317
+ ` Ratio : ${result.ratio}:1`,
6318
+ ``,
6319
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6320
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6321
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6322
+ ` ${mark(result.aaaLarge)} AAA \u2014 large text (\u22654.5:1)`
6323
+ ].join("\n");
6324
+ return { content: [{ type: "text", text }] };
6325
+ }
6326
+ );
6327
+ server2.tool(
6328
+ "stackwright_pro_derive_accessible_palette",
6329
+ 'Given a seed color (treated as a background), derive the best accessible foreground (text) color that meets the target contrast ratio. Evaluates #ffffff and #000000 against the seed and picks whichever satisfies the target ratio with the highest contrast. Use this for every {name}-foreground token derivation instead of guessing white vs black. Accepts #RGB, #RRGGBB, hsl(...), or shadcn HSL format ("H S% L%").',
6330
+ {
6331
+ seed: z18.string().describe("Background (seed) color \u2014 hex or HSL"),
6332
+ targetRatio: numCoerce(z18.number().default(4.5)).describe(
6333
+ "Minimum required contrast ratio (default 4.5 for WCAG AA)"
6334
+ )
6335
+ },
6336
+ async ({ seed, targetRatio }) => {
6337
+ let result;
6338
+ try {
6339
+ result = handleDeriveAccessiblePalette(seed, targetRatio ?? 4.5);
6340
+ } catch (err) {
6341
+ return {
6342
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6343
+ };
6344
+ }
6345
+ const metLine = result.meetsTarget ? `${PASS} Meets target (${targetRatio}:1)` : `${FAIL} Target (${targetRatio}:1) UNACHIEVABLE with white or black \u2014 best available used`;
6346
+ const altNote = result.alternativeRatio >= (targetRatio ?? 4.5) ? `also passes (${result.alternativeRatio}:1)` : `fails at ${result.alternativeRatio}:1`;
6347
+ const text = [
6348
+ `Accessible Palette Derivation`,
6349
+ ``,
6350
+ ` Background (seed) : ${result.seedHex}`,
6351
+ ` Foreground : ${result.foreground} (${result.strategy})`,
6352
+ ` Contrast ratio : ${result.ratio}:1`,
6353
+ ` ${metLine}`,
6354
+ ``,
6355
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6356
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6357
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6358
+ ``,
6359
+ ` Alternative (${result.alternativeForeground}): ${altNote}`
6360
+ ].join("\n");
6361
+ return { content: [{ type: "text", text }] };
6362
+ }
6363
+ );
6364
+ }
6365
+
3424
6366
  // package.json
3425
6367
  var package_default = {
3426
6368
  dependencies: {
3427
6369
  "@modelcontextprotocol/sdk": "^1.10.0",
3428
6370
  "@stackwright-pro/cli-data-explorer": "workspace:*",
3429
- zod: "^4.3.6"
6371
+ "@stackwright-pro/types": "workspace:*",
6372
+ "@types/js-yaml": "^4.0.9",
6373
+ "js-yaml": "^4.2.0",
6374
+ zod: "^4.4.3"
3430
6375
  },
3431
6376
  devDependencies: {
3432
- "@types/node": "^24.1.0",
3433
- tsup: "^8.5.0",
3434
- typescript: "^5.8.3",
3435
- vitest: "^4.0.18"
6377
+ "@types/node": "catalog:",
6378
+ tsup: "catalog:",
6379
+ typescript: "catalog:",
6380
+ vitest: "catalog:"
3436
6381
  },
3437
6382
  scripts: {
3438
6383
  prepublishOnly: "node scripts/verify-integrity-sync.js",
@@ -3443,10 +6388,13 @@ var package_default = {
3443
6388
  "test:coverage": "vitest run --coverage"
3444
6389
  },
3445
6390
  name: "@stackwright-pro/mcp",
3446
- version: "0.2.0-alpha.8",
6391
+ version: "0.2.0-alpha.81",
3447
6392
  description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3448
- license: "PROPRIETARY",
6393
+ license: "SEE LICENSE IN LICENSE",
3449
6394
  main: "./dist/server.js",
6395
+ bin: {
6396
+ "stackwright-pro-mcp": "./dist/server.js"
6397
+ },
3450
6398
  module: "./dist/server.mjs",
3451
6399
  types: "./dist/server.d.ts",
3452
6400
  exports: {
@@ -3459,6 +6407,11 @@ var package_default = {
3459
6407
  types: "./dist/integrity.d.ts",
3460
6408
  import: "./dist/integrity.mjs",
3461
6409
  require: "./dist/integrity.js"
6410
+ },
6411
+ "./type-schemas": {
6412
+ types: "./dist/tools/type-schemas.d.ts",
6413
+ import: "./dist/tools/type-schemas.mjs",
6414
+ require: "./dist/tools/type-schemas.js"
3462
6415
  }
3463
6416
  },
3464
6417
  files: [
@@ -3486,9 +6439,24 @@ registerPipelineTools(server);
3486
6439
  registerSafeWriteTools(server);
3487
6440
  registerAuthTools(server);
3488
6441
  registerIntegrityTools(server);
6442
+ registerArtifactSigningTools(server);
3489
6443
  registerDomainTools(server);
6444
+ registerTypeSchemasTool(server);
6445
+ registerValidateYamlFragmentTool(server);
6446
+ registerGetSchemaTool(server);
6447
+ registerScaffoldCleanupTools(server);
6448
+ registerContrastTools(server);
3490
6449
  async function main() {
3491
6450
  const transport = new StdioServerTransport();
6451
+ try {
6452
+ const servicesRegisterPkg = "@stackwright-services/mcp/register";
6453
+ const mod = await import(servicesRegisterPkg);
6454
+ if (typeof mod.registerServicesTools === "function") {
6455
+ mod.registerServicesTools(server);
6456
+ console.error("Stackwright Services tools registered on pro MCP");
6457
+ }
6458
+ } catch {
6459
+ }
3492
6460
  await server.connect(transport);
3493
6461
  console.error("Stackwright Pro MCP server running on stdio");
3494
6462
  }