delimit-cli 4.0.3 → 4.0.4

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.
@@ -0,0 +1,240 @@
1
+ """Ledger Propose — AI-driven item generation from signals.
2
+
3
+ Analyzes repo state, sensing signals, completed work, and venture priorities
4
+ to propose 3-5 new ledger items with rationale. Runs at end of build loops
5
+ when the queue is empty, or on-demand.
6
+
7
+ Works across all AI models via MCP — no model-specific code.
8
+ """
9
+
10
+ import json
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional
14
+
15
+
16
+ SIGNALS_DIR = Path.home() / ".delimit" / "signals"
17
+ PROPOSALS_DIR = Path.home() / ".delimit" / "proposals"
18
+
19
+
20
+ def _gather_context(venture: str = "") -> Dict[str, Any]:
21
+ """Collect context from multiple sources for proposal generation."""
22
+ context = {
23
+ "timestamp": time.time(),
24
+ "venture": venture or "all",
25
+ "sources": {},
26
+ }
27
+
28
+ # 1. Recent ledger completions (what just shipped)
29
+ ledger_path = Path.home() / ".delimit" / "ledger.jsonl"
30
+ if ledger_path.exists():
31
+ recent_done = []
32
+ for line in ledger_path.read_text().strip().split("\n")[-100:]:
33
+ try:
34
+ item = json.loads(line)
35
+ if item.get("status") == "done":
36
+ recent_done.append({
37
+ "id": item.get("id", ""),
38
+ "title": item.get("title", ""),
39
+ "venture": item.get("venture", ""),
40
+ })
41
+ except json.JSONDecodeError:
42
+ continue
43
+ context["sources"]["completed_work"] = recent_done[-10:]
44
+
45
+ # 2. Open items (what's already tracked)
46
+ open_items = []
47
+ if ledger_path.exists():
48
+ for line in ledger_path.read_text().strip().split("\n"):
49
+ try:
50
+ item = json.loads(line)
51
+ if item.get("status") == "open":
52
+ open_items.append(item.get("title", ""))
53
+ except json.JSONDecodeError:
54
+ continue
55
+ context["sources"]["open_items_count"] = len(open_items)
56
+ context["sources"]["open_item_titles"] = open_items[:20]
57
+
58
+ # 3. Sensing signals (GitHub issues, Reddit, migrations)
59
+ signals_file = Path.home() / ".delimit" / "signals" / "recent.jsonl"
60
+ if signals_file.exists():
61
+ signals = []
62
+ for line in signals_file.read_text().strip().split("\n")[-20:]:
63
+ try:
64
+ sig = json.loads(line)
65
+ signals.append({
66
+ "type": sig.get("type", ""),
67
+ "title": sig.get("title", ""),
68
+ "source": sig.get("source", ""),
69
+ "relevance": sig.get("relevance", 0),
70
+ })
71
+ except json.JSONDecodeError:
72
+ continue
73
+ context["sources"]["signals"] = signals
74
+
75
+ # 4. Git recent activity
76
+ try:
77
+ import subprocess
78
+ result = subprocess.run(
79
+ ["git", "log", "--oneline", "-10"],
80
+ capture_output=True, text=True, timeout=5,
81
+ )
82
+ if result.returncode == 0:
83
+ context["sources"]["recent_commits"] = result.stdout.strip().split("\n")
84
+ except Exception:
85
+ pass
86
+
87
+ # 5. Swarm state
88
+ swarm_registry = Path.home() / ".delimit" / "swarm" / "agent_registry.json"
89
+ if swarm_registry.exists():
90
+ try:
91
+ reg = json.loads(swarm_registry.read_text())
92
+ context["sources"]["swarm_agents"] = len(reg.get("agents", {}))
93
+ except json.JSONDecodeError:
94
+ pass
95
+
96
+ return context
97
+
98
+
99
+ def propose_items(
100
+ venture: str = "",
101
+ focus: str = "",
102
+ max_items: int = 5,
103
+ ) -> Dict[str, Any]:
104
+ """Generate proposed ledger items based on current context.
105
+
106
+ Analyzes completed work, open items, sensing signals, and repo state
107
+ to suggest what to work on next. Returns structured proposals that
108
+ can be added to the ledger with delimit_ledger_add.
109
+
110
+ This is the AI's "what should I do next?" engine. Works with any model.
111
+
112
+ Args:
113
+ venture: Focus proposals on a specific venture.
114
+ focus: Optional focus area (e.g., "outreach", "engineering", "security").
115
+ max_items: Maximum number of proposals to generate.
116
+ """
117
+ context = _gather_context(venture)
118
+
119
+ # Build proposal prompt from context
120
+ proposals = []
121
+ open_titles = set(context["sources"].get("open_item_titles", []))
122
+
123
+ # Strategy 1: Follow-through on completed work
124
+ for done in context["sources"].get("completed_work", []):
125
+ title = done.get("title", "")
126
+ if venture and done.get("venture", "") != venture:
127
+ continue
128
+ # Suggest follow-up actions
129
+ if "deploy" in title.lower() or "publish" in title.lower():
130
+ follow_up = f"Verify deployment: {title}"
131
+ if follow_up not in open_titles:
132
+ proposals.append({
133
+ "title": follow_up,
134
+ "rationale": f"Follow-through: '{title}' was shipped but may need verification",
135
+ "priority": "P1",
136
+ "type": "task",
137
+ "source": "ledger_propose:follow_through",
138
+ })
139
+ if "outreach" in title.lower() or "issue" in title.lower():
140
+ follow_up = f"Monitor engagement: {title}"
141
+ if follow_up not in open_titles:
142
+ proposals.append({
143
+ "title": follow_up,
144
+ "rationale": f"Outreach needs monitoring for responses and engagement",
145
+ "priority": "P1",
146
+ "type": "task",
147
+ "source": "ledger_propose:follow_through",
148
+ })
149
+
150
+ # Strategy 2: Act on unprocessed signals
151
+ for sig in context["sources"].get("signals", []):
152
+ sig_title = sig.get("title", "")
153
+ if sig_title and sig_title not in open_titles:
154
+ proposals.append({
155
+ "title": f"Evaluate signal: {sig_title[:80]}",
156
+ "rationale": f"Unprocessed {sig.get('type', 'signal')} from {sig.get('source', 'unknown')}",
157
+ "priority": "P1",
158
+ "type": "strategy",
159
+ "source": "ledger_propose:signal",
160
+ })
161
+
162
+ # Strategy 3: Detect gaps
163
+ has_tests = any("test" in t.lower() for t in open_titles)
164
+ has_docs = any("doc" in t.lower() or "readme" in t.lower() for t in open_titles)
165
+ has_security = any("security" in t.lower() or "audit" in t.lower() for t in open_titles)
166
+
167
+ if not has_tests and focus != "outreach":
168
+ proposals.append({
169
+ "title": f"Run test coverage analysis{f' for {venture}' if venture else ''}",
170
+ "rationale": "No test-related items in queue — ensure coverage hasn't regressed",
171
+ "priority": "P1",
172
+ "type": "task",
173
+ "source": "ledger_propose:gap_detection",
174
+ })
175
+
176
+ if not has_security and focus != "outreach":
177
+ proposals.append({
178
+ "title": f"Security audit{f' for {venture}' if venture else ''}",
179
+ "rationale": "No security items in queue — periodic audits prevent surprises",
180
+ "priority": "P2",
181
+ "type": "task",
182
+ "source": "ledger_propose:gap_detection",
183
+ })
184
+
185
+ if not has_docs:
186
+ proposals.append({
187
+ "title": f"Documentation freshness check{f' for {venture}' if venture else ''}",
188
+ "rationale": "No doc items in queue — ensure README/CHANGELOG reflect current state",
189
+ "priority": "P2",
190
+ "type": "task",
191
+ "source": "ledger_propose:gap_detection",
192
+ })
193
+
194
+ # Apply focus filter
195
+ if focus:
196
+ focus_lower = focus.lower()
197
+ proposals = [p for p in proposals if focus_lower in p.get("title", "").lower()
198
+ or focus_lower in p.get("rationale", "").lower()
199
+ or focus_lower in p.get("type", "").lower()]
200
+
201
+ # Deduplicate and limit
202
+ seen = set()
203
+ unique = []
204
+ for p in proposals:
205
+ key = p["title"][:50]
206
+ if key not in seen:
207
+ seen.add(key)
208
+ unique.append(p)
209
+ proposals = unique[:max_items]
210
+
211
+ # Save proposals for audit trail
212
+ PROPOSALS_DIR.mkdir(parents=True, exist_ok=True)
213
+ proposal_file = PROPOSALS_DIR / f"proposal_{int(time.time())}.json"
214
+ proposal_file.write_text(json.dumps({
215
+ "proposals": proposals,
216
+ "context_summary": {
217
+ "completed_work": len(context["sources"].get("completed_work", [])),
218
+ "open_items": context["sources"].get("open_items_count", 0),
219
+ "signals": len(context["sources"].get("signals", [])),
220
+ "swarm_agents": context["sources"].get("swarm_agents", 0),
221
+ },
222
+ "venture": venture,
223
+ "focus": focus,
224
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
225
+ }, indent=2))
226
+
227
+ return {
228
+ "status": "ok",
229
+ "proposals": proposals,
230
+ "total": len(proposals),
231
+ "venture": venture or "all",
232
+ "focus": focus or "none",
233
+ "context": {
234
+ "completed_work_analyzed": len(context["sources"].get("completed_work", [])),
235
+ "open_items": context["sources"].get("open_items_count", 0),
236
+ "signals_analyzed": len(context["sources"].get("signals", [])),
237
+ },
238
+ "message": f"Generated {len(proposals)} proposal(s). "
239
+ "Use delimit_ledger_add to add approved items.",
240
+ }