-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.py
More file actions
610 lines (504 loc) · 19.2 KB
/
validate.py
File metadata and controls
610 lines (504 loc) · 19.2 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
#!/usr/bin/env python3
"""
mind_lite validator - simplified state validation
"""
import json
import sys
from pathlib import Path
BASE = Path(__file__).parent
CHARTER = BASE / "state" / "charter.json"
ROADMAP = BASE / "state" / "roadmap.json"
PROPOSALS = BASE / "proposals"
# Runner state paths
RUNNER_DIR = BASE / "state" / "runner"
RUNNER_GOAL = RUNNER_DIR / "goal.json"
RUNNER_PROGRESS = RUNNER_DIR / "progress.json"
RUNNER_TASKS = RUNNER_DIR / "tasks.json"
def load_json(path):
try:
return json.loads(path.read_text())
except FileNotFoundError:
print(f"ERROR: Missing {path}")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"ERROR: Invalid JSON in {path}: {e}")
sys.exit(1)
def validate():
"""Validate state files."""
errors = []
warnings = []
charter = load_json(CHARTER)
roadmap = load_json(ROADMAP)
# Charter checks
project = charter.get("project", {})
if not project.get("name"):
warnings.append("charter.project.name is empty")
if not project.get("why"):
warnings.append("charter.project.why is empty")
# Task checks
tasks = roadmap.get("tasks", [])
task_ids = set()
for i, task in enumerate(tasks):
tid = task.get("id")
if not tid:
errors.append(f"tasks[{i}]: missing id")
continue
if tid in task_ids:
errors.append(f"tasks[{i}]: duplicate id '{tid}'")
task_ids.add(tid)
if not task.get("deliverable"):
errors.append(f"task '{tid}': missing deliverable")
if not task.get("verify"):
errors.append(f"task '{tid}': missing verify")
# Step validation for complex tasks
if task.get("complexity") == "complex":
steps = task.get("steps", [])
if not steps:
errors.append(f"task '{tid}': complex but no steps defined")
for s in steps:
step_num = s.get("step", "?")
if not s.get("title"):
errors.append(f"task '{tid}' step {step_num}: missing title")
if not s.get("deliverable"):
errors.append(f"task '{tid}' step {step_num}: missing deliverable")
if not s.get("verify"):
errors.append(f"task '{tid}' step {step_num}: missing verify")
# Validate depends_on is a list
deps = task.get("depends_on", [])
if deps and not isinstance(deps, list):
errors.append(f"task '{tid}': depends_on must be a list, got {type(deps).__name__}")
# Check all dependencies exist and no self-dependencies
for task in tasks:
tid = task.get("id")
deps = task.get("depends_on", [])
if not isinstance(deps, list):
continue # Already reported above
for dep in deps:
if dep == tid:
errors.append(f"task '{tid}': depends on itself")
elif dep not in task_ids:
errors.append(f"task '{tid}': depends on missing '{dep}'")
# Cycle detection - returns the cycle path if found
def find_cycle(tid, visited, path):
visited.add(tid)
path.append(tid)
task = next((t for t in tasks if t.get("id") == tid), None)
if task:
for dep in task.get("depends_on", []):
if dep not in visited:
cycle = find_cycle(dep, visited, path)
if cycle:
return cycle
elif dep in path:
# Found cycle - extract it from where dep appears
cycle_start = path.index(dep)
return path[cycle_start:] + [dep]
path.pop()
return None
visited = set()
for task in tasks:
tid = task.get("id")
if tid and tid not in visited:
cycle = find_cycle(tid, set(), [])
if cycle:
errors.append(f"dependency cycle: {' -> '.join(cycle)}")
visited.update(cycle[:-1]) # Mark cycle tasks as visited
# Output
for w in warnings:
print(f"WARN: {w}")
for e in errors:
print(f"ERROR: {e}")
if errors:
return 1
return 0
def ready():
"""Show tasks ready to work on."""
roadmap = load_json(ROADMAP)
tasks = roadmap.get("tasks", [])
done = {t["id"] for t in tasks if t.get("status") in ("done", "skipped")}
ready_tasks = []
for task in tasks:
# Include "todo" and "partial" tasks (partial = can continue)
if task.get("status") not in ("todo", "partial"):
continue
deps = task.get("depends_on", [])
if all(d in done for d in deps):
ready_tasks.append(task)
# Sort by priority
def prio(t):
p = t.get("priority", "P9")
if isinstance(p, str) and p.startswith("P"):
return int(p[1:]) if p[1:].isdigit() else 9
return 9
ready_tasks.sort(key=prio)
for t in ready_tasks:
partial_flag = " [PARTIAL]" if t.get("status") == "partial" else ""
if t.get("complexity") == "complex":
steps = t.get("steps", [])
done_steps = sum(1 for s in steps if s.get("status") == "done")
total_steps = len(steps)
next_step = next((s for s in steps if s.get("status") != "done"), None)
print(f"{t['id']}\t{t.get('priority', '-')}\t{t.get('title', '')} [{done_steps}/{total_steps} steps]{partial_flag}")
if next_step:
print(f" → Next: Step {next_step.get('step')} - {next_step.get('title', '')}")
else:
print(f"{t['id']}\t{t.get('priority', '-')}\t{t.get('title', '')}{partial_flag}")
# Show partial status details if available
if t.get("status") == "partial":
if t.get("completed_criteria"):
print(f" ✓ Completed: {', '.join(t.get('completed_criteria', []))}")
if t.get("blocked_criteria"):
print(f" ✗ Blocked: {', '.join(t.get('blocked_criteria', []))}")
if t.get("blocker_reason"):
print(f" → Reason: {t.get('blocker_reason')}")
return 0
def order():
"""Show tasks in dependency order."""
roadmap = load_json(ROADMAP)
tasks = roadmap.get("tasks", [])
# Topological sort
task_map = {t["id"]: t for t in tasks if t.get("id")}
in_degree = {tid: 0 for tid in task_map}
for task in tasks:
for dep in task.get("depends_on", []):
if dep in task_map:
in_degree[task["id"]] = in_degree.get(task["id"], 0) + 1
queue = [tid for tid, deg in in_degree.items() if deg == 0]
result = []
while queue:
queue.sort()
tid = queue.pop(0)
result.append(tid)
for task in tasks:
if tid in task.get("depends_on", []):
in_degree[task["id"]] -= 1
if in_degree[task["id"]] == 0:
queue.append(task["id"])
# Warn if tasks excluded due to unmet dependencies
if len(result) != len(task_map):
missing = set(task_map.keys()) - set(result)
print(f"WARNING: {len(missing)} task(s) excluded (unmet dependencies or cycles): {', '.join(sorted(missing))}")
print()
for tid in result:
print(tid)
return 0
def steps(task_id):
"""Show steps for a specific task."""
roadmap = load_json(ROADMAP)
tasks = roadmap.get("tasks", [])
task = next((t for t in tasks if t.get("id") == task_id), None)
if not task:
print(f"ERROR: Task '{task_id}' not found")
return 1
if task.get("complexity") != "complex":
print(f"Task '{task_id}' is not complex (no steps)")
return 0
task_steps = task.get("steps", [])
if not task_steps:
print(f"Task '{task_id}' is complex but has no steps defined")
return 0
done_count = sum(1 for s in task_steps if s.get("status") == "done")
print(f"Steps for {task_id}: {task.get('title', '')} [{done_count}/{len(task_steps)}]")
print()
for s in task_steps:
status_icon = "[x]" if s.get("status") == "done" else "[ ]"
critical = " (CRITICAL)" if s.get("critical") else ""
print(f" {status_icon} Step {s.get('step', '?')}: {s.get('title', '')}{critical}")
print(f" Deliverable: {s.get('deliverable', '-')}")
print(f" Verify: {s.get('verify', '-')}")
if s.get("rollback"):
print(f" Rollback: {s.get('rollback')}")
print()
return 0
def proposals():
"""Show pending proposals."""
if not PROPOSALS.exists():
print("No proposals/ directory")
return 0
proposal_files = list(PROPOSALS.glob("TASK-*.json"))
if not proposal_files:
print("No pending proposals")
return 0
for pf in sorted(proposal_files):
try:
data = json.loads(pf.read_text())
# Validate root is an object
if not isinstance(data, dict):
print(f"{pf.name}: ERROR - not a JSON object")
continue
task_id = data.get("task_id", "?")
# Validate proposed_state_update structure
state_update = data.get("proposed_state_update")
if state_update is not None and not isinstance(state_update, dict):
print(f"{pf.name}: ERROR - proposed_state_update must be object")
continue
status = state_update.get("task_status", "?") if state_update else "?"
# Validate escalations structure
escalations_list = data.get("escalations")
if escalations_list is not None and not isinstance(escalations_list, list):
print(f"{pf.name}: ERROR - escalations must be array")
continue
escalations = len(escalations_list) if escalations_list else 0
esc_flag = f" [!] {escalations} escalations" if escalations > 0 else ""
print(f"{pf.name}: {task_id} -> {status}{esc_flag}")
except json.JSONDecodeError as e:
print(f"{pf.name}: ERROR - invalid JSON: {e}")
except (IOError, OSError) as e:
print(f"{pf.name}: ERROR - cannot read: {e}")
return 0
def load_json_safe(path):
"""Load JSON file, return None if missing or invalid."""
try:
return json.loads(path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
return None
def runner_status():
"""Show current runner state."""
goal = load_json_safe(RUNNER_GOAL)
progress = load_json_safe(RUNNER_PROGRESS)
if not progress:
print("No active runner session")
print("Start a goal with: python3 validate.py runner-init 'Your goal here'")
return 0
print("=== Runner Status ===")
print()
# Goal info
if goal:
print(f"Goal ID: {goal.get('id', 'unknown')}")
print(f"Objective: {goal.get('objective', 'none')}")
print(f"Status: {goal.get('status', 'unknown')}")
criteria = goal.get('success_criteria', [])
if criteria:
met = sum(1 for c in criteria if c.get('met'))
print(f"Success Criteria: {met}/{len(criteria)} met")
print()
# Progress info
print(f"Phase: {progress.get('phase', 'unknown')}")
print(f"Cycle: {progress.get('cycle_count', 0)}")
current = progress.get('current_task_id')
if current:
print(f"Current Task: {current}")
summary = progress.get('tasks_summary', {})
if summary:
print()
print("Tasks:")
print(f" Total: {summary.get('total', 0)}")
print(f" Completed: {summary.get('completed', 0)}")
print(f" In Progress: {summary.get('in_progress', 0)}")
print(f" Ready: {summary.get('ready', 0)}")
print(f" Pending: {summary.get('pending', 0)}")
print(f" Failed: {summary.get('failed', 0)}")
blockers = progress.get('blockers', [])
if blockers:
print()
print("Blockers:")
for b in blockers:
print(f" - [{b.get('severity', 'unknown')}] {b.get('description', '')}")
last_checkpoint = progress.get('last_checkpoint')
if last_checkpoint:
print()
print(f"Last Checkpoint: {last_checkpoint}")
return 0
def runner_ready():
"""Show ready tasks for the current runner goal."""
tasks_data = load_json_safe(RUNNER_TASKS)
if not tasks_data:
print("No runner tasks defined")
return 0
tasks = tasks_data if isinstance(tasks_data, list) else tasks_data.get('tasks', [])
# Find completed task IDs
done = {t["id"] for t in tasks if t.get("status") in ("completed", "skipped")}
ready_tasks = []
for task in tasks:
status = task.get("status", "pending")
if status not in ("pending", "ready"):
continue
deps = task.get("depends_on", [])
if all(d in done for d in deps):
ready_tasks.append(task)
# Sort by priority
def prio(t):
p = t.get("priority", 99)
return p if isinstance(p, int) else 99
ready_tasks.sort(key=prio)
if not ready_tasks:
print("No ready tasks")
return 0
for t in ready_tasks:
print(f"{t['id']}\t{t.get('priority', '-')}\t{t.get('title', '')}")
return 0
def runner_complete():
"""Check if the current goal is complete. Returns 0 if complete, 1 if not."""
progress = load_json_safe(RUNNER_PROGRESS)
goal = load_json_safe(RUNNER_GOAL)
if not progress:
print("NO_SESSION")
return 1
phase = progress.get('phase', '')
# Check phase
if phase == 'complete':
print("COMPLETE")
return 0
elif phase == 'failed':
print("FAILED")
return 1
# Check success criteria
if goal:
criteria = goal.get('success_criteria', [])
if criteria:
all_met = all(c.get('met', False) for c in criteria)
if all_met:
print("COMPLETE")
return 0
# Check if any tasks remain
tasks_data = load_json_safe(RUNNER_TASKS)
if tasks_data:
tasks = tasks_data if isinstance(tasks_data, list) else tasks_data.get('tasks', [])
pending = [t for t in tasks if t.get('status') not in ('completed', 'skipped', 'failed')]
if not pending:
print("COMPLETE")
return 0
print("IN_PROGRESS")
return 1
def runner_init(goal_text):
"""Initialize a new runner goal from natural language."""
from datetime import datetime
# Create runner directory if needed
RUNNER_DIR.mkdir(parents=True, exist_ok=True)
# Check for existing active goal
progress = load_json_safe(RUNNER_PROGRESS)
if progress and progress.get('phase') not in ('complete', 'failed', 'idle', ''):
print("ERROR: Active goal already exists. Complete or reset it first.")
print(f"Current goal: {load_json_safe(RUNNER_GOAL).get('objective', 'unknown')}")
return 1
# Generate goal ID
goal_id = f"GOAL-{datetime.now().strftime('%Y%m%d%H%M%S')}"
# Create goal structure
goal = {
"id": goal_id,
"objective": goal_text,
"raw_input": goal_text,
"constraints": [],
"success_criteria": [],
"context": {},
"status": "active",
"created_at": datetime.now().isoformat()
}
# Create initial progress
progress = {
"goal_id": goal_id,
"phase": "perceive",
"cycle_count": 0,
"current_task_id": None,
"tasks_summary": {
"total": 0,
"pending": 0,
"ready": 0,
"in_progress": 0,
"completed": 0,
"failed": 0
},
"last_action": None,
"next_action": "Parse goal and decompose into tasks",
"blockers": [],
"last_checkpoint": datetime.now().isoformat()
}
# Write files
RUNNER_GOAL.write_text(json.dumps(goal, indent=2))
RUNNER_PROGRESS.write_text(json.dumps(progress, indent=2))
# Clear old tasks if any
if RUNNER_TASKS.exists():
RUNNER_TASKS.unlink()
print(f"Goal initialized: {goal_id}")
print(f"Objective: {goal_text}")
print()
print("Next: Run the agent to decompose this goal into tasks")
print(" claude @AGENT.md")
return 0
def runner_reset():
"""Reset the runner state (clear current goal)."""
if not RUNNER_DIR.exists():
print("No runner state to reset")
return 0
# Check for active goal
progress = load_json_safe(RUNNER_PROGRESS)
if progress and progress.get('phase') not in ('complete', 'failed', 'idle', ''):
print("WARNING: Active goal in progress!")
print(f"Phase: {progress.get('phase')}")
print("Use 'runner-reset --force' to reset anyway")
if len(sys.argv) < 3 or sys.argv[2] != '--force':
return 1
# Reset runner state to empty templates (not delete)
empty_progress = {
"phase": "idle",
"cycle_count": 0,
"tasks_summary": {"total": 0, "pending": 0, "ready": 0, "in_progress": 0, "completed": 0, "failed": 0}
}
empty_goal = {}
empty_results = {}
empty_tasks = []
with open(RUNNER_PROGRESS, 'w') as f:
json.dump(empty_progress, f, indent=2)
with open(RUNNER_GOAL, 'w') as f:
json.dump(empty_goal, f, indent=2)
with open(RUNNER_DIR / 'results.json', 'w') as f:
json.dump(empty_results, f, indent=2)
with open(RUNNER_DIR / 'tasks.json', 'w') as f:
json.dump(empty_tasks, f, indent=2)
# Clear task results
tasks_dir = RUNNER_DIR / 'tasks'
if tasks_dir.exists():
for f in tasks_dir.glob('*.json'):
f.unlink()
print("Runner state reset")
return 0
def main():
if len(sys.argv) < 2:
print("Usage: validate.py <command>")
print()
print("Project commands:")
print(" validate Validate state files")
print(" ready Show ready tasks from roadmap")
print(" order Show tasks in dependency order")
print(" steps TASK-ID Show steps for a task")
print(" proposals Show pending proposals")
print()
print("Runner commands:")
print(" runner-status Show current runner state")
print(" runner-ready Show ready tasks for runner goal")
print(" runner-complete Check if goal is complete")
print(" runner-init Initialize new goal: runner-init 'goal text'")
print(" runner-reset Reset runner state (--force to override)")
return 1
cmd = sys.argv[1]
if cmd == "validate":
return validate()
elif cmd == "ready":
return ready()
elif cmd == "order":
return order()
elif cmd == "steps":
if len(sys.argv) < 3:
print("Usage: validate.py steps TASK-ID")
return 1
return steps(sys.argv[2])
elif cmd == "proposals":
return proposals()
elif cmd == "runner-status":
return runner_status()
elif cmd == "runner-ready":
return runner_ready()
elif cmd == "runner-complete":
return runner_complete()
elif cmd == "runner-init":
if len(sys.argv) < 3:
print("Usage: validate.py runner-init 'Your goal here'")
return 1
return runner_init(sys.argv[2])
elif cmd == "runner-reset":
return runner_reset()
else:
print(f"Unknown command: {cmd}")
return 1
if __name__ == "__main__":
sys.exit(main())