@exaudeus/workrail 3.17.0 → 3.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "workflow-for-workflows",
3
- "name": "Progressive Workflow Creation Guide",
4
- "version": "0.1.0",
5
- "description": "Use this to author or modernize a WorkRail workflow. Guides through understanding the task, defining effectiveness targets, designing architecture and quality gates, drafting, validating, and handing off.",
3
+ "name": "Workflow Authoring Workflow (Quality Gate v2)",
4
+ "version": "2.4.0",
5
+ "description": "Use this to author or modernize a WorkRail workflow. Guides through understanding the task, defining effectiveness targets, designing architecture and quality gates, drafting, validating, assigning tags, and handing off.",
6
6
  "about": "## Workflow Authoring Workflow\n\nThis is the standard WorkRail workflow for creating a new workflow from scratch or modernizing an existing one. It is the trust gate for all other workflows: a workflow is not considered production-ready until it has passed through here.\n\n**What it does:**\nThe workflow walks through the full authoring lifecycle: understanding the task, choosing the right baseline and archetype, designing the phase and quality-gate architecture, drafting the workflow JSON, running structural validators, auditing state fields for bloat, simulating execution against real scenarios, running an adversarial quality review, and producing a final trust handoff. For modernization tasks it builds a value inventory first to ensure enforcement mechanisms, domain knowledge, and behavioral rules are preserved or equivalently replaced.\n\n**When to use it:**\n- You want to author a new WorkRail workflow for a recurring task or problem\n- You have an existing workflow that is outdated, uses legacy patterns (pseudo-DSL, regex validation, satisfaction-score loops), or produces shallow results\n- You want a workflow that will pass the WorkRail quality bar and be trusted to run in production\n\n**What it produces:**\nA validated, tagged workflow JSON file with a `validatedAgainstSpecVersion` stamp. A final trust handoff with readiness verdict, known failure modes, residual weaknesses, and testing guidance.\n\n**How to get good results:**\nDescribe the recurring task the workflow should solve, who will run it, and what a satisfying result looks like. For modernization, point to the existing workflow file. The workflow reads the schema and authoring spec itself -- you do not need to know the JSON format in advance.",
7
7
  "examples": [
8
8
  "Create a new workflow for conducting weekly engineering retrospectives",
@@ -10,44 +10,34 @@
10
10
  "Author a workflow for triaging and prioritizing incoming support tickets",
11
11
  "Upgrade the code review workflow to add adversarial reviewer families and hard gates"
12
12
  ],
13
- "clarificationPrompts": [
14
- "What's your experience level with workflow creation? (New to this / Some experience / Very experienced)",
15
- "What type of workflow are you creating? (e.g., coding, analysis, content creation, process management)",
16
- "What recurring problem or task should this workflow solve?",
17
- "Who is the intended audience for this workflow? (e.g., beginners, experts, specific roles)",
18
- "Are there any specific constraints or requirements for this workflow?"
13
+ "recommendedPreferences": {
14
+ "recommendedAutonomy": "guided",
15
+ "recommendedRiskPolicy": "conservative"
16
+ },
17
+ "features": [
18
+ "wr.features.subagent_guidance"
19
19
  ],
20
20
  "preconditions": [
21
- "User has a clear idea of the recurring task or problem the new workflow should solve.",
22
- "The agent has access to 'create_file', 'edit_file', 'run_terminal_cmd', 'workflow_validate_json', and 'workflow_validate' tools."
21
+ "User has a recurring task or problem a workflow should solve, or an existing workflow that should be modernized.",
22
+ "Agent has access to file creation, editing, and terminal tools.",
23
+ "Agent can run workflow validators such as `npm run validate:registry` or equivalent."
23
24
  ],
24
25
  "metaGuidance": [
25
- "fun adaptToPath(content) = 'Deliver {content} with appropriate depth based on learningPath: basic=detailed explanations, intermediate=efficient guidance, advanced=expert context.'",
26
- "fun createWorkflowFile(template) = 'After getting filename, create file using {template}. Use adaptToPath() for explanations as you guide through structure.'",
27
- "fun runValidation(depth) = 'Execute workflow_validate_json for validation. Use adaptToPath() for error explanations: basic=step-by-step teaching, intermediate=systematic analysis, advanced=architectural review.'",
28
- "fun agentInstruct(action) = 'Agent: {action}. Confirm with user before proceeding with file modifications.'",
29
- "fun useEditFile(purpose) = 'Use edit_file for {purpose}. Explain changes and validate with workflow_validate.'",
30
- "fun teachFeature(feature, context) = 'Introduce {feature} progressively. Use adaptToPath() for explanation depth. Even basic users learn advanced features when {context} demands it.'",
31
- "fun gatherDiscovery(focus) = 'Ask 2-3 focused questions about {focus}. Store responses in context.discoveryData. Be conversational and build on previous answers.'",
32
- "fun analyzeGaps() = 'Review discoveryData for missing critical information. Identify next area to explore. Set context.questionFocus for next iteration.'",
33
- "fun checkConvergence() = 'Evaluate if discovery is sufficient: clear problem, user needs, success criteria defined. Set context.discoveryComplete=true if ready.'",
34
- "fun analyzeComplexity(data) = 'Score workflow complexity 1-10 based on {data}. Consider: number of steps, decision branches, integrations, error handling needs.'",
35
- "fun suggestSteps(outline) = 'Expand {outline} into full step with prompt, agentRole, guidance using AI pattern recognition from similar workflows.'",
36
- "fun visualizeWorkflow() = 'Generate Mermaid diagram showing complete workflow flow, decision points, loops, and context variable usage.'",
37
- "fun getSchema() = 'Use workflow_get_schema to retrieve current schema. Reference when building workflow structure to ensure compliance.'",
38
- "PROGRESSIVE LEARNING: adaptToPath() throughout - detailed for basic, balanced for intermediate, expert for advanced.",
39
- "QUALITY FOCUS: All paths produce sophisticated workflows. Difference is in teaching approach, not final capability.",
40
- "The goal is to create a *reusable template*, not a single-use script. Use placeholders like [User provides X] where appropriate.",
41
- "Prompts should define goals and roles for the agent, not a rigid script. This allows the agent to use its intelligence to best achieve the task.",
42
- "agentInstruct() before file modifications or commands.",
43
- "Maintain a clear distinction between the workflow being created and this meta-workflow.",
44
- "Save progress frequently by confirming file edits.",
45
- "TOOL INTEGRATION: Use workflow_list/workflow_get for discovery, runValidation() for comprehensive checks, workflow_validate for step validation.",
46
- "When validation fails, use detailed error messages to guide improvements rather than guessing at fixes.",
47
- "teachFeature() progressively within each path based on use case needs.",
48
- "When you see function calls like adaptToPath() or createWorkflowFile(), refer to the function definitions above for full instructions.",
49
- "Phase 6 DSL Optimization: For intermediate/advanced users with complex workflows, consider Function Reference Pattern to reduce duplication.",
50
- "SCHEMA FIRST: Always getSchema() at start of Phase 2 to ensure compliance with current workflow schema version and structure."
26
+ "REFERENCE HIERARCHY: treat workflow-schema as legal truth for structure. Treat authoring-spec as canonical current guidance for what makes a workflow good. Treat authoring-provenance as optional maintainer context only.",
27
+ "META DISTINCTION: you are authoring or modernizing a workflow, not executing one. Keep the authored workflow's concerns separate from this meta-workflow's execution.",
28
+ "QUALITY-GATE ROLE: this workflow is the trust gate for other workflows. It must optimize not only for validity and modern authoring, but also for task effectiveness, false-confidence resistance, and future maintainability.",
29
+ "DEFAULT BEHAVIOR: self-execute with tools. Only ask the user for business decisions about the workflow being authored or modernized, not things you can learn from the schema, authoring spec, or example workflows.",
30
+ "AUTHORED VOICE: prompts in the authored workflow must be user-voiced. No middleware narration, no pseudo-DSL, no tutorial framing, no teaching-product language.",
31
+ "BASELINE DISCIPLINE: choose both an authoring baseline and an outcome baseline whenever possible. Copy structural patterns, not domain language.",
32
+ "VALIDATION GATE: validate with real validators, not regex approximations. When validator output and authoring assumptions conflict, runtime wins.",
33
+ "DEEP REVIEW: authoring integrity and outcome effectiveness are separate concerns. A workflow is not ready unless both pass.",
34
+ "THOROUGH MODE: for complex or high-trust workflow work, prefer the deepest review path: state economy audit, execution simulation, adversarial review, and redesign if hard gates fail.",
35
+ "ARTIFACT STRATEGY: the workflow JSON file is the primary output. Intermediate notes go in output.notesMarkdown. Do not create extra planning artifacts unless the workflow is genuinely complex.",
36
+ "V2 DURABILITY: use output.notesMarkdown as the primary durable record. Do not mirror execution state into CONTEXT.md or markdown checkpoint files.",
37
+ "ANTI-PATTERNS TO AVOID IN AUTHORED WORKFLOWS: no pseudo-function metaGuidance, no learning-path branching, no satisfaction-score loops, no heavy clarification batteries, no regex-as-primary-validation, no celebration phases.",
38
+ "MODERNIZATION DISTINCTION: remove format problems (pseudo-DSL, regex, A/B phases). Preserve or equivalently replace behavioral mechanisms (forcing functions, hard gates, domain knowledge). Never silently drop a mechanism that prevents a real failure mode.",
39
+ "EQUIVALENT REPLACEMENT: a replacement only qualifies if it prevents the same failure mode with similar enforcement strength. A rubric suggestion is not equivalent to a hard gate. Document the tradeoff explicitly when the replacement is weaker.",
40
+ "NEVER COMMIT MARKDOWN FILES UNLESS USER EXPLICITLY ASKS."
51
41
  ],
52
42
  "references": [
53
43
  {
@@ -55,7 +45,7 @@
55
45
  "title": "Workflow JSON Schema",
56
46
  "source": "spec/workflow.schema.json",
57
47
  "resolveFrom": "package",
58
- "purpose": "Canonical schema for validating structure and field semantics while authoring workflows.",
48
+ "purpose": "Canonical schema for validating structure and field semantics while authoring workflows. This is legal truth.",
59
49
  "authoritative": true
60
50
  },
61
51
  {
@@ -63,7 +53,7 @@
63
53
  "title": "Workflow Authoring Specification",
64
54
  "source": "spec/authoring-spec.json",
65
55
  "resolveFrom": "package",
66
- "purpose": "Canonical authoring guidance, rule levels, and examples for composing workflows correctly.",
56
+ "purpose": "Canonical authoring guidance, rule levels, and examples for composing workflows correctly. This is current authoring truth.",
67
57
  "authoritative": true
68
58
  },
69
59
  {
@@ -71,491 +61,611 @@
71
61
  "title": "Workflow Authoring Provenance",
72
62
  "source": "spec/authoring-spec.provenance.json",
73
63
  "resolveFrom": "package",
74
- "purpose": "Source-of-truth map showing what is canonical, derived, and non-canonical in workflow authoring guidance.",
64
+ "purpose": "Source-of-truth map showing what is canonical, derived, and non-canonical in workflow authoring guidance. Optional maintainer context.",
65
+ "authoritative": false
66
+ },
67
+ {
68
+ "id": "authoring-guide-v2",
69
+ "title": "Workflow Authoring Guide (v2)",
70
+ "source": "docs/authoring-v2.md",
71
+ "resolveFrom": "workspace",
72
+ "purpose": "Current v2 authoring principles, references guidance, and durable execution patterns.",
73
+ "authoritative": true
74
+ },
75
+ {
76
+ "id": "workflow-authoring-reference",
77
+ "title": "Workflow Authoring Reference",
78
+ "source": "docs/design/workflow-authoring-v2.md",
79
+ "resolveFrom": "workspace",
80
+ "purpose": "Detailed v2 workflow authoring patterns for loops, conditions, references, and workflow structure.",
81
+ "authoritative": true
82
+ },
83
+ {
84
+ "id": "routines-guide",
85
+ "title": "Routines Guide",
86
+ "source": "docs/design/routines-guide.md",
87
+ "resolveFrom": "workspace",
88
+ "purpose": "Current guide for deciding when to use delegation, direct execution, or template injection in authored workflows.",
89
+ "authoritative": false
90
+ },
91
+ {
92
+ "id": "lean-coding-workflow",
93
+ "title": "Lean Coding Workflow (Modern Authoring Baseline)",
94
+ "source": "workflows/coding-task-workflow-agentic.lean.v2.json",
95
+ "resolveFrom": "package",
96
+ "purpose": "Strong modern example for engine-native authoring patterns, loop semantics, prompt density, and bounded delegation.",
97
+ "authoritative": false
98
+ },
99
+ {
100
+ "id": "mr-review-workflow",
101
+ "title": "MR Review Workflow (Outcome Baseline Example)",
102
+ "source": "workflows/mr-review-workflow.agentic.v2.json",
103
+ "resolveFrom": "package",
104
+ "purpose": "Strong example of hypothesis, neutral fact packet, reviewer families, contradiction synthesis, final validation, and a three-dimension orthogonal assessment gate.",
105
+ "authoritative": false
106
+ },
107
+ {
108
+ "id": "bug-investigation-workflow",
109
+ "title": "Bug Investigation Workflow (Assessment Gate Example)",
110
+ "source": "workflows/bug-investigation.agentic.v2.json",
111
+ "resolveFrom": "package",
112
+ "purpose": "Simpler example of a single-dimension assessment gate on a final validation step before handoff.",
113
+ "authoritative": false
114
+ },
115
+ {
116
+ "id": "readiness-audit-workflow",
117
+ "title": "Production Readiness Audit (Audit Baseline Example)",
118
+ "source": "workflows/production-readiness-audit.json",
119
+ "resolveFrom": "package",
120
+ "purpose": "Example of a thorough evidence-driven audit workflow with explicit reviewer-family structure and confidence handling.",
75
121
  "authoritative": false
76
122
  }
77
123
  ],
78
124
  "steps": [
79
125
  {
80
- "id": "phase-0-discovery-loop",
81
- "type": "loop",
82
- "title": "Phase 0: Adaptive Discovery & Requirements Analysis",
83
- "loop": {
84
- "type": "while",
85
- "condition": {
86
- "and": [
87
- {
88
- "var": "discoveryComplete",
89
- "not_equals": true
90
- },
126
+ "id": "phase-0-understand-and-classify",
127
+ "title": "Phase 0: Understand and Classify the Authoring Task",
128
+ "promptBlocks": {
129
+ "goal": "Understand what workflow you are authoring or modernizing, and classify the task before you design anything.",
130
+ "constraints": [
131
+ [
91
132
  {
92
- "var": "discoveryIteration",
93
- "lt": 5
133
+ "kind": "ref",
134
+ "refId": "wr.refs.notes_first_durability"
94
135
  }
95
- ]
96
- },
97
- "maxIterations": 5
98
- },
99
- "body": [
100
- {
101
- "id": "discovery-iteration",
102
- "title": "Discovery Iteration: Gathering Requirements",
103
- "prompt": "gatherDiscovery(current focus area)\n\n**Current Focus:** Understanding the workflow requirements\n\nAgent: For iteration 1, ask the 3 core questions about problem, users, and success. For later iterations, ask targeted follow-ups based on context.questionFocus and context.focusedQuestions.\n\n**Core Questions (Iteration 1):**\n1. What specific, recurring task or problem will this workflow solve?\n2. Who will use this workflow and approximately how often?\n3. What does a successful outcome look like?\n\n**Follow-up Areas (Iterations 2+):**\n- Technical: Integration points, tools, error handling\n- Process: Decision branches, approvals, handoffs\n- Scale: Frequency, user count, growth expectations\n- Constraints: Time limits, compliance, resources",
104
- "agentRole": "You are an adaptive discovery specialist. For iteration 1, ask the core questions. For subsequent iterations, analyze context.discoveryData to identify gaps and ask targeted follow-ups. Store all responses in context.discoveryData. Be conversational and acknowledge previous answers.",
105
- "guidance": [
106
- "ITERATION 1: Focus on problem, users, and success criteria only",
107
- "ITERATION 2+: Based on problem type, explore: technical requirements OR process flows OR creative iterations OR data handling",
108
- "BUILD CONTEXT: Reference previous answers when asking follow-ups",
109
- "STAY FOCUSED: Maximum 3 questions per iteration to avoid overwhelming",
110
- "CONVERGENCE: After each iteration, analyzeGaps() and checkConvergence()"
111
- ],
112
- "requireConfirmation": false
113
- },
114
- {
115
- "id": "discovery-analysis",
116
- "title": "Analyzing Discovery Progress",
117
- "prompt": "analyzeGaps() to identify what's still needed.\n\n**AI-Powered Analysis:**\n- Pattern recognition: Based on similar workflows, what requirements are commonly missed?\n- Implicit needs: What hasn't been stated but is likely needed?\n- Optimization opportunities: Where could this workflow benefit from advanced features?\n\nReview the discovery data collected so far and determine:\n1. What critical information is still missing?\n2. Which area should we explore next?\n3. Are we ready to proceed to synthesis?\n\ncheckConvergence() to determine if we have enough information.\n\nAgent: Use pattern recognition to suggest unexplored areas. Set context.questionFocus for next iteration. Increment context.discoveryIteration.",
118
- "agentRole": "You are a discovery analyst. Review all collected data, identify critical gaps, and determine the next area to explore. Common follow-up areas: integration points, error handling, decision branches, constraints, scale/frequency, evolution needs.",
119
- "guidance": [
120
- "CHECK COMPLETENESS: Problem clarity, user needs, success criteria, basic constraints",
121
- "IDENTIFY GAPS: What's critical but missing? Focus on one area at a time",
122
- "SET FOCUS: Update questionFocus with specific area (e.g., 'integration requirements', 'error handling', 'decision points')",
123
- "GENERATE QUESTIONS: Set context.focusedQuestions with 2-3 specific questions for next iteration",
124
- "KNOW WHEN TO STOP: Don't over-analyze; 80% complete is often enough"
125
136
  ],
126
- "requireConfirmation": false
137
+ "Explore first. Ask the user only what you genuinely cannot determine with tools and references.",
138
+ "Choose baselines as models, not templates. Copy structural patterns, not another workflow's domain voice."
139
+ ],
140
+ "procedure": [
141
+ "Read the schema, authoring spec, v2 authoring guides, and the strongest relevant example workflows.",
142
+ "Decide `authoringMode`: `create` or `modernize_existing`.",
143
+ "Classify the target workflow archetype: `review_audit`, `coding_execution`, `diagnostic_investigation`, `planning_design`, `linear_operational`, or `content_analysis`.",
144
+ "Classify `workflowComplexity`: Simple, Medium, or Complex. Classify `rigorMode`: QUICK, STANDARD, or THOROUGH.",
145
+ "Choose an `authoringBaseline` for engine-native authoring quality and an `outcomeBaseline` for the kind of job the authored workflow should perform. If no good baseline exists for one of them, set it to `none` and explain why.",
146
+ "If `authoringMode = modernize_existing`, build a value inventory BEFORE forming opinions about what to change. Read the original and classify each meaningful mechanism: (1) enforcement mechanisms (forcing functions, hard gates, required outputs), (2) domain knowledge (problem-specific principles the agent would not otherwise know), (3) behavioral rules (persistent constraints on how the agent works). This inventory is the preservation checklist.",
147
+ "If `authoringMode = modernize_existing`, identify what must stay the same about purpose, what feels stale, and what modernization constraints apply."
148
+ ],
149
+ "outputRequired": {
150
+ "notesMarkdown": "Task understanding, baseline choices, patterns to borrow or avoid, and any real open questions.",
151
+ "context": "Capture authoringMode, workflowArchetype, workflowComplexity, rigorMode, taskDescription, intendedAudience, successCriteria, domainConstraints, targetWorkflowPath, modernizationGoals, authoringBaseline, outcomeBaseline, baselineDecisionRationale, authoringPatternsToBorrow, outcomePatternsToBorrow, patternsToAvoid, openQuestions, and valueInventory (modernize_existing only)."
127
152
  },
128
- {
129
- "id": "discovery-loop-decision",
130
- "title": "Discovery Loop Decision",
131
- "prompt": "**Provide a loop control decision artifact.**\n\nBased on the discovery analysis above, decide whether to continue gathering requirements or proceed to synthesis.\n\n**Decision logic:**\n- If critical information is still missing (problem unclear, user needs undefined, success criteria absent): decision = 'continue'\n- If discovery is 80%+ complete (clear problem, user needs, success criteria, basic constraints): decision = 'stop'\n\n**Output (exact format):**\nProvide a loop control artifact:\n```json\n{\n \"artifacts\": [{\n \"kind\": \"wr.loop_control\",\n \"decision\": \"continue\",\n \"metadata\": {\n \"reason\": \"One sentence explaining why continuing or stopping\"\n }\n }]\n}\n```",
132
- "agentRole": "You are a discovery analyst making an explicit go/no-go decision on whether enough requirements have been gathered.",
133
- "requireConfirmation": false,
134
- "outputContract": {
135
- "contractRef": "wr.contracts.loop_control"
136
- }
137
- }
138
- ]
139
- },
140
- {
141
- "id": "discovery-synthesis",
142
- "title": "Discovery Synthesis & Template Matching",
143
- "prompt": "Excellent! I now have a comprehensive understanding of your workflow needs.\n\n**Discovery Summary:**\nAgent: Summarize the key findings from context.discoveryData in a structured format.\n\n**Next Steps:**\n1. I'll synthesize this into a refined problem statement\n2. Use workflow_list and workflow_get to find suitable templates\n3. getSchema() to ensure we build on the latest workflow structure\n4. Present recommendations based on structural patterns\n\nAgent: Create a concise problem statement. Search for workflows with similar patterns (not necessarily same domain). A 'bug investigation' workflow might be perfect for a 'customer complaint' workflow if they share similar structures.",
144
- "agentRole": "You are a workflow synthesis expert. Compile all discovery data into a clear, actionable problem statement. Use workflow_list and workflow_get to find templates based on structural similarity. Present 2-3 best matches with explanations.",
145
- "guidance": [
146
- "SYNTHESIZE: Create clear, one-paragraph problem statement",
147
- "PATTERN MATCH: Focus on workflow structure, not domain",
148
- "RECOMMEND: Present 2-3 template options with rationale",
149
- "CONFIRM: Get user agreement before proceeding to learning path selection"
150
- ],
151
- "askForFiles": true,
153
+ "verify": [
154
+ "The task is understood well enough to design the workflow without guessing blindly.",
155
+ "Both authoring and outcome baselines are explicit, or their absence is justified."
156
+ ]
157
+ },
152
158
  "requireConfirmation": true
153
159
  },
154
160
  {
155
- "id": "phase-1-25-complexity-analysis",
156
- "title": "Phase 1.25: Workflow Complexity Analysis",
157
- "prompt": "Based on the discovery data, I'll analyze the workflow complexity to recommend the best learning path.\n\nanalyzeComplexity(discoveryData)\n\n**Complexity Factors Being Evaluated:**\n- Problem domain complexity (technical depth required)\n- Number of potential decision points\n- Integration requirements (tools, systems, APIs)\n- Error handling and recovery needs\n- Data transformation requirements\n- User expertise vs. task complexity gap\n\n**Scoring Guide:**\n- 1-3: Simple, linear workflows (Basic path ideal)\n- 4-7: Moderate complexity with some branching (Intermediate path recommended)\n- 8-10: Complex with multiple integrations/decisions (Advanced path beneficial)\n\nAgent: Calculate complexity score and set context.complexityScore. Determine context.recommendedPath based on score AND user experience. Explain reasoning.",
158
- "agentRole": "You are a workflow complexity analyst. Evaluate the discovered requirements objectively. Consider technical complexity, decision density, integration needs, and error handling requirements. Balance complexity score with user's stated experience level.",
159
- "guidance": [
160
- "OBJECTIVE SCORING: Don't over-complicate simple workflows",
161
- "FACTOR WEIGHTS: Integrations and branching logic add more complexity than step count",
162
- "PATH MATCHING: Score 1-3\u2192basic, 4-7\u2192intermediate, 8-10\u2192advanced, but adjust for user experience",
163
- "EXPLAIN REASONING: Always explain why you scored as you did",
164
- "SET CONTEXT: Store complexityScore, recommendedPath, and complexityFactors in context"
165
- ],
161
+ "id": "phase-1-define-effectiveness-target",
162
+ "title": "Phase 1: Define the Effectiveness Target",
163
+ "promptBlocks": {
164
+ "goal": "Define what success should feel like for the authored workflow, not just what fields it should contain.",
165
+ "constraints": [
166
+ "Be specific about user satisfaction and dangerous false-confidence outcomes.",
167
+ "Distinguish a technically valid workflow from a satisfying one."
168
+ ],
169
+ "procedure": [
170
+ "State what result the authored workflow should reliably produce for its user.",
171
+ "List the criteria that would make the workflow feel genuinely satisfying in practice.",
172
+ "Name the biggest likely failure mode and the most dangerous false-confidence mode.",
173
+ "State what would make the workflow technically correct but still disappointing."
174
+ ],
175
+ "outputRequired": {
176
+ "notesMarkdown": "Effectiveness target, satisfaction criteria, failure modes, and false-confidence risks.",
177
+ "context": "Capture effectivenessTarget, userSatisfactionCriteria, primaryFailureMode, dangerousFalseConfidenceModes, likelyWeakOutcomeModes, and trustRisk."
178
+ },
179
+ "verify": [
180
+ "The authored workflow now has a clear outcome bar, not just an authoring bar."
181
+ ]
182
+ },
166
183
  "requireConfirmation": false
167
184
  },
168
185
  {
169
- "id": "phase-0-5-research",
170
- "title": "Phase 0.5: Deep Research & Inspiration Gathering",
171
- "prompt": "adaptToPath('Enhance your workflow with external knowledge! I'll generate a research prompt for deep analysis on your workflow type's best practices, patterns, and examples. Copy-paste it into ChatGPT/Claude/Gemini, then share the results. We'll synthesize key insights into your workflow ideas.')",
172
- "agentRole": "You are a research specialist with expertise in generating targeted research prompts and synthesizing external knowledge. Generate a tailored prompt like: 'Research top 10 best practices for [workflow type] workflows, focusing on [problem]. Include real-world examples, step patterns, and innovations. Output in structured format: {insights: [], patterns: [], suggestedSteps: []}'. After user provides results, synthesize into workflow recommendations and store in context.researchInsights.",
173
- "guidance": [
174
- "Make research optional for basic path; mandatory for intermediate/advanced.",
175
- "Store synthesized results in context variable 'researchInsights'.",
176
- "Generate research prompts that target external best practices and innovations.",
177
- "Focus on structural patterns that can be adapted to the user's specific domain."
178
- ],
186
+ "id": "phase-2-design-workflow-architecture",
187
+ "title": "Phase 2: Design the Workflow Architecture",
179
188
  "runCondition": {
189
+ "var": "workflowComplexity",
190
+ "not_equals": "Simple"
191
+ },
192
+ "promptBlocks": {
193
+ "goal": "Decide the workflow architecture before you write JSON.",
194
+ "constraints": [
195
+ "Separate workflow architecture from quality-gate architecture. This phase is about the authored workflow itself.",
196
+ "Keep delegation bounded and keep ownership with the main agent."
197
+ ],
198
+ "procedure": [
199
+ "Decide the phase list, one-line goal for each phase, and overall ordering.",
200
+ "Identify meaningful input classifications that require different workflow paths. For each variant dimension, decide the branching mechanism: `runCondition` on separate steps (diverging paths), `promptFragments` (additive behavior on a shared base), or a separate workflow entirely. For each captured variable that drives branching, define its closed set of valid values — unexpected values are a common source of silent misbehavior.",
201
+ "Design loops with explicit exit rules, bounded maxIterations, and real reasons for another pass.",
202
+ "Decide confirmation gates, delegation vs template injection vs direct execution, promptFragments, references, artifacts, and metaGuidance.",
203
+ "If the authored workflow encodes domain knowledge tied to a specific version of an external system or codebase, decide how to handle staleness: prefer reading the codebase at runtime over hardcoding patterns, or explicitly document versioned assumptions so they surface as maintenance debt.",
204
+ "If `authoringMode = modernize_existing`, decide preserve-in-place, restructure, or rewrite. For each item in valueInventory, record: `preserved` (structurally present with equivalent enforcement), `replaced` (new mechanism prevents same failure mode -- justify equivalence), or `dropped` (intentionally removed -- justify the loss). Phase-level mapping alone is insufficient; track what was inside each restructured or removed phase."
205
+ ],
206
+ "outputRequired": {
207
+ "notesMarkdown": "Structured workflow outline, loop design, confirmation design, delegation design, artifact plan, and modernization mapping.",
208
+ "context": "Capture workflowOutline, loopDesign, confirmationDesign, delegationDesign, artifactPlan, contextModel, voiceStrategy, routineAudit, delegationBoundaries, templateInjectionPlan, modernizationStrategy, legacyMapping, behaviorPreservationNotes, and valuePreservationMap (modernize_existing only)."
209
+ },
210
+ "verify": [
211
+ "The authored workflow architecture is coherent before JSON drafting begins."
212
+ ]
213
+ },
214
+ "promptFragments": [
215
+ {
216
+ "id": "phase-2-simple-direct",
217
+ "when": {
218
+ "var": "workflowComplexity",
219
+ "equals": "Simple"
220
+ },
221
+ "text": "For Simple workflows, keep the architecture linear and compact. Do not invent loops or ceremony unless the task truly needs them."
222
+ }
223
+ ],
224
+ "requireConfirmation": {
180
225
  "or": [
181
226
  {
182
- "var": "learningPath",
183
- "equals": "intermediate"
227
+ "var": "workflowComplexity",
228
+ "not_equals": "Simple"
184
229
  },
185
230
  {
186
- "var": "learningPath",
187
- "equals": "advanced"
231
+ "var": "rigorMode",
232
+ "not_equals": "QUICK"
188
233
  }
189
234
  ]
190
- },
191
- "requireConfirmation": true
192
- },
193
- {
194
- "id": "phase-1-assessment",
195
- "title": "Phase 1: Personalized Learning Path Selection",
196
- "prompt": "Excellent! With a clear understanding of your goals, let's choose the best way to build your workflow.\n\n**Complexity Analysis Results:**\nAgent: Display the complexity score, recommended path, and key factors from context.\n\nPlease select your experience level with workflow creation:\n\n\ud83c\udf31 **Basic Path - \"Learn by Doing with Explanation\"**\n - New to workflows or want thorough understanding\n - Step-by-step guidance with detailed explanations\n - Progressive introduction of advanced features with context\n - Focus: Understanding concepts and building confidence\n\n\ud83d\ude80 **Intermediate Path - \"Balanced Guidance with Examples\"**\n - Some experience with automation or process design\n - Structured approach with practical examples\n - Feature recommendations based on your use case\n - Focus: Efficient workflow creation with best practices\n\n\ud83c\udfc6 **Advanced Path - \"Full Features with Expert Context\"**\n - Experienced with workflow/automation tools\n - Comprehensive feature access from the start\n - Architectural guidance and performance considerations\n - Focus: Sophisticated workflow engineering\n\nagentInstruct(set learningPath context variable to user's selection. Highlight which path matches the complexity analysis recommendation.)",
197
- "agentRole": "You are a workflow education specialist and learning path advisor with expertise in adapting technical instruction to different experience levels. Your role is to help users choose the most appropriate learning approach based on their background and goals.",
198
- "guidance": [
199
- "PATH EXPLANATION: Clearly explain what each learning path offers so users can make an informed choice based on the discovery from Phase 0.",
200
- "QUALITY FOCUS: All paths should result in high-quality workflows. The difference is in teaching approach, not final capability."
201
- ],
202
- "requireConfirmation": true
235
+ }
203
236
  },
204
237
  {
205
- "id": "phase-1-5-ideation",
206
- "title": "Phase 1.5: Brainstorm & Ideate Workflow Elements",
207
- "prompt": "teachFeature(brainstorming, using researchInsights). Based on your goals and any research insights gathered, let's brainstorm innovative workflow elements!\n\nI'll generate 3-5 creative ideas for:\n- Unique step sequences that could make your workflow more effective\n- Advanced features that could enhance user experience\n- Innovative patterns adapted from other domains\n- Potential safeguards or quality checks\n\nAfter presenting ideas, we'll discuss pros/cons and refine based on your feedback.",
208
- "agentRole": "You are an ideation expert specializing in workflow innovation. Use research insights (if available) and cross-domain thinking to propose creative, non-generic workflow designs. Present ideas with clear benefits and trade-offs. Store refined ideas in context.ideationNotes.",
209
- "guidance": [
210
- "Integrate 'researchInsights' if available from Phase 0.5",
211
- "Propose both conventional and unconventional approaches",
212
- "Explain how each idea addresses the user's specific goals",
213
- "Store refined/selected ideas in 'ideationNotes' context variable"
214
- ],
215
- "requireConfirmation": true
238
+ "id": "phase-3-design-quality-architecture",
239
+ "title": "Phase 3: Design the Quality-Gate Architecture",
240
+ "promptBlocks": {
241
+ "goal": "Design how the authored workflow will avoid shallow results, false confidence, and state bloat.",
242
+ "constraints": [
243
+ "This phase is about the authored workflow's quality model, not its basic phase list.",
244
+ "Prefer explicit quality structure over hoping the agent will infer it."
245
+ ],
246
+ "procedure": [
247
+ "Decide whether the authored workflow needs a hypothesis step, neutral fact packet, reviewer or validator families, contradiction loop, final validation bundle, or explicit blind-spot handling.",
248
+ "Design the confidence model, blind-spot model, and state economy plan.",
249
+ "Decide the hard-gate dimensions that would make the authored workflow unsafe or unsatisfying if they fail. Choose the right enforcement mechanism for each gate: `assessments` + `assessmentRefs` + `assessmentConsequences` for bounded confidence judgments (each dimension captures a distinct orthogonal failure mode — see `mr-review-workflow.agentic.v2.json` and `bug-investigation.agentic.v2.json`); `validationCriteria` with context-aware conditions for completion-gating on structured checklists or required output content (the engine enforces that required content appears in the response before the step can complete, without a loop — conditions on individual rules can match the workflow's branching context); a re-verification loop for fix-and-verify cycles where the agent must act then prove the action worked. Do not default to a loop when `validationCriteria` is the right tool, or to `requireConfirmation` when a hard gate is needed.",
250
+ "Write the redesign triggers that should force architectural revision rather than cosmetic refinement."
251
+ ],
252
+ "outputRequired": {
253
+ "notesMarkdown": "Quality architecture, confidence model, blind-spot model, state economy plan, and hard-gate triggers.",
254
+ "context": "Capture qualityArchitecture, confidenceModel, blindSpotModel, stateEconomyPlan, reviewBundlePlan, qualityGateTriggers, and hardGateModel."
255
+ },
256
+ "verify": [
257
+ "The authored workflow has an explicit plan for false-confidence resistance and quality review."
258
+ ]
259
+ },
260
+ "requireConfirmation": {
261
+ "or": [
262
+ {
263
+ "var": "rigorMode",
264
+ "equals": "THOROUGH"
265
+ },
266
+ {
267
+ "var": "workflowComplexity",
268
+ "equals": "Complex"
269
+ }
270
+ ]
271
+ }
216
272
  },
217
273
  {
218
- "id": "phase-2-basic",
219
- "runCondition": {
220
- "var": "learningPath",
221
- "equals": "basic"
222
- },
223
- "title": "Phase 2: Guided Workflow Creation (Basic Path)",
224
- "prompt": "Let's create your workflow step-by-step with detailed explanations! \ud83c\udf31\n\n**STEP 0: Schema Foundation**\nFirst, I'll getSchema() to ensure we build on the current workflow structure.\n\n**STEP 1: Create Your Workflow File**\nWhat would you like to name your new workflow file? (e.g., `my-workflow.json`)\n\ncreateWorkflowFile(template from Phase 1)\n\n**STEP 2: Build the Structure Together**\nNow, let's go through each part of your workflow one by one:\n\n1. **Basic Info** (`id`, `name`, `version`, `description`)\n - (Agent: For each field, explain why it matters and help the user craft clear, descriptive content.)\n2. **Setup Requirements** (`preconditions`)\n - (Agent: Explain what preconditions are, why they prevent problems, and ask the user what's needed.)\n3. **Global Rules** (`metaGuidance`)\n - (Agent: Explain the difference between global rules and step-specific instructions, and ask for input.)\n4. **The Action Steps** (`steps`)\n - (Agent: Guide the user in creating simple, linear steps first. When user provides step outline, suggestSteps() to expand into full format. Analyze goal/research for needed features (e.g., conditions for branching, loops for repetition) and teachFeature() if appropriate.)\n5. **Quality Integration**\n - (Agent: useTools() to read docs like naming-conventions.md and suggest pattern integrations based on ideationNotes if available.)\n\n**AI ASSISTANCE:** When you describe a step briefly, I'll help expand it into a complete step with prompt, agentRole, and guidance!\n\n**LEARNING FOCUS:** We'll focus on understanding what each piece does and why it's useful.",
225
- "agentRole": "You are a patient and thorough workflow education instructor specializing in teaching beginners. Your goal is to guide the user collaboratively. Ask for one piece of information at a time, explain the concepts, and wait for their input before proceeding. Your expertise lies in breaking down complex concepts into understandable steps, providing clear explanations for why each element matters, and building user confidence through hands-on learning.",
226
- "guidance": [
227
- "EXPLAIN EVERYTHING: This user is learning. Explain the purpose of each JSON field and workflow concept.",
228
- "PROGRESSIVE FEATURES: Start with basics, introduce advanced features (conditional steps, context variables) when the use case needs them - with full explanations.",
229
- "USE ANALOGIES: Compare workflow concepts to familiar things (recipes, instruction manuals, etc.).",
230
- "ENCOURAGE QUESTIONS: Invite the user to ask about anything that's unclear.",
231
- "QUALITY TEACHING: Even though this is the basic path, don't compromise on workflow quality - just explain more.",
232
- "AI ASSIST: When user provides step outline, use suggestSteps() to expand into full format with all required fields"
233
- ],
234
- "validationCriteria": [
235
- {
236
- "type": "regex",
237
- "pattern": "\"id\":\\s*\"[a-zA-Z0-9_-]+\"",
238
- "message": "Workflow must have a valid id field with alphanumeric characters, underscores, or hyphens"
239
- },
240
- {
241
- "type": "regex",
242
- "pattern": "\"name\":\\s*\"[^\"]{3,}\"",
243
- "message": "Workflow must have a descriptive name (at least 3 characters)"
244
- },
245
- {
246
- "type": "regex",
247
- "pattern": "\"description\":\\s*\"[^\"]{20,}\"",
248
- "message": "Workflow must have a meaningful description (at least 20 characters)"
274
+ "id": "phase-4-draft-or-revise",
275
+ "title": "Phase 4: Draft or Revise the Workflow",
276
+ "promptBlocks": {
277
+ "goal": "Write the workflow JSON file using the architecture and quality model you already chose.",
278
+ "constraints": [
279
+ "The schema defines what is legal. The authoring spec defines what is good.",
280
+ "Write prompts in the user's voice. Vary prompt density by step needs rather than using one density everywhere.",
281
+ "If you are modernizing, preserve what still fits the workflow's purpose. Do not rewrite just because a workflow is old."
282
+ ],
283
+ "procedure": [
284
+ "If `authoringMode = create` and no filename was specified, ask the user for the filename before writing.",
285
+ "If `authoringMode = modernize_existing`, default to editing `targetWorkflowPath` unless there is a strong reason to create a new variant or file.",
286
+ "Write the workflow file. Keep protocol requirements explicit, loops bounded, confirmations meaningful, and metaGuidance clean."
287
+ ],
288
+ "outputRequired": {
289
+ "notesMarkdown": "Draft status and any notable authoring choices that are important to later review.",
290
+ "context": "Capture workflowFilePath and draftComplete."
249
291
  },
292
+ "verify": [
293
+ "The workflow file exists and reflects the chosen architecture rather than an improvised one."
294
+ ]
295
+ },
296
+ "promptFragments": [
250
297
  {
251
- "type": "regex",
252
- "pattern": "\"steps\":\\s*\\[",
253
- "message": "Workflow must have a steps array with at least one step"
298
+ "id": "phase-4-simple-fast",
299
+ "when": {
300
+ "var": "workflowComplexity",
301
+ "equals": "Simple"
302
+ },
303
+ "text": "For Simple workflows, keep the file compact and linear. Do not create extra metaGuidance or loops unless the task truly needs them."
254
304
  }
255
305
  ],
256
- "hasValidation": true
306
+ "requireConfirmation": false
257
307
  },
258
308
  {
259
- "id": "phase-2-intermediate",
260
- "runCondition": {
261
- "var": "learningPath",
262
- "equals": "intermediate"
263
- },
264
- "title": "Phase 2: Structured Workflow Development (Intermediate Path)",
265
- "prompt": "Let's build your workflow with a structured approach and best practices! \ud83d\ude80\n\n**STEP 0: Schema & Foundation**\ngetSchema() to ensure compliance with current workflow structure.\n\n**STEP 1: Initialize Workflow File**\nWhat would you like to name your new workflow file?\n\ncreateWorkflowFile(template from Phase 1)\n\n**STEP 2: Core Structure Development**\nWe'll build your workflow systematically:\n\n1. **Metadata & Identity** (`id`, `name`, `version`, `description`)\n - Focus on discoverability and clear communication.\n2. **Operational Requirements** (`preconditions`, `metaGuidance`)\n - Define what's needed before starting and establish global rules.\n3. **Step Architecture with AI Assistance**\n - Design clear, actionable steps.\n - When you outline a step, I'll suggestSteps() to expand it professionally.\n - Analyze goal/research for needed features (e.g., loops for multi-item processing) and teachFeature() proactively.\n4. **Context Variable Intelligence**\n - I'll analyze your steps and suggest which context variables you'll need for data flow.\n5. **Quality Patterns**\n - useTools() to examine existing workflows and docs to suggest proven patterns from ideationNotes.\n\n**STEP 3: Enhanced Feature Recommendations**\nBased on your workflow's purpose, I may recommend specific features like:\n- **Clarification Prompts**: To gather better input upfront.\n- **Validation Criteria**: For automatic quality checks.\n- **Context Variables**: When you need information to flow between steps.\n- **Conditional Logic**: For workflows with decision points.\n\n(Agent: As you build the steps, proactively recommend these features where they seem appropriate, explaining the benefits. Integrate researchInsights and ideationNotes into recommendations.)\n\n**EFFICIENCY FOCUS:** We'll focus on building a professionally structured workflow with the right features for the job.",
266
- "agentRole": "You are an experienced workflow development consultant with expertise in efficient workflow creation and best practices. You will act as a collaborator, guiding the user through the creation process efficiently. Your role is to guide users through structured development while recommending appropriate features and maintaining professional standards.",
267
- "guidance": [
268
- "STRUCTURED APPROACH: Follow a logical sequence with clear reasoning for each decision.",
269
- "FEATURE RECOMMENDATIONS: Suggest appropriate features based on workflow type and use case.",
270
- "BEST PRACTICES: Share proven patterns and explain why they work.",
271
- "PRACTICAL EXAMPLES: Use real-world scenarios to illustrate concepts.",
272
- "BALANCED DEPTH: Provide enough detail to understand without overwhelming with basics.",
273
- "AI OPTIMIZATION: Use suggestSteps() to expand outlines; analyze steps to suggest context variables",
274
- "PATTERN MATCHING: Leverage AI to identify similar workflow patterns and suggest optimizations"
275
- ],
276
- "validationCriteria": [
277
- {
278
- "type": "regex",
279
- "pattern": "\"id\":\\s*\"[a-zA-Z0-9_-]+\"",
280
- "message": "Workflow must have a valid id field with alphanumeric characters, underscores, or hyphens"
281
- },
282
- {
283
- "type": "regex",
284
- "pattern": "\"name\":\\s*\"[^\"]{3,}\"",
285
- "message": "Workflow must have a descriptive name (at least 3 characters)"
309
+ "id": "phase-5-validate",
310
+ "type": "loop",
311
+ "title": "Phase 5: Structural Validation Loop",
312
+ "loop": {
313
+ "type": "while",
314
+ "conditionSource": {
315
+ "kind": "artifact_contract",
316
+ "contractRef": "wr.contracts.loop_control",
317
+ "loopId": "validation_loop"
286
318
  },
319
+ "maxIterations": 3
320
+ },
321
+ "body": [
287
322
  {
288
- "type": "regex",
289
- "pattern": "\"description\":\\s*\"[^\"]{20,}\"",
290
- "message": "Workflow must have a meaningful description (at least 20 characters)"
323
+ "id": "phase-5a-run-validation",
324
+ "title": "Run Validation",
325
+ "promptBlocks": {
326
+ "goal": "Run the real workflow validators against the drafted workflow.",
327
+ "constraints": [
328
+ "Do not rely on reading the JSON and eyeballing it.",
329
+ "If runtime and authoring assumptions conflict, runtime wins."
330
+ ],
331
+ "procedure": [
332
+ "Run the available validation tools or commands such as `npm run validate:registry`, schema validation, or the MCP validation surface.",
333
+ "If validation fails, list the actual errors, fix them in the workflow file, and re-run validation.",
334
+ "If validation passes cleanly, say so plainly."
335
+ ],
336
+ "outputRequired": {
337
+ "notesMarkdown": "Validation results, actual errors if any, and what was fixed.",
338
+ "context": "Capture validationErrors and validationPassed."
339
+ },
340
+ "verify": [
341
+ "Validation results are based on real validators, not approximations."
342
+ ]
343
+ },
344
+ "promptFragments": [
345
+ {
346
+ "id": "phase-5a-thorough",
347
+ "when": {
348
+ "var": "rigorMode",
349
+ "equals": "THOROUGH"
350
+ },
351
+ "text": "After structural validation passes, also check the workflow manually against required-level authoring-spec rules and fix any failures before moving on."
352
+ }
353
+ ],
354
+ "requireConfirmation": false
291
355
  },
292
356
  {
293
- "type": "regex",
294
- "pattern": "\"steps\":\\s*\\[",
295
- "message": "Workflow must have a steps array with at least one step"
357
+ "id": "phase-5b-loop-decision",
358
+ "title": "Validation Loop Decision",
359
+ "promptBlocks": {
360
+ "goal": "Decide whether structural validation needs another pass.",
361
+ "constraints": [
362
+ "Use validator state, not vibes."
363
+ ],
364
+ "procedure": [
365
+ "If all errors are fixed and validation passes, stop.",
366
+ "If you fixed errors but have not re-validated yet, continue.",
367
+ "If you hit the iteration limit, stop and record what remains."
368
+ ],
369
+ "outputRequired": {
370
+ "artifact": "Emit a `wr.loop_control` artifact for `validation_loop` with `decision` set to `continue` or `stop`."
371
+ },
372
+ "verify": [
373
+ "The loop decision matches the actual validation state."
374
+ ]
375
+ },
376
+ "outputContract": {
377
+ "contractRef": "wr.contracts.loop_control"
378
+ },
379
+ "requireConfirmation": false
296
380
  }
297
- ],
298
- "hasValidation": true
381
+ ]
299
382
  },
300
383
  {
301
- "id": "phase-2-advanced",
384
+ "id": "phase-5-escalation",
385
+ "title": "Validation Escalation",
302
386
  "runCondition": {
303
- "var": "learningPath",
304
- "equals": "advanced"
387
+ "var": "validationPassed",
388
+ "equals": false
305
389
  },
306
- "title": "Phase 2: Comprehensive Workflow Architecture (Advanced Path)",
307
- "prompt": "Let's architect a sophisticated workflow with full feature utilization. \ud83c\udfc6\n\n**STEP 0: Schema & Architecture Foundation**\ngetSchema() to ensure we leverage all available features properly.\n\n**STEP 1: Rapid File Initialization**\nWhat filename shall we use for the new workflow?\n\ncreateWorkflowFile(template foundation) and shift to architectural decisions\n\n**STEP 2: Architectural Design with AI Enhancement**\nLet's discuss the high-level architecture:\n\n1. **Core Architecture** (`id`, `name`, `version`, `description`)\n - Semantic versioning strategy, namespace considerations, API documentation approach.\n2. **Operational Design** (`preconditions`, `metaGuidance`, `contextVariables`)\n - Comprehensive precondition modeling, sophisticated metaGuidance patterns.\n - AI-powered context variable architecture based on data flow analysis.\n3. **Advanced Step Design with Optimization**\n - Trade-offs for conditional logic, validation strategy, performance.\n - suggestSteps() with enterprise patterns when you provide high-level design.\n - AI-suggested step ordering for optimal execution flow.\n4. **Innovation Integration**\n - useTools() to analyze existing enterprise workflows.\n - AI-powered pattern recognition for non-obvious optimizations.\n - Leverage researchInsights for cutting-edge approaches.\n\n**AI ARCHITECTURE ASSISTANT:** I'll analyze your design decisions and suggest:\n- Optimal step sequencing\n- Advanced validation criteria\n- Performance optimizations\n- Scalability considerations\n\n**MASTERY FOCUS:** Creating an enterprise-grade workflow with sophisticated, AI-enhanced architecture.",
308
- "agentRole": "You are a senior workflow architect and systems design expert with deep expertise in enterprise-grade workflow engineering. Your role is to act as an architectural consultant. You will propose design patterns and discuss trade-offs with the user. Your role is to engage in sophisticated technical discussions, propose advanced design patterns, and help users create workflows that meet enterprise standards for scalability, maintainability, and performance.",
309
- "guidance": [
310
- "ARCHITECTURAL THINKING: Focus on design patterns, scalability, and maintainability.",
311
- "FULL FEATURE ACCESS: Leverage the complete feature set appropriately for the use case.",
312
- "PERFORMANCE AWARENESS: Consider efficiency and resource implications.",
313
- "ENTERPRISE PATTERNS: Apply proven enterprise workflow patterns.",
314
- "EXPERT CONTEXT: Assume understanding of complex concepts, focus on sophisticated applications.",
315
- "AI ARCHITECTURE: Use AI to suggest optimal patterns, step ordering, and performance optimizations",
316
- "INNOVATION ENGINE: Leverage AI pattern recognition for non-obvious workflow enhancements"
317
- ],
318
- "validationCriteria": [
319
- {
320
- "type": "regex",
321
- "pattern": "\"id\":\\s*\"[a-zA-Z0-9_-]+\"",
322
- "message": "Workflow must have a valid id field with alphanumeric characters, underscores, or hyphens"
323
- },
324
- {
325
- "type": "regex",
326
- "pattern": "\"name\":\\s*\"[^\"]{3,}\"",
327
- "message": "Workflow must have a descriptive name (at least 3 characters)"
328
- },
329
- {
330
- "type": "regex",
331
- "pattern": "\"description\":\\s*\"[^\"]{20,}\"",
332
- "message": "Workflow must have a meaningful description (at least 20 characters)"
333
- },
334
- {
335
- "type": "regex",
336
- "pattern": "\"steps\":\\s*\\[",
337
- "message": "Workflow must have a steps array with at least one step"
338
- }
339
- ],
340
- "hasValidation": true
390
+ "promptBlocks": {
391
+ "goal": "Do not silently continue with a structurally broken workflow.",
392
+ "constraints": [
393
+ "Present the situation honestly."
394
+ ],
395
+ "procedure": [
396
+ "List the remaining validation errors and assess their severity.",
397
+ "Present the options: proceed with known issues documented, or stop so the user can intervene manually."
398
+ ]
399
+ },
400
+ "requireConfirmation": true
341
401
  },
342
402
  {
343
- "id": "phase-3-4-refinement-loop",
403
+ "id": "phase-6-quality-gate-loop",
344
404
  "type": "loop",
345
- "title": "Phases 3-4: Iterative Validation & Refinement Loop",
405
+ "title": "Phase 6: Quality-Gate Loop",
346
406
  "loop": {
347
407
  "type": "while",
348
- "condition": {
349
- "and": [
350
- {
351
- "var": "satisfactionScore",
352
- "lt": 9
353
- },
354
- {
355
- "var": "iterationCount",
356
- "lt": 3
357
- }
358
- ]
408
+ "conditionSource": {
409
+ "kind": "artifact_contract",
410
+ "contractRef": "wr.contracts.loop_control",
411
+ "loopId": "quality_gate_loop"
359
412
  },
360
- "maxIterations": 3
413
+ "maxIterations": 2
361
414
  },
362
415
  "body": [
363
416
  {
364
- "id": "phase-3-basic",
365
- "runCondition": {
366
- "var": "learningPath",
367
- "equals": "basic"
417
+ "id": "phase-6a-state-economy-audit",
418
+ "title": "State Economy Audit",
419
+ "promptBlocks": {
420
+ "goal": "Check whether every context field in the authored workflow earns its keep.",
421
+ "constraints": [
422
+ "A field is justified only if it materially affects routing, synthesis, confidence, or handoff quality.",
423
+ "Do not keep bookkeeping fields just because they sound organized."
424
+ ],
425
+ "procedure": [
426
+ "For each meaningful captured context field, record where it is set, where it is consumed, what decision or outcome it influences, and what gets worse if it is removed.",
427
+ "Classify each field as `keep`, `wire`, or `remove`.",
428
+ "Fix weak or unused fields directly in the workflow file."
429
+ ],
430
+ "outputRequired": {
431
+ "notesMarkdown": "State field audit with keep/wire/remove decisions and any fixes applied.",
432
+ "context": "Capture stateFieldAudit, unusedOrWeakFields, and stateEconomyPassed."
433
+ },
434
+ "verify": [
435
+ "Weak or unused fields are either wired meaningfully or removed."
436
+ ]
368
437
  },
369
- "title": "Phase 3: Learning Through Validation (Basic Path)",
370
- "prompt": "Great! Your workflow draft is complete. Now let's make sure it works perfectly! \ud83c\udf31\n\n**UNDERSTANDING VALIDATION:**\nValidation is like proofreading - it catches mistakes before they cause problems. Our validation tool will check for issues with syntax, structure, and logic.\n\n**STEP 1: Run Your First Validation**\nrunValidation(basic) with detailed explanations\n\n**STEP 2: Learning from Errors (Don't worry - errors are normal!)**\nIf there are errors, I will guide you through them one at a time:\n1. **Explain the error** in simple terms.\n2. **Show you where** the problem is in the file.\n3. **Explain why** it's a problem.\n4. **Help you fix it** step-by-step.\n5. Then, we'll **rerun validation** to see our progress.\n\n**LEARNING GOAL:** Our goal is to understand what makes a workflow valid and why each rule exists. Every error is a learning opportunity!",
371
- "agentRole": "You are a supportive workflow validation instructor with expertise in teaching through problem-solving. Your goal is to run the validation tool and then guide the user through fixing any errors one by one, explaining each concept as you go. Your role is to turn validation errors into learning opportunities, explaining technical concepts in accessible terms while building user confidence in workflow creation.",
372
- "guidance": [
373
- "EDUCATIONAL APPROACH: Treat each error as a teaching moment. Explain what went wrong and why the rule exists.",
374
- "STEP-BY-STEP FIXES: Guide through each fix individually, don't overwhelm with multiple changes.",
375
- "ENCOURAGE LEARNING: Emphasize that errors are normal and part of the learning process.",
376
- "EXPLAIN THE WHY: Help user understand the reasoning behind validation rules.",
377
- "BUILD CONFIDENCE: Celebrate when validation passes and acknowledge progress."
378
- ],
379
- "requireConfirmation": true
438
+ "requireConfirmation": false
380
439
  },
381
440
  {
382
- "id": "phase-3-intermediate",
383
- "runCondition": {
384
- "var": "learningPath",
385
- "equals": "intermediate"
441
+ "id": "phase-6b-execution-simulation",
442
+ "title": "Execution Simulation",
443
+ "promptBlocks": {
444
+ "goal": "Simulate what would happen if the authored workflow ran on the user's real task.",
445
+ "constraints": [
446
+ "This is about practical utility, not only context-flow correctness.",
447
+ "Flag places where the workflow would produce paperwork, generic output, or false confidence instead of value."
448
+ ],
449
+ "procedure": [
450
+ "Trace the authored workflow step by step against the user's actual task or the closest realistic scenario.",
451
+ "For each step, ask: what would the agent actually do, what context would it have, what would it likely produce, and what would the next step inherit?",
452
+ "Also trace at least one degraded or edge-case path -- not just the happy path. Ask: what happens when a condition evaluates unexpectedly, a loop has nothing to iterate, a runCondition skips a phase, or the user provides minimal input? Quality gates that only protect the happy path are not quality gates.",
453
+ "Identify likely weak steps, likely unsatisfying outputs, and likely false-confidence modes.",
454
+ "For any loop in the workflow, explicitly check: does the exit condition have structural teeth (artifact contract, bounded maxIterations), or does it rely on prose instructions the engine cannot enforce?",
455
+ "Fix issues directly in the workflow file when the right improvement is clear."
456
+ ],
457
+ "outputRequired": {
458
+ "notesMarkdown": "Execution simulation findings, likely weak steps, unsatisfying outputs, false-confidence risks, and any fixes applied.",
459
+ "context": "Capture simulationFindings, likelyWeakSteps, likelyUnsatisfyingOutputs, falseConfidenceFindings, and outcomeEffectivenessPassed."
460
+ },
461
+ "verify": [
462
+ "The simulation judges likely usefulness, not just structural legality."
463
+ ]
386
464
  },
387
- "title": "Phase 3: Systematic Validation & Quality Assurance (Intermediate Path)",
388
- "prompt": "Time to validate and refine your workflow with systematic quality checks. \ud83d\ude80\n\n**STEP 1: Comprehensive Validation**\nrunValidation(intermediate) for systematic analysis\n\n**STEP 2: Error Pattern Analysis & Resolution**\nWhen issues are found, we will address them systematically:\n1. **Categorize errors** by type (e.g., syntax, logic, reference).\n2. **Identify patterns** that might indicate a recurring misunderstanding.\n3. **Prioritize fixes**, starting with critical syntax errors.\n4. **Apply fixes efficiently**, grouping related changes.\n5. **Re-validate incrementally** to confirm progress.\n\n(Agent: Guide the user through this analysis and resolution process, explaining your reasoning at each step.)\n\n**EFFICIENCY FOCUS:** Our goal is systematic error resolution and pattern recognition for faster iteration.",
389
- "agentRole": "You are a workflow quality assurance specialist with expertise in systematic validation and error pattern analysis. Your role is to run the validator, analyze the results for patterns, and then guide the user through a systematic fix process. Your role is to efficiently identify and resolve validation issues while teaching users to recognize and prevent common problems in future workflow development.",
390
- "guidance": [
391
- "SYSTEMATIC APPROACH: Handle errors methodically, grouping similar issues for efficient resolution.",
392
- "PATTERN RECOGNITION: Help user identify common error patterns and prevention strategies.",
393
- "PROFESSIONAL STANDARDS: Apply industry best practices for validation and quality assurance.",
394
- "EFFICIENT ITERATION: Balance thoroughness with practical development speed.",
395
- "QUALITY FOCUS: Ensure the workflow meets professional standards beyond just 'working'."
465
+ "promptFragments": [
466
+ {
467
+ "id": "phase-6b-quick",
468
+ "when": {
469
+ "var": "rigorMode",
470
+ "equals": "QUICK"
471
+ },
472
+ "text": "For QUICK rigor, keep the simulation compact but still answer where the workflow would likely disappoint the user if it disappointed them at all."
473
+ },
474
+ {
475
+ "id": "phase-6b-modernize-check",
476
+ "when": {
477
+ "var": "authoringMode",
478
+ "equals": "modernize_existing"
479
+ },
480
+ "text": "For modernize_existing: after tracing the workflow forward, check each item in valueInventory. For each enforcement mechanism and domain knowledge item: would the modernized workflow produce the same behavior? Any item where the answer is no or weaker is a loss -- fix it directly or record the accepted tradeoff with justification."
481
+ }
396
482
  ],
397
- "requireConfirmation": true
483
+ "requireConfirmation": false
398
484
  },
399
485
  {
400
- "id": "phase-3-advanced",
401
- "runCondition": {
402
- "var": "learningPath",
403
- "equals": "advanced"
486
+ "id": "phase-6c-adversarial-quality-review",
487
+ "title": "Adversarial Quality Review",
488
+ "promptBlocks": {
489
+ "goal": "Review the authored workflow as a quality gate, not just as a valid JSON file.",
490
+ "constraints": [
491
+ "Authoring integrity and outcome effectiveness are separate concerns. Score both.",
492
+ "Reviewer-family or validator output is evidence, not authority."
493
+ ],
494
+ "procedure": [
495
+ "Score these dimensions 0-2 with one sentence of evidence each: `voiceClarity`, `ceremonyLevel`, `loopSoundness`, `delegationBoundedness`, `artifactClarity`, `taskEffectiveness`, `falseConfidenceResistance`, `stateMinimality`, `coverageSharpness`, `domainFit`, `handoffUtility`, `rigorAdaptability` (0 = adapts to complexity/rigor levels, 2 = single-weight), `enforcementStrength` (0 = behavioral rules have structural teeth; 2 = important rules are prose-only with no enforcement mechanism), and `modernizationDiscipline` (0 = every valueInventory item preserved, equivalently replaced with justification, or dropped with justification; 2 = items missing or replaced with weaker versions without justification -- score 0 for create mode).",
496
+ "If delegation is available and rigor is THOROUGH, run an adversarial review bundle with these lenses: `engine_native_reviewer`, `task_effectiveness_reviewer`, `state_economy_reviewer`, `false_confidence_reviewer`, `domain_fit_reviewer`, and `maintainer_reviewer`.",
497
+ "Synthesize what the review confirmed, what it challenged, and what changed your mind.",
498
+ "When scoring `falseConfidenceResistance`, explicitly check: do the workflow's quality gates protect edge cases and degraded paths, or only the happy path? A workflow that passes its own checks on ideal input but fails silently on minimal or unexpected input scores 2.",
499
+ "Set hard-gate failures whenever any of these are materially weak: `taskEffectiveness`, `falseConfidenceResistance`, `stateMinimality`, `coverageSharpness`, `domainFit`, or `handoffUtility`.",
500
+ "Set `authoringIntegrityPassed = true` only if structural and authoring-quality dimensions are all acceptable. Set `outcomeEffectivenessPassed = true` only if the workflow is likely to achieve satisfying results for the user."
501
+ ],
502
+ "outputRequired": {
503
+ "notesMarkdown": "Quality review scores, adversarial review findings, hard-gate failures, and the current redesign severity.",
504
+ "context": "Capture reviewScores, hardGateFailures, authoringIntegrityPassed, outcomeEffectivenessPassed, qualityReviewSummary, and redesignSeverity."
505
+ },
506
+ "verify": [
507
+ "Hard gates reflect real user-trust risk, not cosmetic imperfections."
508
+ ]
404
509
  },
405
- "title": "Phase 3: Advanced Validation & Architectural Review (Advanced Path)",
406
- "prompt": "Let's execute a comprehensive validation with an eye for performance and architectural integrity. \ud83c\udfc6\n\n**STEP 1: Comprehensive Technical Validation**\nrunValidation(advanced) for architectural review\n\n**STEP 2: Advanced Error Analysis & Architectural Resolution**\nFor any issues found, we will perform a deep analysis:\n1. **Root Cause Analysis**: Let's trace the errors back to their architectural source.\n2. **Impact Assessment**: We'll evaluate the consequences for scalability and maintainability.\n3. **Strategic Resolution**: I will help you fix the underlying patterns, not just the symptoms.\n4. **Architectural Refinement**: We'll ensure the fixes align with our overall design principles.\n\n(Agent: Lead the user through this discussion, proposing and implementing fixes collaboratively.)\n\n**MASTERY FOCUS:** We will use validation feedback to refine architectural decisions and optimize for enterprise deployment.",
407
- "agentRole": "You are a principal workflow architect and validation expert with deep expertise in enterprise-grade quality assurance. Your role is to run the validator and then lead an advanced analysis of the errors, connecting them back to architectural decisions. Your role is to conduct sophisticated technical analysis, identify architectural implications of validation issues, and guide strategic resolution that enhances overall workflow design.",
408
- "guidance": [
409
- "ARCHITECTURAL PERSPECTIVE: View validation through the lens of overall system design and long-term maintainability.",
410
- "PERFORMANCE AWARENESS: Consider validation overhead and execution efficiency implications.",
411
- "ENTERPRISE STANDARDS: Apply enterprise-grade quality gates and compliance requirements.",
412
- "STRATEGIC THINKING: Fix root causes and patterns, not just individual errors.",
413
- "OPTIMIZATION FOCUS: Use validation as an opportunity to refine and optimize the workflow architecture."
510
+ "promptFragments": [
511
+ {
512
+ "id": "phase-6c-standard",
513
+ "when": {
514
+ "var": "rigorMode",
515
+ "equals": "STANDARD"
516
+ },
517
+ "text": "For STANDARD rigor, you may keep the review self-executed unless uncertainty remains material. If you do delegate, prefer a small adversarial bundle."
518
+ },
519
+ {
520
+ "id": "phase-6c-thorough",
521
+ "when": {
522
+ "var": "rigorMode",
523
+ "equals": "THOROUGH"
524
+ },
525
+ "text": "For THOROUGH rigor, assume the first review is not enough. Use adversarial reviewer lanes unless a hard limitation makes them impossible."
526
+ },
527
+ {
528
+ "id": "phase-6c-heritage-review",
529
+ "when": {
530
+ "var": "authoringMode",
531
+ "equals": "modernize_existing"
532
+ },
533
+ "text": "For modernize_existing: add a heritage_reviewer to the adversarial bundle. Its job is to check each valueInventory item and find what was lost or weakened -- it ignores format improvements. It must answer: which enforcement mechanisms are now prose-only? Which domain knowledge items are absent? Which behavioral rules were removed without equivalent replacement? Heritage_reviewer findings drive enforcementStrength and modernizationDiscipline scores."
534
+ }
414
535
  ],
415
- "requireConfirmation": true
416
- },
417
- {
418
- "id": "phase-4-basic",
419
- "runCondition": {
420
- "var": "learningPath",
421
- "equals": "basic"
422
- },
423
- "title": "Phase 4: Simple Testing & Improvement (Basic Path)",
424
- "prompt": "Excellent! Your workflow is technically sound. Now let's make sure it's clear and easy to use. \ud83c\udf31\n\n**STEP 1: Choose What to Test**\nFirst, which important step from your new workflow would you like to test? Pick one that is complex or that a user might struggle with.\n\n**STEP 2: Simple Persona Testing**\nOnce you've chosen a step, we'll test it by imagining different types of users:\n\n- **The Beginner User:** Would someone new to this topic understand the instructions? Are there any technical words that need explaining?\n- **The Busy User:** Could someone in a hurry misunderstand this? Is it too long or wordy?\n- **The Adversarial LLM (Advanced Concept):** Is there any ambiguity an AI could exploit to produce a plausible but incorrect result? This helps make the prompt robust for AI agents.\n\n(Agent: For each persona, ask the user these questions and help them analyze the prompt.)\n\n**STEP 3: Make It Better**\nBased on what we find, I will help you:\n1. **Understand the problems** we identified.\n2. **Come up with specific improvements**.\n3. **Make the changes** using `edit_file`.\n4. **Check our work** with `workflow_validate`.\n\n**LEARNING GOAL:** Our goal is to understand how to make instructions clear for everyone.",
425
- "agentRole": "You are a workflow usability specialist focused on clear communication and user experience design. Your role is to guide the user through testing one of their steps against simple personas and help them improve the clarity of the instructions.",
426
- "guidance": [
427
- "SIMPLE APPROACH: Focus on clarity and basic usability rather than complex edge cases.",
428
- "EDUCATIONAL FOCUS: Explain why each test matters and what good instructions look like.",
429
- "ENCOURAGE EMPATHY: Help user think about different types of people who might use their workflow.",
430
- "PRACTICAL IMPROVEMENTS: Focus on concrete, actionable changes that clearly improve usability.",
431
- "BUILD CONFIDENCE: Celebrate improvements and explain how testing makes workflows better."
432
- ]
536
+ "hasValidation": true,
537
+ "validationCriteria": [
538
+ { "type": "contains", "value": "voiceClarity", "message": "Review must score voiceClarity" },
539
+ { "type": "contains", "value": "ceremonyLevel", "message": "Review must score ceremonyLevel" },
540
+ { "type": "contains", "value": "loopSoundness", "message": "Review must score loopSoundness" },
541
+ { "type": "contains", "value": "delegationBoundedness", "message": "Review must score delegationBoundedness" },
542
+ { "type": "contains", "value": "artifactClarity", "message": "Review must score artifactClarity" },
543
+ { "type": "contains", "value": "taskEffectiveness", "message": "Review must score taskEffectiveness" },
544
+ { "type": "contains", "value": "falseConfidenceResistance", "message": "Review must score falseConfidenceResistance" },
545
+ { "type": "contains", "value": "stateMinimality", "message": "Review must score stateMinimality" },
546
+ { "type": "contains", "value": "coverageSharpness", "message": "Review must score coverageSharpness" },
547
+ { "type": "contains", "value": "domainFit", "message": "Review must score domainFit" },
548
+ { "type": "contains", "value": "handoffUtility", "message": "Review must score handoffUtility" },
549
+ { "type": "contains", "value": "rigorAdaptability", "message": "Review must score rigorAdaptability" },
550
+ { "type": "contains", "value": "enforcementStrength", "message": "Review must score enforcementStrength" },
551
+ {
552
+ "type": "contains",
553
+ "value": "modernizationDiscipline",
554
+ "condition": { "var": "authoringMode", "equals": "modernize_existing" },
555
+ "message": "Modernization reviews must score modernizationDiscipline"
556
+ }
557
+ ],
558
+ "requireConfirmation": false
433
559
  },
434
560
  {
435
- "id": "phase-4-intermediate",
436
- "runCondition": {
437
- "var": "learningPath",
438
- "equals": "intermediate"
561
+ "id": "phase-6d-redesign-and-revalidate",
562
+ "title": "Redesign and Revalidate",
563
+ "promptBlocks": {
564
+ "goal": "If hard gates fail, redesign the workflow instead of polishing around the problem.",
565
+ "constraints": [
566
+ "Minor cosmetic refinement is not enough when task effectiveness or false-confidence resistance is weak.",
567
+ "If structure changes, re-run real validators before leaving this step."
568
+ ],
569
+ "procedure": [
570
+ "If `authoringIntegrityPassed` and `outcomeEffectivenessPassed` are both true and `hardGateFailures` is empty, say that no redesign is needed.",
571
+ "Otherwise classify the needed redesign severity as `minor`, `architectural`, or `unsafe_to_ship` and apply the necessary fixes directly to the workflow file.",
572
+ "If the redesign changed structure, run the real validators again and update the validation state before leaving this step."
573
+ ],
574
+ "outputRequired": {
575
+ "notesMarkdown": "Redesign actions taken, why they were needed, and whether revalidation passed.",
576
+ "context": "Capture redesignApplied, validationPassed, and remainingConcerns."
577
+ },
578
+ "verify": [
579
+ "Structural redesign problems are handled as redesign problems, not cosmetic ones."
580
+ ]
439
581
  },
440
- "title": "Phase 4: Systematic Testing & Quality Refinement (Intermediate Path)",
441
- "prompt": "Your workflow is validated. Let's ensure it's robust and professional through comprehensive testing. \ud83d\ude80\n\n**STEP 1: Critical Step Selection**\nTo begin, please identify 1-2 critical steps from your workflow that are either complex, high-impact, or involve key user decisions.\n\n**STEP 2: Multi-Persona Analysis**\nFor each step you select, we will evaluate it from these strategic perspectives:\n\n- **The Domain Expert:** Does the step leverage domain knowledge correctly? Are there unstated assumptions?\n- **The Efficiency-Focused User:** Can the step be completed quickly without sacrificing quality? Are there bottlenecks?\n- **The Adversarial LLM:** How could an AI exploit ambiguity in the prompt to produce a plausible but incorrect result?\n\n(Agent: Guide the user through this analysis, asking probing questions for each persona.)\n\n**STEP 3: Strategic Refinements**\nBased on our analysis, I will help you:\n1. **Prioritize improvements** by impact.\n2. **Implement targeted enhancements** using `edit_file`.\n3. **Validate consistency** with `workflow_validate`.\n4. **Document the rationale** for key design decisions.\n\n**PROFESSIONAL FOCUS:** Our goal is to balance efficiency, quality, and usability for real-world deployment.",
442
- "agentRole": "You are a workflow quality engineer and strategic testing specialist with expertise in multi-persona analysis and systematic quality improvement. Your role is to guide the user through a systematic evaluation of a critical step against multiple strategic personas.",
443
- "guidance": [
444
- "STRATEGIC THINKING: Focus on improvements that have the highest impact on workflow effectiveness.",
445
- "PROFESSIONAL STANDARDS: Apply industry best practices for user experience and process design.",
446
- "BALANCED APPROACH: Consider trade-offs between different user needs and workflow goals.",
447
- "SYSTEMATIC PROCESS: Use structured analysis to ensure comprehensive coverage of potential issues.",
448
- "PRACTICAL DEPLOYMENT: Focus on refinements that matter for real-world workflow usage."
449
- ]
582
+ "requireConfirmation": false
450
583
  },
451
584
  {
452
- "id": "phase-4-advanced",
453
- "runCondition": {
454
- "var": "learningPath",
455
- "equals": "advanced"
585
+ "id": "phase-6e-quality-loop-decision",
586
+ "title": "Quality Loop Decision",
587
+ "promptBlocks": {
588
+ "goal": "Decide whether the quality-gate loop needs another pass.",
589
+ "constraints": [
590
+ "Use hard gates and actual remaining concerns, not vibes."
591
+ ],
592
+ "procedure": [
593
+ "Continue if `authoringIntegrityPassed = false`.",
594
+ "Otherwise continue if `outcomeEffectivenessPassed = false`.",
595
+ "Otherwise continue if `hardGateFailures` is not empty.",
596
+ "Otherwise continue if `redesignSeverity` is `architectural` or `unsafe_to_ship` and you have not yet re-reviewed the redesigned workflow.",
597
+ "Otherwise continue if `validationPassed = false` after redesign.",
598
+ "Otherwise stop."
599
+ ],
600
+ "outputRequired": {
601
+ "artifact": "Emit a `wr.loop_control` artifact for `quality_gate_loop` with `decision` set to `continue` or `stop`."
602
+ },
603
+ "verify": [
604
+ "The workflow does not stop while hard trust problems remain."
605
+ ]
456
606
  },
457
- "title": "Phase 4: Enterprise Testing & Architectural Refinement (Advanced Path)",
458
- "prompt": "Let's execute sophisticated, enterprise-grade testing and optimization. \ud83c\udfc6\n\n**STEP 1: Strategic Component Selection**\nFirst, please identify the critical components in your workflow for analysis. Focus on high-complexity steps, key decision points, or integration touchpoints.\n\n**STEP 2: Advanced Multi-Dimensional Analysis**\nFor each component you choose, we will execute a comprehensive evaluation framework. I will lead you through discussions on:\n\n- **Architectural Perspective:** Are the design patterns consistent? What are the scalability implications?\n- **Performance & Efficiency:** Where are the potential bottlenecks? Is context variable usage optimal?\n- **The Adversarial LLM:** How can we harden prompts against sophisticated misinterpretation by an AI agent seeking the path of least resistance?\n- **Enterprise User Experience:** How does this work for multi-user collaboration or in enterprise environments?\n- **Maintenance & Evolution:** How easy is this to maintain and extend?\n\n(Agent: Lead the user through this deep analysis, acting as an architectural consultant.)\n\n**STEP 3: Strategic Architectural Refinement**\nBased on our analysis, I will help you:\n1. **Architect strategic improvements** that address systemic issues.\n2. **Optimize for enterprise deployment** with sophisticated enhancements.\n3. **Validate architectural integrity** using `workflow_validate`.\n4. **Document our architectural decisions** and the rationale for them.\n\n**MASTERY OUTCOME:** Our goal is to create an enterprise-ready workflow optimized for scalability, maintainability, and sophisticated deployment scenarios.",
459
- "agentRole": "You are a principal workflow architect and enterprise testing specialist with deep expertise in sophisticated multi-dimensional analysis and enterprise-grade optimization. Your role is to lead a multi-dimensional analysis of critical workflow components, focusing on architectural integrity and enterprise readiness.",
460
- "guidance": [
461
- "ARCHITECTURAL EXCELLENCE: Focus on sophisticated design patterns and enterprise-grade considerations.",
462
- "PERFORMANCE OPTIMIZATION: Identify and address efficiency opportunities across all dimensions.",
463
- "ENTERPRISE READINESS: Ensure the workflow meets sophisticated organizational deployment requirements.",
464
- "STRATEGIC REFINEMENT: Make improvements that enhance long-term value and architectural integrity.",
465
- "COMPREHENSIVE ANALYSIS: Apply enterprise-grade evaluation frameworks for thorough assessment."
466
- ]
467
- },
468
- {
469
- "id": "satisfaction-check",
470
- "title": "Iteration Satisfaction Check & Loop Decision",
471
- "prompt": "Let's assess your satisfaction with the workflow so far.\n\n**Rate your satisfaction (1-10):**\n- 10: Perfect! Ready to deploy\n- 8-9: Very good, minor tweaks only\n- 6-7: Good foundation, needs refinement\n- 4-5: Major improvements needed\n- 1-3: Significant rework required\n\n**Decision logic:**\n- Score 9+: decision = 'stop' (proceed to completion)\n- Score <9: decision = 'continue' (iterate again, up to 3 times total)\n\nAgent: Set context.satisfactionScore and increment context.iterationCount.\n\n**Provide a loop control artifact:**\n```json\n{\n \"artifacts\": [{\n \"kind\": \"wr.loop_control\",\n \"decision\": \"continue\",\n \"metadata\": {\n \"reason\": \"Satisfaction score X/10 - [brief reason]\"\n }\n }]\n}\n```",
472
- "agentRole": "You are a quality assessment specialist. Guide the user through evaluating their workflow objectively. Provide a loop control artifact with the decision.",
473
- "requireConfirmation": false,
474
607
  "outputContract": {
475
608
  "contractRef": "wr.contracts.loop_control"
476
- }
609
+ },
610
+ "requireConfirmation": false
477
611
  }
478
612
  ]
479
613
  },
480
614
  {
481
- "id": "phase-5-completion",
482
- "title": "Phase 5: Celebration & Growth",
483
- "prompt": "\ud83c\udf89 **WORKFLOW CREATION COMPLETE!** \ud83c\udf89\n\n**STEP 1: Final Review**\nagentInstruct(review workflow name and description, then runValidation(final))\n\n**STEP 2: Path-Specific Celebration**\n\nagentInstruct(provide adaptToPath(celebration) based on learning path):\n\n**\ud83c\udf31 BASIC PATH:**\nCongratulations! You've created your first workflow with advanced features!\nLearned: Workflow structure, conditional steps, validation, clear guidance.\nNext: Try intermediate path for advanced patterns and sophisticated testing.\n\n**\ud83d\ude80 INTERMEDIATE PATH:**\nExcellent work! You've created a professionally structured workflow!\nMastered: Efficient authoring, strategic features, systematic validation, design patterns.\nNext: Consider Phase 6 optimization, create domain workflows, explore advanced logic.\n\n**\ud83c\udfc6 ADVANCED PATH:**\nOutstanding! You've demonstrated workflow architecture mastery!\nAchieved: Sophisticated design, enterprise validation, advanced patterns, expert engineering.\nNext: Lead design, contribute advanced templates, mentor others, explore innovations.\n\n**STEP 3: Documentation & Quality Metrics**\ncreateFile(README.md) with usage instructions generated from workflow content.\n\n**Quality Rubric - Rate your workflow:**\n- Clarity: How clear are the instructions? (1-10)\n- Adaptability: How well does it handle edge cases? (1-10)\n- Innovation: How creative is the approach? (1-10)\n- Maintainability: How easy to update? (1-10)\n\nAgent: If any score < 8, suggest specific improvements.\n\n**STEP 4: Completion**\nAgent: Confirm workflow is deployment-ready. For basic/intermediate users, offer level-up opportunities for future workflows.\n\n**UNIVERSAL TRUTH:** Workflow mastery continues with each template. Every workflow is an opportunity to improve!",
484
- "guidance": [
485
- "ADAPTIVE CELEBRATION: Match the celebration intensity and language to the user's learning path and achievement level.",
486
- "GROWTH ORIENTATION: Always provide clear next steps that encourage continued learning and skill development.",
487
- "PATH-SPECIFIC GUIDANCE: Tailor advice to the user's demonstrated skill level and learning journey.",
488
- "LEVEL-UP OPPORTUNITIES: For basic and intermediate users, gently suggest trying higher complexity paths for future workflows.",
489
- "UNIVERSAL PRINCIPLES: End with shared wisdom that applies to all workflow creators regardless of skill level."
490
- ],
491
- "validationCriteria": [
492
- {
493
- "type": "length",
494
- "min": 500,
495
- "message": "Final workflow should be comprehensive (at least 500 characters)"
496
- },
497
- {
498
- "type": "regex",
499
- "pattern": "\"steps\":\\s*\\[[^\\]]+\\]",
500
- "message": "Final workflow must have at least one complete step"
615
+ "id": "phase-7a-assign-tags",
616
+ "title": "Phase 7a: Assign Tags",
617
+ "promptBlocks": {
618
+ "goal": "Register the workflow in the catalog: assign tags in spec/workflow-tags.json and write about and examples fields into the workflow JSON so humans and agents can discover and understand the workflow.",
619
+ "procedure": [
620
+ "Read spec/workflow-tags.json to see the available tags and their 'when' phrases.",
621
+ "Based on the workflow's purpose and description, select 1-3 tags from the closed set (coding, review_audit, investigation, design, documentation, tickets, learning, routines, authoring).",
622
+ "Add the workflow ID as a new entry under 'workflows' in spec/workflow-tags.json: { \"tags\": [\"<tag1>\"] }.",
623
+ "If the workflow is a test fixture or internal utility not meant for end-user discovery, add 'hidden': true.",
624
+ "Save the tags file. Do not modify any other field.",
625
+ "Write the 'about' field into the workflow JSON: a markdown string (100-400 words) written for a human deciding whether to use this workflow. Cover what it does, when to use it, what it produces, and how to get good results. This is a user-facing surface -- not agent instructions (use metaGuidance for that).",
626
+ "Write the 'examples' field into the workflow JSON: an array of 2-4 short, concrete goal strings (10-120 chars each) showing what this workflow is used for. Each example should be specific enough to be informative -- not generic ('implement a feature'). These appear in list_workflows output so agents can communicate concrete goal phrasing to users.",
627
+ "Skip 'about' and 'examples' only if the workflow is marked hidden: true."
628
+ ],
629
+ "constraints": [
630
+ "Only use tags from the closed set. Do not invent new tags.",
631
+ "If the workflow already has an entry in the tags file, update it rather than adding a duplicate.",
632
+ "Tags should reflect what the workflow does, not what it is named.",
633
+ "Write 'about' for humans, not agents -- do not copy metaGuidance or step prompt text into it.",
634
+ "Examples must be specific to this workflow; reject generic examples that would fit any workflow."
635
+ ],
636
+ "outputRequired": {
637
+ "notesMarkdown": "List the assigned tags with a one-line justification for each. Confirm about and examples were written."
501
638
  }
502
- ],
503
- "hasValidation": true
504
- },
505
- {
506
- "id": "phase-5-5-visual-preview",
507
- "title": "Phase 5.5: Visual Workflow Preview",
508
- "prompt": "Let's visualize your workflow to see the complete flow! \ud83c\udfa8\n\nvisualizeWorkflow() to generate a comprehensive diagram.\n\n**Creating Mermaid Diagram:**\nI'll generate a flowchart showing:\n- Complete step sequence\n- Decision branches (conditional steps)\n- Loop structures\n- Context variable flow\n- Learning path variations\n\nAgent: Use create_diagram to generate a Mermaid flowchart. Include:\n1. All workflow steps as nodes\n2. Conditional branches with decision labels\n3. Loop indicators with iteration info\n4. Context variables as data flow annotations\n5. Different colors for different phases or complexity levels\n\n**Example Structure:**\n```mermaid\nflowchart TD\n Start([\"\ud83d\ude80 Workflow Start\"])\n Discovery[\"Phase 0: Discovery Loop<br/>Gather Requirements\"]\n Complexity[\"Phase 1.25: Complexity Analysis<br/>Score: context.complexityScore\"]\n PathSelect{{\"Learning Path Selection<br/>Basic/Intermediate/Advanced\"}}\n ...\n End([\"\u2705 Workflow Complete\"])\n```\n\n**Benefits of Visualization:**\n- See the complete workflow structure at a glance\n- Verify logical flow and dependencies\n- Identify optimization opportunities\n- Great for documentation and team sharing",
509
- "agentRole": "You are a workflow visualization expert. Create clear, comprehensive Mermaid diagrams that accurately represent the workflow structure, including all paths, conditions, and data flows.",
510
- "guidance": [
511
- "COMPLETE COVERAGE: Include every step, even conditional ones",
512
- "CLEAR LABELING: Use descriptive labels for all nodes and edges",
513
- "VISUAL HIERARCHY: Use subgraphs for loops and phases",
514
- "DATA FLOW: Show context variable usage with annotations",
515
- "ACCESSIBILITY: Ensure diagram is readable and well-organized"
516
- ],
639
+ },
517
640
  "requireConfirmation": false
518
641
  },
519
642
  {
520
- "id": "phase-6-dsl-optimization",
521
- "title": "Phase 6: Optimize with Function Reference Pattern (Advanced)",
522
- "prompt": "**WORKFLOW OPTIMIZATION OPPORTUNITY** \ud83d\udd27\n\nYour workflow is complete and functional! Now let's make it more maintainable and efficient using the **Function Reference Pattern** - an advanced technique for reducing duplication.\n\n**STEP 1: Analyze for Duplication**\nLet's examine your workflow for repeated instruction patterns:\n- Look for similar phrases across multiple step prompts\n- Identify repeated tool usage instructions (edit_file, workflow_validate, etc.)\n- Find common guidance patterns that appear in multiple places\n\n**STEP 2: Identify Function Candidates**\nBased on your workflow, we might create functions like:\n```\nfun createFile(filename) = 'Use edit_file to create {filename}. Explain the structure as you build it.'\nfun runValidation() = 'Execute workflow_validate_json. Explain any errors found and guide through fixes step-by-step.'\nfun adaptToPath(content) = 'Deliver {content} with appropriate depth based on learningPath: basic=detailed explanations, intermediate=efficient guidance, advanced=expert context.'\n```\n\n**STEP 3: Implementation Decision**\nFunction references work best for workflows with:\n\u2705 10+ steps with shared patterns\n\u2705 Repeated instruction blocks\n\u2705 Long prompts hitting character limits\n\u2705 Team workflows needing consistency\n\n**Agent Instructions:**\n1. Analyze the created workflow for duplication patterns\n2. If suitable (complex workflow with repeated patterns), propose specific function definitions\n3. Show examples of how 2-3 steps would look with function references\n4. Calculate potential file size reduction\n5. Let user decide whether to implement this optimization\n\nThis is an **optional advanced technique** - the workflow is already complete and functional!",
523
- "agentRole": "You are a workflow optimization specialist with expertise in the Function Reference Pattern (DSL approach). Your role is to analyze the completed workflow for duplication opportunities and guide the user through the decision of whether to apply this advanced optimization technique.",
524
- "guidance": [
525
- "PATTERN RECOGNITION: Look for repeated instruction blocks, tool usage patterns, and similar guidance across steps.",
526
- "BENEFIT ANALYSIS: Calculate concrete benefits (file size reduction, consistency improvement, maintenance ease).",
527
- "OPTIONAL OPTIMIZATION: Make it clear this is an advanced, optional technique - the workflow already works.",
528
- "PRACTICAL EXAMPLES: Show concrete before/after examples from their actual workflow.",
529
- "USER CHOICE: Let them decide based on their workflow complexity and maintenance needs."
530
- ],
531
- "runCondition": {
532
- "or": [
533
- {
534
- "var": "learningPath",
535
- "equals": "intermediate"
536
- },
537
- {
538
- "var": "learningPath",
539
- "equals": "advanced"
540
- }
643
+ "id": "phase-7-final-trust-handoff",
644
+ "title": "Phase 7: Final Trust Handoff",
645
+ "promptBlocks": {
646
+ "goal": "Summarize the authored or modernized workflow as a trust decision, not just a file edit.",
647
+ "constraints": [
648
+ "Keep it concise. The workflow file is the deliverable, not the summary."
649
+ ],
650
+ "procedure": [
651
+ "Stamp the workflow file: read the current `version` from `spec/authoring-spec.json` and write `validatedAgainstSpecVersion: <N>` as a top-level field in the workflow JSON. Commit the change -- the stamp has no effect if only saved locally.",
652
+ "State the workflow file path and name, whether it was created or modernized, and what it does in one sentence.",
653
+ "Summarize the step structure, loops, confirmations, and delegation profile.",
654
+ "Report validation status, authoring-integrity status, and outcome-effectiveness status.",
655
+ "Set a final `workflowReadinessVerdict`: `ready`, `ready_with_conditions`, or `not_ready`.",
656
+ "List the main improvements, residual weaknesses, trust risks if any, and how to test the workflow."
657
+ ],
658
+ "outputRequired": {
659
+ "notesMarkdown": "Final trust handoff covering readiness verdict, validation status, strengths, residual weaknesses, and testing guidance.",
660
+ "context": "Capture workflowReadinessVerdict, trustRiskSummary, knownFailureModes, and residualWeaknesses."
661
+ },
662
+ "verify": [
663
+ "The final handoff makes clear whether WorkRail should trust this workflow."
541
664
  ]
542
665
  },
543
- "requireConfirmation": true
544
- },
545
- {
546
- "id": "level-up-opportunity",
547
- "runCondition": {
548
- "var": "learningPath",
549
- "not_equals": "advanced"
550
- },
551
- "title": "\ud83d\ude80 Ready to Level Up?",
552
- "prompt": "**OPTIONAL: Explore the Next Level**\n\nYou've successfully completed your workflow! Would you like to explore what the next learning path offers for your future workflows?\n\n**FOR BASIC PATH GRADUATES:**\nThe **Intermediate Path** offers:\n- More efficient workflow creation process\n- Advanced feature recommendations based on use case\n- Professional design patterns and best practices\n- Systematic validation and testing approaches\n\n**FOR INTERMEDIATE PATH GRADUATES:**\nThe **Advanced Path** offers:\n- Comprehensive feature utilization from the start\n- Enterprise-grade architectural considerations\n- Performance optimization and scalability patterns\n- Sophisticated testing and validation frameworks\n\n**Remember:** You can always return to your comfortable level - this is just an invitation to explore new possibilities when you're ready!\n\n**Agent Guidance:** If the user expresses interest, provide a brief preview of what they would experience in the next path level. If not interested, celebrate their current achievement and encourage them to practice at their current level.",
553
- "guidance": [
554
- "OPTIONAL EXPLORATION: Make it clear this is purely optional and they've already succeeded.",
555
- "NO PRESSURE: Emphasize they can always return to their comfort level.",
556
- "PREVIEW VALUE: Show concrete benefits of advancing without making current level seem inadequate.",
557
- "RESPECT CHOICE: Whether they advance or stay, celebrate their decision and provide appropriate support."
558
- ]
666
+ "notesOptional": true,
667
+ "requireConfirmation": false
559
668
  }
560
- ]
669
+ ],
670
+ "validatedAgainstSpecVersion": 3
561
671
  }