-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdev_council.py
More file actions
2381 lines (2040 loc) · 82.6 KB
/
Copy pathdev_council.py
File metadata and controls
2381 lines (2040 loc) · 82.6 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""dev-council: a minimal SDLC coding CLI powered by Ollama."""
from __future__ import annotations
import argparse
import atexit
import io
import json
import os
import re
import shlex
import subprocess
import sys
import textwrap
import threading
import uuid
from datetime import datetime
from pathlib import Path
import checkpoint as ckpt
from agent import (
AgentState,
PermissionRequest,
TextChunk,
ThinkingChunk,
ToolEnd,
ToolStart,
TurnDone,
run,
)
from compaction import estimate_tokens, get_context_limit, manual_compact
from config import (
CONFIG_DIR,
DAILY_DIR,
DEFAULTS,
MR_SESSION_DIR,
SESSION_HIST_FILE,
calc_cost,
current_provider,
load_config,
save_config,
)
from context import build_system_prompt
from memory import load_index, search_memory
from mcp import (
add_server_to_user_config,
list_config_files,
load_mcp_configs,
remove_server_from_user_config,
)
from mcp.client import get_mcp_manager
from mcp.tools import refresh_server, reload_mcp
from providers import (
PROVIDERS,
bare_model,
detect_provider,
get_api_key,
get_base_url,
list_ollama_models,
stream,
)
from skill.loader import find_skill, load_skills, substitute_arguments
from task import (
clear_all_tasks,
create_task,
delete_task,
get_task,
list_tasks,
update_task,
)
from tools import ask_input_interactive
VERSION = "2.7.0"
C = {
"cyan": "\033[36m",
"green": "\033[32m",
"yellow": "\033[33m",
"red": "\033[31m",
"blue": "\033[34m",
"magenta": "\033[35m",
"bold": "\033[1m",
"dim": "\033[2m",
"reset": "\033[0m",
}
def clr(text: str, *keys: str) -> str:
return "".join(C[key] for key in keys) + str(text) + C["reset"]
def info(message: str) -> None:
print(clr(message, "cyan"))
def ok(message: str) -> None:
print(clr(message, "green"))
def warn(message: str) -> None:
print(clr(f"Warning: {message}", "yellow"))
def err(message: str) -> None:
print(clr(f"Error: {message}", "red"), file=sys.stderr)
_scheduled_queries: list[str] = []
_scheduled_lock = threading.Lock()
_active_state: AgentState | None = None
_active_config: dict | None = None
def _ensure_utf8_stdio() -> None:
"""Wrap Windows stdio only during CLI execution, not at import time."""
if sys.platform != "win32":
return
for name in ("stdout", "stderr"):
stream = getattr(sys, name)
buffer = getattr(stream, "buffer", None)
if buffer is None:
continue
if str(getattr(stream, "encoding", "") or "").lower() == "utf-8":
continue
setattr(sys, name, io.TextIOWrapper(buffer, encoding="utf-8", errors="replace"))
def _enqueue_system_query(query: str) -> None:
with _scheduled_lock:
_scheduled_queries.append(query)
def _drain_scheduled_queries() -> list[str]:
with _scheduled_lock:
pending = list(_scheduled_queries)
_scheduled_queries.clear()
return pending
def _SDLC_dir() -> Path:
path = Path.cwd() / "SDLC"
path.mkdir(parents=True, exist_ok=True)
return path
def _council_dir() -> Path:
path = _SDLC_dir() / "council"
path.mkdir(parents=True, exist_ok=True)
return path
def _session_record(state: AgentState, session_id: str) -> dict:
return {
"session_id": session_id,
"saved_at": datetime.now().isoformat(timespec="seconds"),
"turn_count": state.turn_count,
"total_input_tokens": state.total_input_tokens,
"total_output_tokens": state.total_output_tokens,
"messages": state.messages,
}
def _save_history_snapshot(record: dict, latest_name: str = "session_latest.json") -> Path:
MR_SESSION_DIR.mkdir(parents=True, exist_ok=True)
latest_path = MR_SESSION_DIR / latest_name
latest_path.write_text(json.dumps(record, indent=2, ensure_ascii=False), encoding="utf-8")
return latest_path
def _save_daily_snapshot(record: dict) -> Path:
day_dir = DAILY_DIR / datetime.now().strftime("%Y-%m-%d")
day_dir.mkdir(parents=True, exist_ok=True)
suffix = record["session_id"][:8]
filename = f"session_{datetime.now().strftime('%H%M%S')}_{suffix}.json"
path = day_dir / filename
path.write_text(json.dumps(record, indent=2, ensure_ascii=False), encoding="utf-8")
return path
def _update_master_history(record: dict, config: dict) -> None:
SESSION_HIST_FILE.parent.mkdir(parents=True, exist_ok=True)
history = {"sessions": []}
if SESSION_HIST_FILE.exists():
try:
history = json.loads(SESSION_HIST_FILE.read_text(encoding="utf-8"))
except Exception:
history = {"sessions": []}
sessions = history.get("sessions", [])
sessions.append(record)
keep = int(config.get("session_history_limit", DEFAULTS["session_history_limit"]))
history["sessions"] = sessions[-keep:]
history["total_turns"] = sum(item.get("turn_count", 0) for item in history["sessions"])
SESSION_HIST_FILE.write_text(json.dumps(history, indent=2, ensure_ascii=False), encoding="utf-8")
def save_session(state: AgentState, config: dict, session_id: str) -> None:
record = _session_record(state, session_id)
latest = _save_history_snapshot(record)
daily = _save_daily_snapshot(record)
_update_master_history(record, config)
ok(f"Session saved -> {latest}")
ok(f" -> {daily}")
def _autosave_session() -> None:
if _active_state is None or _active_config is None:
return
session_id = _active_config.get("_session_id", "")
if not session_id:
return
try:
save_session(_active_state, _active_config, session_id)
except Exception:
pass
def load_session_file(path: Path) -> AgentState | None:
if not path.exists():
err(f"Session file not found: {path}")
return None
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
err(f"Failed to load session: {exc}")
return None
state = AgentState()
state.messages = payload.get("messages", [])
state.turn_count = int(payload.get("turn_count", 0))
state.total_input_tokens = int(payload.get("total_input_tokens", 0))
state.total_output_tokens = int(payload.get("total_output_tokens", 0))
return state
def _permission_prompt(description: str, config: dict) -> bool:
if config.get("permission_mode") == "accept-all":
return True
raw = ask_input_interactive(clr(f"Allow this action? {description} [y/N] ", "yellow"), config)
return raw.strip().lower() in {"y", "yes"}
def _print_tool_result(result: str, config: dict) -> None:
if not result:
return
if "--- a/" in result and "+++ b/" in result:
print(result)
return
lines = result.strip().splitlines()
if not lines:
return
is_error = result.strip().startswith("Error")
limit = 10 if not config.get("verbose") else 50
preview_lines = lines[:limit]
preview = "\n".join(preview_lines)
if len(lines) > limit or len(preview) > 2000:
preview = preview[:2000]
if not preview.endswith("\n"):
preview += "\n"
preview += clr(f" [...truncated {len(lines) - len(preview_lines)} lines...]", "dim")
color = "red" if is_error else "dim"
print(clr(" result:", color))
print(textwrap.indent(preview, " "))
def _context_usage(state: AgentState, config: dict) -> tuple[int, int, int]:
used = estimate_tokens(state.messages)
limit = get_context_limit(config.get("model", DEFAULTS["model"]))
percent = min(999, int((used / limit) * 100)) if limit else 0
return used, limit, percent
def _context_footer(state: AgentState, config: dict) -> str:
used, limit, percent = _context_usage(state, config)
return f"[Context: {percent}% used | ~{used:,} / {limit:,} tokens]"
def _print_context_footer(state: AgentState, config: dict) -> None:
print(clr(_context_footer(state, config), "dim"))
def _auto_compaction_notice(percent: int) -> None:
print(clr(f"⚠️ Context compaction triggered automatically (usage: {percent}%)", "yellow"))
def _print_banner() -> None:
banner = r"""
____ _______ __ ____ ___ _ _ _ _ ____ ___ _
| _ \| ____\ \ / / / ___/ _ \| | | | \ | |/ ___|_ _| |
| | | | _| \ \ / /_____ | | | | | | | | | \| | | | || |
| |_| | |___ \ V /|_____| | |__| |_| | |_| | |\ | |___ | || |___
|____/|_____| \_/ \____\___/ \___/|_| \_|\____|___|_____|
"""
print(clr(banner.rstrip(), "cyan", "bold"))
print(clr(f"dev-council {VERSION}", "cyan", "bold"))
print(clr("SDLC stages: SRS -> Milestones -> Tech Stack -> Code -> QA -> Deployment", "dim"))
print(clr("Use /model to choose Single LLM or Consensus mode. Press Ctrl+C to exit.", "dim"))
def _exit_on_interrupt() -> None:
print()
ok("Exiting dev-council.")
def _run_agent_query(
query: str,
state: AgentState,
config: dict,
model_override: str = "",
quiet: bool = False,
use_skills: bool = False,
) -> str:
effective_config = dict(config)
if model_override:
effective_config["model"] = model_override
effective_config["_run_query_callback"] = _enqueue_system_query
effective_config["_auto_compact_notice"] = _auto_compaction_notice
if use_skills:
query, _ = _apply_skill_context(query, announce=not quiet, force_coding=True)
system_prompt = build_system_prompt(effective_config)
response_parts: list[str] = []
for event in run(query, state, effective_config, system_prompt):
if isinstance(event, TextChunk):
response_parts.append(event.text)
if not quiet:
print(event.text, end="", flush=True)
elif isinstance(event, ThinkingChunk):
if effective_config.get("verbose") and not quiet:
print(clr(event.text, "dim"), end="", flush=True)
elif isinstance(event, ToolStart):
if not quiet:
print()
target = (
event.inputs.get("file_path")
or event.inputs.get("path")
or event.inputs.get("command")
or event.inputs.get("target")
or event.inputs.get("query")
)
if target:
info(f"[tool] {event.name}: {target}")
else:
info(f"[tool] {event.name}")
if effective_config.get("verbose"):
params_str = json.dumps(event.inputs, ensure_ascii=False)
print(clr(f" parameters: {params_str}", "dim"))
elif isinstance(event, ToolEnd):
if not quiet:
_print_tool_result(event.result, effective_config)
elif isinstance(event, PermissionRequest):
event.granted = _permission_prompt(event.description, effective_config)
elif isinstance(event, TurnDone):
if effective_config.get("verbose") and not quiet:
print()
info(f"[tokens] input={event.input_tokens} output={event.output_tokens}")
if not quiet:
print()
return "".join(response_parts)
def _run_text_prompt(
prompt: str,
config: dict,
model: str = "",
system: str = "",
use_skills: bool = False,
announce_skills: bool = False,
) -> str:
prompt_model = model or config["model"]
prompt_system = system or "You are dev-council. Respond with clean Markdown only."
if use_skills:
prompt, _ = _apply_skill_context(prompt, announce=announce_skills, force_coding=True)
text_parts: list[str] = []
llm_config = dict(config)
llm_config["no_tools"] = True
for event in stream(
model=prompt_model,
system=prompt_system,
messages=[{"role": "user", "content": prompt}],
tool_schemas=[],
config=llm_config,
):
if hasattr(event, "text"):
text_parts.append(event.text)
return "".join(text_parts).strip()
def _run_generation_prompt(prompt: str, config: dict, system: str = "") -> str:
if config.get("llm_mode") != "consensus":
return _run_text_prompt(prompt, config, system=system)
selected_models = list(config.get("consensus_models") or [])
if not selected_models:
warn("Consensus mode has no models selected; falling back to active single model.")
return _run_text_prompt(prompt, config, system=system)
council_root = _council_dir() / datetime.now().strftime("%Y%m%d_%H%M%S")
council_root.mkdir(parents=True, exist_ok=True)
proposals: list[tuple[str, str]] = []
failures: list[tuple[str, str]] = []
for index, model_name in enumerate(selected_models, 1):
info(f"Consensus prompt {index}/{len(selected_models)}: {model_name}")
try:
proposal = _run_text_prompt(prompt, config, model=model_name, system=system)
proposals.append((model_name, proposal))
proposal_path = council_root / f"proposal_{index}_{bare_model(model_name).replace(':', '_')}.md"
proposal_path.write_text(proposal + "\n", encoding="utf-8")
except Exception as exc:
failures.append((model_name, str(exc)))
warn(f"Consensus model failed: {model_name} -> {exc}")
if not proposals:
details = "; ".join(f"{model_name}: {error}" for model_name, error in failures)
raise RuntimeError(f"All consensus models failed for this prompt. {details}")
if len(proposals) == 1:
if failures:
warn("Continuing with the only successful consensus model response.")
return proposals[0][1]
synthesis_prompt = ["Synthesize these model responses into one final output."]
synthesis_prompt.append(f"Original prompt:\n{prompt}\n")
for model_name, proposal in proposals:
synthesis_prompt.append(f"[{model_name}]\n{proposal}\n")
synthesis_prompt.append("Return only the final synthesized answer.")
# Use the judge model for synthesis if configured, otherwise first successful proposer
judge = config.get("judge_model") or proposals[0][0]
info(f"Synthesizing consensus with {judge}")
synthesis_result = _run_text_prompt(
"\n".join(synthesis_prompt),
config,
model=judge,
system="You are a consensus editor. Produce the final answer only.",
)
consensus_path = council_root / "consensus.md"
consensus_path.write_text(synthesis_result + "\n", encoding="utf-8")
ok(f"Consensus output saved to {council_root}")
return synthesis_result
def _strip_wrapping_code_fence(content: str) -> str:
stripped = content.strip()
if not stripped.startswith("```"):
return stripped
lines = stripped.splitlines()
if len(lines) < 3 or lines[-1].strip() != "```":
return stripped
return "\n".join(lines[1:-1]).strip()
def _sanitize_markdown_stage_output(content: str) -> str:
cleaned = _strip_wrapping_code_fence(content)
lines = cleaned.splitlines()
chatter_prefixes = (
"here is",
"here's",
"below is",
"this is",
"i have",
"i've",
"i will",
"i'll",
"we need to",
"we should",
"let me",
"certainly",
"sure",
"the following",
)
while lines and not lines[0].strip():
lines.pop(0)
while lines:
first = lines[0].strip()
lowered = first.lower()
if any(lowered.startswith(prefix) for prefix in chatter_prefixes):
lines.pop(0)
while lines and not lines[0].strip():
lines.pop(0)
continue
break
return "\n".join(lines).strip()
def _extract_json_fragment(content: str) -> str:
stripped = content.strip()
candidates = [stripped, _strip_wrapping_code_fence(stripped)]
fence_matches = re.findall(r"```(?:json)?\s*(.*?)```", content, flags=re.IGNORECASE | re.DOTALL)
candidates.extend(match.strip() for match in fence_matches if match.strip())
for candidate in candidates:
if not candidate:
continue
try:
json.loads(candidate)
return candidate
except Exception:
continue
starts = sorted(
{index for token in ("{", "[") for index in [content.find(token)] if index != -1}
)
for start in starts:
opening = content[start]
closing = "}" if opening == "{" else "]"
depth = 0
in_string = False
escape = False
for end in range(start, len(content)):
char = content[end]
if in_string:
if escape:
escape = False
elif char == "\\":
escape = True
elif char == '"':
in_string = False
continue
if char == '"':
in_string = True
continue
if char == opening:
depth += 1
continue
if char == closing:
depth -= 1
if depth == 0:
candidate = content[start:end + 1].strip()
try:
json.loads(candidate)
return candidate
except Exception:
break
raise ValueError("Model output did not contain valid JSON.")
def _listify(value: object) -> list[str]:
if value is None:
return []
if isinstance(value, str):
text = value.strip()
return [text] if text else []
if isinstance(value, list):
items: list[str] = []
for item in value:
text = str(item).strip()
if text:
items.append(text)
return items
text = str(value).strip()
return [text] if text else []
def _normalize_milestone_tasks(content: str) -> str:
payload = json.loads(_extract_json_fragment(content))
raw_tasks = payload.get("tasks") if isinstance(payload, dict) else payload
if not isinstance(raw_tasks, list) or not raw_tasks:
raise ValueError("Milestone output must include a non-empty tasks list.")
prepared: list[tuple[str, dict]] = []
id_aliases: dict[str, str] = {}
used_ids: set[str] = set()
for index, item in enumerate(raw_tasks, 1):
if not isinstance(item, dict):
raise ValueError("Each milestone task must be a JSON object.")
candidate_id = str(item.get("id") or index).strip() or str(index)
task_id = candidate_id
while task_id in used_ids:
task_id = str(len(used_ids) + 1)
used_ids.add(task_id)
prepared.append((task_id, item))
id_aliases[candidate_id] = task_id
id_aliases[task_id] = task_id
tasks: list[dict] = []
now = datetime.now().isoformat()
valid_statuses = {"pending", "in_progress", "completed", "cancelled"}
for task_id, item in prepared:
subject = str(
item.get("subject")
or item.get("title")
or item.get("name")
or f"Milestone Task {task_id}"
).strip()
description = str(item.get("description") or "").strip()
status = str(item.get("status") or "pending").strip().lower()
dependencies = _listify(
item.get("blocked_by")
or item.get("depends_on")
or item.get("dependencies")
)
blocked_by = [id_aliases[dep] for dep in dependencies if dep in id_aliases]
metadata = dict(item.get("metadata") or {})
milestone = str(item.get("milestone") or item.get("phase") or "").strip()
deliverables = _listify(item.get("deliverables"))
acceptance_criteria = _listify(
item.get("acceptance_criteria") or item.get("done_criteria")
)
if milestone:
metadata["milestone"] = milestone
if deliverables:
metadata["deliverables"] = deliverables
if acceptance_criteria:
metadata["acceptance_criteria"] = acceptance_criteria
if not description:
description = "; ".join(deliverables or acceptance_criteria) or subject
tasks.append(
{
"id": task_id,
"subject": subject,
"description": description,
"status": status if status in valid_statuses else "pending",
"active_form": str(item.get("active_form") or "").strip(),
"owner": str(item.get("owner") or "").strip(),
"blocks": [],
"blocked_by": blocked_by,
"metadata": metadata,
"created_at": str(item.get("created_at") or now),
"updated_at": str(item.get("updated_at") or now),
}
)
tasks_by_id = {task["id"]: task for task in tasks}
for task in tasks:
for blocker_id in task["blocked_by"]:
blocker = tasks_by_id.get(blocker_id)
if blocker is not None and task["id"] not in blocker["blocks"]:
blocker["blocks"].append(task["id"])
normalized = {
"tasks": tasks,
"generated_at": now,
"artifact": "milestones",
}
return json.dumps(normalized, indent=2, ensure_ascii=False)
def _sanitize_stage_output(stage_name: str, content: str) -> str:
if stage_name == "milestones":
return _normalize_milestone_tasks(content)
return _sanitize_markdown_stage_output(content)
def _render_stage_prompt(template: str, context: str) -> str:
return template.replace("{context}", context)
def _project_snapshot(limit: int = 200) -> str:
files: list[str] = []
for path in sorted(Path.cwd().rglob("*")):
if ".git" in path.parts or "__pycache__" in path.parts:
continue
if path.is_file():
files.append(str(path.relative_to(Path.cwd())))
if len(files) >= limit:
break
return "\n".join(files)
def _stage_context(extra: str = "") -> str:
sections = []
SDLC = _SDLC_dir()
for name in ["srs.md", "tasks.json", "tech_stack.md", "qa_report.md", "deployment_plan.md"]:
path = SDLC / name
if path.exists():
sections.append(f"[{name}]\n{path.read_text(encoding='utf-8')[:8000]}")
if extra:
sections.append(f"[user]\n{extra}")
return "\n\n".join(sections).strip()
def _tokenize(text: str) -> set[str]:
cleaned = []
current = []
for char in text.lower():
if char.isalnum() or char in {"-", "_"}:
current.append(char)
else:
if current:
cleaned.append("".join(current))
current = []
if current:
cleaned.append("".join(current))
return {token for token in cleaned if len(token) >= 3}
def _select_relevant_skills(query: str, force_coding: bool = True) -> list:
query_terms = _tokenize(query)
scored: list[tuple[int, object]] = []
coding_skill_names = {
"implementation-core",
"frontend-builder",
"backend-builder",
"fullstack-builder",
"testing-guard",
}
frontend_terms = {"frontend", "react", "next", "html", "css", "ui", "ux", "landing", "tailwind"}
backend_terms = {"backend", "python", "api", "server", "database", "auth", "fastapi", "django", "flask", "sql"}
fullstack_terms = {"saas", "fullstack", "full-stack", "dashboard", "platform", "product", "portal", "crm"}
testing_terms = {"test", "tests", "testing", "qa", "pytest", "unit", "integration", "e2e", "bug", "fix"}
for skill in load_skills():
if force_coding and skill.name not in coding_skill_names:
continue
corpus = " ".join(
[
skill.name,
skill.description,
skill.when_to_use,
" ".join(skill.triggers),
]
)
skill_terms = _tokenize(corpus)
score = len(query_terms & skill_terms)
if skill.name == "implementation-core" and force_coding:
score += 3
if query_terms & frontend_terms and skill.name == "frontend-builder":
score += 4
if query_terms & backend_terms and skill.name == "backend-builder":
score += 4
if query_terms & fullstack_terms and skill.name == "fullstack-builder":
score += 4
if query_terms & testing_terms and skill.name == "testing-guard":
score += 4
if score > 0:
scored.append((score, skill))
scored.sort(key=lambda item: (-item[0], item[1].name))
selected = []
seen = set()
for _, skill in scored:
if skill.name in seen:
continue
selected.append(skill)
seen.add(skill.name)
if len(selected) >= 3:
break
if force_coding and "implementation-core" not in seen:
for skill in load_skills():
if skill.name == "implementation-core":
selected.insert(0, skill)
break
return selected[:3]
def _apply_skill_context(query: str, announce: bool = True, force_coding: bool = True) -> tuple[str, list[str]]:
skills = _select_relevant_skills(query, force_coding=force_coding)
if not skills:
return query, []
names = [skill.name for skill in skills]
if announce:
info(f"[skills] Using: {', '.join(names)}")
rendered = []
for skill in skills:
rendered_prompt = substitute_arguments(skill.prompt, query, skill.arguments)
rendered.append(f"[Auto-applied skill: {skill.name}]\n{rendered_prompt}")
enriched_query = (
f"{query}\n\n"
"Apply the following skill guidance while working:\n\n"
+ "\n\n".join(rendered)
)
return enriched_query, names
def _project_is_effectively_empty() -> bool:
ignored = {"SDLC", "__pycache__", "node_modules", ".git"}
for child in Path.cwd().iterdir():
if child.name.startswith("."):
continue
if child.name in ignored:
continue
return False
return True
def _looks_like_large_product_request(query: str) -> bool:
lowered = query.lower()
words = re.findall(r"\b[\w-]+\b", lowered)
build_terms = (
"build",
"create",
"develop",
"make a full",
"implement a system",
)
product_terms = (
"saas",
"full stack",
"fullstack",
"full-stack",
"full system",
"dashboard",
"platform",
"portal",
"marketplace",
"crm",
"erp",
"admin panel",
"web app",
"application",
"product",
"system",
"feature set",
)
has_build_term = any(term in lowered for term in build_terms)
has_product_term = any(term in lowered for term in product_terms)
return (has_build_term and has_product_term) or (len(words) > 30 and has_product_term)
def _should_apply_skill_context(query: str) -> bool:
lowered = query.lower().strip()
if not lowered:
return False
informational_starts = (
"read ",
"show ",
"tell ",
"explain ",
"summarize ",
"what ",
"why ",
"how ",
"list ",
"find ",
"search ",
"inspect ",
"review ",
)
mutation_terms = (
"add",
"build",
"change",
"code",
"create",
"debug",
"develop",
"edit",
"fix",
"implement",
"refactor",
"remove",
"repair",
"test",
"update",
"write",
)
if lowered.startswith(informational_starts) and not any(term in lowered for term in mutation_terms):
return False
return any(term in lowered for term in mutation_terms)
_STAGE_SPECS = {
"srs": {
"file": "srs.md",
"title": "Software Requirements Specification",
"prompt": (
"Create a Software Requirements Specification for this request.\n\n"
"{context}\n\n"
"Include: overview, goals, actors, functional requirements, non-functional "
"requirements, assumptions, risks, success criteria, and acceptance criteria.\n\n"
"Return only the final Markdown document body with no prefatory text."
),
},
"milestones": {
"file": "tasks.json",
"title": "Milestone Tasks",
"prompt": (
"Create milestone tasks for this project context.\n\n"
"{context}\n\n"
"Return JSON only using this shape:\n"
"{\n"
' "tasks": [\n'
" {\n"
' "id": "1",\n'
' "subject": "Short task title",\n'
' "description": "What must be completed",\n'
' "blocked_by": [],\n'
' "milestone": "Milestone 1",\n'
' "deliverables": ["deliverable"],\n'
' "acceptance_criteria": ["done criteria"]\n'
" }\n"
" ]\n"
"}\n\n"
"The tasks must cover milestone sequencing from foundation to delivery. Do not add Markdown, code fences, or explanations."
),
},
"techstack": {
"file": "tech_stack.md",
"title": "Technology Stack",
"prompt": (
"Generate a recommended technology stack for this project context.\n\n"
"{context}\n\n"
"Include details for the Frontend, Backend, Database, and Deployment strategy, and "
"provide a brief rationale for these choices.\n\n"
"Return only the final Markdown document body with no prefatory text."
),
},
"qa": {
"file": "qa_report.md",
"title": "QA Strategy and Report",
"prompt": (
"Create a QA strategy and assessment for this project context.\n\n"
"{context}\n\n"
"Include unit tests, integration tests, end-to-end checks, performance validation, "
"security review, gaps, and recommended fixes.\n\n"
"Return only the final Markdown document body with no prefatory text."
),
},
"deploy": {
"file": "deployment_plan.md",
"title": "Deployment and CI/CD Plan",
"prompt": (
"Create a deployment and CI/CD plan for this project context.\n\n"
"{context}\n\n"
"Include build pipeline, environments, secrets, release flow, rollback, monitoring, "
"and production-readiness gates.\n\n"
"Return only the final Markdown document body with no prefatory text."
),
},
}
def _write_stage_file(stage_name: str, content: str) -> Path:
spec = _STAGE_SPECS[stage_name]
path = _SDLC_dir() / spec["file"]
if _active_config and _active_config.get("_session_id"):
ckpt.track_file_edit(_active_config["_session_id"], str(path))
cleaned = _sanitize_stage_output(stage_name, content)
path.write_text(cleaned.strip() + "\n", encoding="utf-8")
return path
def _run_stage(stage_name: str, user_text: str, config: dict) -> Path:
spec = _STAGE_SPECS[stage_name]
context = _stage_context(user_text)
use_consensus = False
raw_consensus = ask_input_interactive(clr(f"Do you want consensus for {spec['title']}? [y/N] ", "yellow"), config).strip().lower()
if raw_consensus in {"y", "yes"}:
use_consensus = True
original_llm_mode = config.get("llm_mode")
original_model = config.get("model")
if use_consensus:
config["llm_mode"] = "consensus"
else:
config["llm_mode"] = "single"
selected_models = config.get("consensus_models", [])
if len(selected_models) > 1:
print()
info(f"Available models for {spec['title']}:")
for idx, m in enumerate(selected_models, 1):
print(f" [{idx}] {m}")
while True:
raw_idx = ask_input_interactive("Select model number: ", config).strip()
if raw_idx.isdigit() and 1 <= int(raw_idx) <= len(selected_models):
config["model"] = selected_models[int(raw_idx) - 1]
break
err("Invalid selection.")
elif len(selected_models) == 1:
config["model"] = selected_models[0]
try:
feedback_context = ""
while True:
base_prompt = _render_stage_prompt(spec["prompt"], context or user_text)
if feedback_context:
prompt = base_prompt + "\n\nUser feedback on previous iteration:\n" + feedback_context + "\n\nPlease revise the output incorporating this feedback."
else:
prompt = base_prompt
system = (
f"You are dev-council working on SDLC stage output: {spec['title']}. "
"Return only the requested artifact. Do not add explanations, prefaces, code fences, or commentary."
)
result = _sanitize_stage_output(
stage_name,
_run_generation_prompt(prompt, config, system=system),