File size: 12,418 Bytes
6859bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Inference logic for task decomposition using FLAN-T5.

Real mode: builds a structured prompt, runs FLAN-T5 generation, parses
the output lines in SUBTASK_N format.

Mock mode: returns realistic fake subtask suggestions based on keyword
matching so the full UI can be built before training is complete.
"""

import logging
import random
import re

from .model import get_model
from utils.privacy import assert_no_pii

log = logging.getLogger(__name__)

_FIBONACCI = {1, 2, 3, 5, 8, 13}


def decompose(
    task_id: str,
    title: str,
    description: str,
    priority: str,
    project_context: str,
    existing_tags: list[str],
) -> dict:
    """Run decomposition inference (or mock).

    Returns a dict matching DecomposeResponse schema.
    """
    # PII hard-stop — model never runs if this fails
    assert_no_pii(
        {
            "task_id": task_id,
            "title": title,
            "description": description,
            "priority": priority,
            "project_context": project_context,
            "existing_tags": existing_tags,
        },
        context="decomposition",
    )

    dm = get_model()

    if dm.is_mock:
        return _mock_decompose(task_id, title, description, priority, existing_tags)

    return _real_decompose(
        dm, task_id, title, description, priority, existing_tags, project_context
    )


# ---------------------------------------------------------------------------
# Real model inference
# ---------------------------------------------------------------------------
def _real_decompose(
    dm, task_id, title, description, priority, tags, project_context
) -> dict:
    """Run FLAN-T5 generation and parse structured output."""
    import torch

    device = next(dm.model.parameters()).device

    # Build prompt matching training format
    prompt = (
        f"Decompose this software task into subtasks:\n"
        f"Task: {title}\n"
        f"Description: {description}\n"
        f"Priority: {priority}\n"
        f"Context: {project_context or 'software project'}"
    )

    inputs = dm.tokenizer(
        prompt,
        return_tensors="pt",
        max_length=512,
        truncation=True,
    ).to(device)

    with torch.no_grad():
        outputs = dm.model.generate(
            **inputs,
            max_new_tokens=256,
            num_beams=4,
            temperature=0.7,
            early_stopping=True,
            do_sample=False,
        )

    raw_output = dm.tokenizer.decode(outputs[0], skip_special_tokens=True)
    log.debug("Raw model output: %s", raw_output)

    # Parse structured lines
    subtasks = _parse_model_output(raw_output, priority, tags)
    overall_confidence = _compute_confidence(subtasks, raw_output)

    return {
        "task_id": task_id,
        "subtasks": subtasks,
        "overall_confidence": overall_confidence,
        "model_version": dm.version,
    }


# ---------------------------------------------------------------------------
# Output parsing — handles SUBTASK_N structured format
# ---------------------------------------------------------------------------
_SUBTASK_PATTERN = re.compile(
    r"SUBTASK_\d+:\s*(?P<title>[^|]+)"
    r"\|\s*PRIORITY:\s*(?P<priority>[^|]+)"
    r"\|\s*POINTS:\s*(?P<points>[^|]+)"
    r"\|\s*DAYS:\s*(?P<days>[^|]+)"
    r"\|\s*TAGS:\s*(?P<tags>.+)",
    re.IGNORECASE,
)


def parse_subtask_line(line: str) -> dict | None:
    """Parse a single SUBTASK_N line into a subtask dict.

    Expected format:
      SUBTASK_1: title | PRIORITY: p | POINTS: n | DAYS: n | TAGS: t1,t2

    Returns None if the line doesn't match the expected format.
    """
    match = _SUBTASK_PATTERN.match(line.strip())
    if not match:
        return None

    title = match.group("title").strip()
    priority = match.group("priority").strip().lower()
    tags_str = match.group("tags").strip()

    # Parse story points — must be Fibonacci
    try:
        points = int(float(match.group("points").strip()))
        if points not in _FIBONACCI:
            points = min(_FIBONACCI, key=lambda x: abs(x - points))
    except (ValueError, TypeError):
        points = 2

    # Parse days
    try:
        days = round(float(match.group("days").strip()), 1)
        days = max(0.5, min(20.0, days))
    except (ValueError, TypeError):
        days = 1.0

    # Parse tags
    tags = [t.strip() for t in tags_str.split(",") if t.strip()]

    # Validate priority
    valid_priorities = {"low", "medium", "high", "urgent"}
    if priority not in valid_priorities:
        priority = "medium"

    return {
        "title": title,
        "description": "",
        "priority": priority,
        "story_points": points,
        "estimated_days": days,
        "tags": tags,
        "confidence": round(random.uniform(0.65, 0.92), 2),
    }


def _parse_model_output(
    raw: str, fallback_priority: str, fallback_tags: list[str]
) -> list[dict]:
    """Parse full model output into a list of subtask dicts.

    Tries structured SUBTASK_N format first, then falls back to
    line-by-line parsing for unstructured output.
    """
    subtasks = []

    # Try structured format first
    for line in raw.split("\n"):
        line = line.strip()
        if not line:
            continue
        parsed = parse_subtask_line(line)
        if parsed:
            subtasks.append(parsed)

    if subtasks:
        return subtasks

    # Fallback: treat each non-empty line as a subtask title
    lines = [l.strip() for l in raw.split("\n") if l.strip()]
    for line in lines:
        # Strip leading numbering like "1." or "1)"
        cleaned = re.sub(r"^\d+[\.\)]\s*", "", line)
        if cleaned and len(cleaned) > 3:
            subtasks.append({
                "title": cleaned[:120],
                "description": "",
                "priority": fallback_priority,
                "story_points": 2,
                "estimated_days": 1.0,
                "tags": fallback_tags[:2] if fallback_tags else ["general"],
                "confidence": 0.45,
            })

    # If nothing parsed at all, return a single generic subtask
    if not subtasks:
        subtasks.append({
            "title": "Implement task requirements",
            "description": "",
            "priority": fallback_priority,
            "story_points": 3,
            "estimated_days": 1.5,
            "tags": fallback_tags[:2] if fallback_tags else ["general"],
            "confidence": 0.3,
        })

    return subtasks


def _compute_confidence(subtasks: list[dict], raw_output: str) -> float:
    """Compute overall confidence based on output quality signals."""
    if not subtasks:
        return 0.1

    score = 0.4

    # More subtasks (2-6) is a good sign
    n = len(subtasks)
    if 2 <= n <= 6:
        score += 0.15
    elif n > 6:
        score += 0.05

    # Structured format parsed successfully
    if any(parse_subtask_line(line) for line in raw_output.split("\n") if line.strip()):
        score += 0.2

    # Subtasks have varied story points
    points = {s.get("story_points") for s in subtasks}
    if len(points) > 1:
        score += 0.1

    # Individual confidence average
    avg_conf = sum(s.get("confidence", 0.5) for s in subtasks) / n
    score += avg_conf * 0.15

    return max(0.0, min(1.0, round(score, 2)))


# ---------------------------------------------------------------------------
# Mock inference — realistic fake data for UI development
# ---------------------------------------------------------------------------
_MOCK_KEYWORD_TEMPLATES = {
    "auth": [
        ("Set up authentication provider configuration", "high", 3, 1.0, "backend,auth"),
        ("Implement login and signup API endpoints", "high", 5, 2.0, "backend,auth,api"),
        ("Build login form with validation", "medium", 3, 1.0, "frontend,auth,forms"),
        ("Add session management and token refresh", "high", 3, 1.5, "backend,auth,security"),
        ("Write authentication tests", "medium", 3, 1.0, "testing,auth"),
    ],
    "api": [
        ("Design API endpoint structure and request schemas", "high", 2, 0.5, "backend,api,design"),
        ("Implement CRUD endpoints with validation", "high", 5, 2.0, "backend,api"),
        ("Add error handling and status codes", "medium", 2, 1.0, "backend,api"),
        ("Write API integration tests", "medium", 3, 1.5, "testing,api"),
        ("Document API endpoints with examples", "low", 2, 1.0, "docs,api"),
    ],
    "ui": [
        ("Create component layout and structure", "medium", 2, 0.5, "frontend,ui"),
        ("Build interactive UI components", "high", 5, 2.0, "frontend,ui"),
        ("Add responsive design and mobile support", "medium", 3, 1.0, "frontend,ui,responsive"),
        ("Implement accessibility features", "low", 2, 1.0, "frontend,ui,a11y"),
    ],
    "database": [
        ("Design database schema and relations", "high", 3, 1.0, "backend,database"),
        ("Write migration scripts", "high", 2, 0.5, "backend,database,migration"),
        ("Add indexes for query optimization", "medium", 2, 0.5, "backend,database"),
        ("Create seed data for development", "low", 2, 1.0, "backend,database"),
    ],
    "test": [
        ("Set up test framework and utilities", "high", 2, 0.5, "testing,setup"),
        ("Write unit tests for core logic", "high", 3, 1.5, "testing,unit"),
        ("Write integration tests", "medium", 5, 2.0, "testing,integration"),
        ("Set up CI test pipeline", "medium", 2, 1.0, "testing,ci"),
    ],
    "deploy": [
        ("Write Dockerfile and container config", "high", 3, 1.0, "devops,docker"),
        ("Configure CI/CD pipeline", "high", 3, 1.5, "devops,ci"),
        ("Set up environment variables and secrets", "medium", 2, 0.5, "devops,config"),
        ("Add health checks and monitoring", "medium", 2, 1.0, "devops,monitoring"),
    ],
}

# Default template when no keyword matches
_MOCK_DEFAULT_TEMPLATES = {
    "high": [
        ("Define requirements and acceptance criteria", "high", 2, 0.5, "planning"),
        ("Implement core functionality", "high", 5, 2.0, "development"),
        ("Write automated tests", "medium", 3, 1.0, "testing"),
        ("Code review and refactor", "medium", 2, 0.5, "review"),
        ("Deploy and verify", "low", 1, 0.5, "devops"),
    ],
    "medium": [
        ("Research and design approach", "medium", 2, 0.5, "planning"),
        ("Implement solution", "medium", 3, 1.5, "development"),
        ("Test and validate", "medium", 2, 1.0, "testing"),
    ],
    "low": [
        ("Investigate and plan", "low", 1, 0.5, "planning"),
        ("Implement change", "low", 2, 1.0, "development"),
        ("Verify and document", "low", 1, 0.5, "docs"),
    ],
    "urgent": [
        ("Triage and identify root cause", "urgent", 2, 0.5, "investigation"),
        ("Implement fix", "urgent", 3, 1.0, "development"),
        ("Write regression test", "high", 2, 0.5, "testing"),
        ("Deploy hotfix", "urgent", 1, 0.5, "devops"),
    ],
}


def _mock_decompose(
    task_id: str,
    title: str,
    description: str,
    priority: str,
    tags: list[str],
) -> dict:
    """Generate realistic mock subtasks based on keyword matching."""
    log.info("MOCK decomposition for task %s: %s", task_id, title)

    combined_text = f"{title} {description}".lower()

    # Try keyword matching first
    templates = None
    for keyword, keyword_templates in _MOCK_KEYWORD_TEMPLATES.items():
        if keyword in combined_text:
            templates = keyword_templates
            break

    # Fall back to priority-based templates
    if templates is None:
        templates = _MOCK_DEFAULT_TEMPLATES.get(
            priority, _MOCK_DEFAULT_TEMPLATES["medium"]
        )

    subtasks = []
    for title_t, prio, points, days, tags_str in templates:
        subtask_tags = tags_str.split(",")
        # Merge with existing tags if any
        if tags:
            subtask_tags = list(set(subtask_tags + tags[:1]))

        subtasks.append({
            "title": title_t,
            "description": "",
            "priority": prio,
            "story_points": points,
            "estimated_days": days,
            "tags": subtask_tags,
            "confidence": round(random.uniform(0.72, 0.93), 2),
        })

    return {
        "task_id": task_id,
        "subtasks": subtasks,
        "overall_confidence": round(random.uniform(0.75, 0.90), 2),
        "model_version": "mock-v0",
    }