File size: 13,225 Bytes
d83cac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf8c05f
 
 
 
 
 
d83cac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# ---- Changelog ----
# [2026-04-07] Josh + Claude β€” Spec generator via Strategist persona (Phase 5)
# What: Turns natural language intent + constraints into valid WorkBlockSpec JSON
# Why: The system needs to generate its own specs, not have humans write JSON by hand
# How: Strategist persona + Graph context + schema reference + validation retry loop
# -------------------

"""Spec Generator β€” Strategist creates structured work block specs.

The Strategist persona takes natural language intent and constraints,
queries the Graph for relevant past experience, and produces a valid
WorkBlockSpec JSON. Schema validation on output β€” malformed specs
trigger a retry with the validation errors fed back in.
"""

import json
import logging
from typing import Optional

from persona_client import call_persona
from work_block_schema import validate_spec, WORK_BLOCK_SCHEMA, _TOOL_NAMES

logger = logging.getLogger("spec_generator")

# Compact schema reference for the Strategist prompt β€” just enough to generate valid specs
_SCHEMA_REFERENCE = f"""## WorkBlockSpec Schema Reference

Required top-level keys: spec_version, block, steps, constraints

### spec_version
Always "1.0.0"

### block
Required: id (string), name (string, max 120 chars), scope (string), acceptance_criteria (array of strings, min 1)
Optional: agent (string), workspace (string β€” absolute path for cross-repo work), depends_on (array of strings)

### snap_interface (optional)
inputs: array of {{name, type (file|function|config|state), source_block, path}}
outputs: array of {{name, type, path, contract}}

### constraints
Required: never (array of strings, min 1), anti_drift (array of strings)
Optional: tool_allowlist (array from: {', '.join(_TOOL_NAMES)}), shell_allowlist (array of strings), max_iterations (int, 1-100, default 15), timeout_seconds (int, 30-3600, default 300)

### steps (array, min 1)
Five step types:

**action** (required: id, type:"action", tool, params, validation, on_failure)
- tool: one of {', '.join(_TOOL_NAMES)}
- params: object matching tool's input schema
- bind_result: optional "$variable_name" to store result
- validation.checks: array of {{operator, target, value, description}}
  operators: contains, not_contains, equals, not_equals, matches_regex, result_is_string, result_is_not_error, file_exists, file_contains, output_length_gt, output_length_lt
- on_failure: {{action: abort_block|retry|skip|goto|escalate_to_qb, message}}

**gate** (required: id, type:"gate", description, gate_type)
- gate_type: human_review | qb_checkpoint | auto_approve
- staged_actions: array of step IDs

**condition** (required: id, type:"condition", check, if_true, if_false)
- check: {{operator, target, value, description}}
- if_true / if_false: arrays of steps

**loop** (required: id, type:"loop", over, body)
- over: {{items: [strings]}} or {{from_result: "$var", split_on: "\\n"}}
- bind_item: "$item" (default)
- body: array of steps

**group** (required: id, type:"group", steps)
- steps: array of steps
- on_failure: optional

### CRITICAL RULES
1. EVERY action step MUST have a validation block with at least one check
2. EVERY action step MUST have an on_failure handler
3. NEVER guess file paths β€” start with shell_execute "find" or "ls" to discover repo structure
4. Start specs by reading the source of truth (vault docs, canonical files) before acting
5. Verify before asserting β€” add read/grep steps before write steps
6. Use shell_execute for reads outside the default workspace (grep, head, tail, find, ls, etc.)
7. All file paths in params must be ABSOLUTE (starting with /) when workspace is set
8. ONLY use operators from the list above β€” do NOT invent new operators
"""


def generate_spec(
    intent: str,
    constraints: Optional[str] = None,
    graph_context: Optional[list] = None,
    workspace: Optional[str] = None,
    max_retries: int = 2,
) -> dict:
    """Generate a WorkBlockSpec from natural language intent.

    Args:
        intent: What to build/fix/audit (natural language)
        constraints: Project-specific constraints (natural language or structured)
        graph_context: Graph recall results for relevant past experience
        workspace: Workspace path if cross-repo work needed
        max_retries: How many times to retry on schema validation failure

    Returns:
        {
            success: bool,
            spec: dict | None (the validated spec),
            errors: [str] | None (validation errors if failed),
            generation_attempts: int,
            strategist_response: str (raw response for debugging),
        }
    """
    task = _build_generation_prompt(intent, constraints, workspace)

    for attempt in range(max_retries + 1):
        logger.info("Spec generation attempt %d/%d", attempt + 1, max_retries + 1)

        result = call_persona(
            role="strategist",
            task=task,
            graph_context=graph_context,
            temperature=0.4,  # Low temp for structured output
            max_tokens=8192,  # Specs can be long
        )

        raw = result.get("response", "")

        # Extract JSON from the response
        spec = _extract_json(raw)
        if spec is None:
            logger.warning("Attempt %d: No valid JSON found in response", attempt + 1)
            task = _build_retry_prompt(intent, constraints, workspace,
                                       ["No valid JSON found in response. Output ONLY the JSON spec, no prose."])
            continue

        # Schema validation
        valid, errors = validate_spec(spec)
        if valid:
            logger.info("Spec generated and validated on attempt %d", attempt + 1)
            return {
                "success": True,
                "spec": spec,
                "errors": None,
                "generation_attempts": attempt + 1,
                "strategist_response": raw,
            }

        # Validation failed β€” retry with errors
        logger.warning("Attempt %d: Schema validation failed with %d errors", attempt + 1, len(errors))
        task = _build_retry_prompt(intent, constraints, workspace, errors)

    return {
        "success": False,
        "spec": spec,  # Return the last attempt even if invalid
        "errors": errors if 'errors' in dir() else ["Max retries exceeded"],
        "generation_attempts": max_retries + 1,
        "strategist_response": raw if 'raw' in dir() else "",
    }


def generate_followup_spec(
    original_spec: dict,
    failed_report: dict,
    evaluation: dict,
    graph_context: Optional[list] = None,
    max_retries: int = 2,
) -> dict:
    """Generate a follow-up spec targeting gaps from a failed execution.

    Args:
        original_spec: The spec that was executed
        failed_report: The execution report showing failures
        evaluation: The evaluate_report() output with iteration hints
        graph_context: Graph recall for context
        max_retries: Retry count for validation

    Returns:
        Same format as generate_spec()
    """
    task = _build_followup_prompt(original_spec, failed_report, evaluation)

    for attempt in range(max_retries + 1):
        logger.info("Follow-up spec generation attempt %d/%d", attempt + 1, max_retries + 1)

        result = call_persona(
            role="strategist",
            task=task,
            graph_context=graph_context,
            temperature=0.4,
            max_tokens=8192,
        )

        raw = result.get("response", "")
        spec = _extract_json(raw)

        if spec is None:
            task = _build_retry_prompt(
                f"Follow-up for {original_spec.get('block', {}).get('name', 'unknown')}",
                None, None,
                ["No valid JSON found. Output ONLY the JSON spec."]
            )
            continue

        valid, errors = validate_spec(spec)
        if valid:
            logger.info("Follow-up spec validated on attempt %d", attempt + 1)
            return {
                "success": True,
                "spec": spec,
                "errors": None,
                "generation_attempts": attempt + 1,
                "strategist_response": raw,
            }

        task = _build_retry_prompt(
            f"Follow-up for {original_spec.get('block', {}).get('name', 'unknown')}",
            None, None, errors
        )

    return {
        "success": False,
        "spec": spec if 'spec' in dir() else None,
        "errors": errors if 'errors' in dir() else ["Max retries exceeded"],
        "generation_attempts": max_retries + 1,
        "strategist_response": raw if 'raw' in dir() else "",
    }


# ---------------------------------------------------------------------------
# Prompt builders
# ---------------------------------------------------------------------------

def _build_generation_prompt(intent: str, constraints: Optional[str], workspace: Optional[str]) -> str:
    """Build the initial spec generation prompt for Strategist."""
    parts = [
        "Generate a WorkBlockSpec JSON for the following task.\n",
        "Output ONLY valid JSON β€” no prose before or after. No markdown code fences.\n\n",
        f"## Task\n{intent}\n",
    ]

    if constraints:
        parts.append(f"\n## Project Constraints\n{constraints}\n")

    if workspace:
        parts.append(f"\n## Workspace\nSet block.workspace to: {workspace}\n")

    parts.append(f"\n{_SCHEMA_REFERENCE}\n")

    parts.append(
        "\n## Remember\n"
        "- Start by reading the source of truth before acting\n"
        "- Verify paths exist on disk before using them\n"
        "- Every action MUST have validation checks and on_failure\n"
        "- Use shell_execute with head/tail/grep for cross-repo reads\n"
        "- Output ONLY the JSON. No explanation. No wrapping.\n"
    )

    return "\n".join(parts)


def _build_retry_prompt(intent: str, constraints: Optional[str], workspace: Optional[str], errors: list) -> str:
    """Build a retry prompt with validation errors."""
    error_text = "\n".join(f"- {e}" for e in errors[:10])
    return (
        f"Your previous spec had validation errors:\n{error_text}\n\n"
        f"Fix these errors and output a corrected WorkBlockSpec JSON.\n"
        f"Output ONLY valid JSON β€” no prose, no code fences.\n\n"
        f"{_SCHEMA_REFERENCE}"
    )


def _build_followup_prompt(original_spec: dict, report: dict, evaluation: dict) -> str:
    """Build a follow-up spec generation prompt from a failed execution."""
    hints = evaluation.get("iteration_hints", [])
    hints_text = "\n".join(f"- {h}" for h in hints) if hints else "No specific hints."

    # Summarize what failed
    failed_steps = []
    for sid, r in report.get("step_results", {}).items():
        if r.get("status") == "fail":
            failed_steps.append(f"- {sid}: {r.get('reason', 'unknown')}")
    failed_text = "\n".join(failed_steps) if failed_steps else "No step failures (evaluation flagged other issues)."

    return (
        f"The previous spec execution needs a follow-up.\n\n"
        f"## Original Block\n"
        f"Name: {original_spec.get('block', {}).get('name', '?')}\n"
        f"ID: {original_spec.get('block', {}).get('id', '?')}\n\n"
        f"## What Failed\n{failed_text}\n\n"
        f"## Iteration Hints\n{hints_text}\n\n"
        f"## Acceptance Criteria Still Unmet\n"
        f"{json.dumps(original_spec.get('block', {}).get('acceptance_criteria', []), indent=2)}\n\n"
        f"## Constraints From Original Spec\n"
        f"{json.dumps(original_spec.get('constraints', {}), indent=2)}\n\n"
        f"Generate a NEW WorkBlockSpec JSON that addresses the failures and unmet criteria.\n"
        f"Output ONLY valid JSON β€” no prose, no code fences.\n\n"
        f"{_SCHEMA_REFERENCE}"
    )


# ---------------------------------------------------------------------------
# JSON extraction
# ---------------------------------------------------------------------------

def _extract_json(text: str) -> Optional[dict]:
    """Extract a JSON object from text, handling various formats.

    Tries: raw JSON, markdown code blocks, finding { } boundaries.
    """
    text = text.strip()

    # Try direct parse
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass

    # Try extracting from markdown code block
    if "```json" in text:
        start = text.index("```json") + 7
        end = text.index("```", start)
        try:
            return json.loads(text[start:end].strip())
        except (json.JSONDecodeError, ValueError):
            pass

    if "```" in text:
        start = text.index("```") + 3
        # Skip language identifier if present
        newline = text.index("\n", start)
        content_start = newline + 1
        end = text.index("```", content_start)
        try:
            return json.loads(text[content_start:end].strip())
        except (json.JSONDecodeError, ValueError):
            pass

    # Try finding outermost { } pair
    first_brace = text.find("{")
    last_brace = text.rfind("}")
    if first_brace >= 0 and last_brace > first_brace:
        try:
            return json.loads(text[first_brace:last_brace + 1])
        except json.JSONDecodeError:
            pass

    return None