-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·251 lines (202 loc) · 8.75 KB
/
cli.py
File metadata and controls
executable file
·251 lines (202 loc) · 8.75 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
#!/usr/bin/env python3
"""
Decision Logger CLI - Shell interface for the decision logger.
Makes decision tracking accessible from bash, cron, subagents, anywhere.
Usage:
python3 cli.py log --category "tool-selection" --options "search,fetch,cache" \
--chosen "search" --context "needed real-time data" --rationale "stale cache" \
--confidence HIGH --tags "tools,data"
python3 cli.py outcome --id abc123def456 --result "worked perfectly" --score 0.9
python3 cli.py query --category "response-style" --days 7
python3 cli.py analyze --days 30
python3 cli.py summary --days 7
python3 cli.py export --days 30 --format json
python3 cli.py stats
"""
import argparse
import json
import sys
from pathlib import Path
# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from decision_logger import DecisionLogger, PatternAnalyzer
def cmd_log(args):
logger = DecisionLogger(agent_id=args.agent)
options = [o.strip() for o in args.options.split(",")]
tags = [t.strip() for t in args.tags.split(",")] if args.tags else []
metadata = {}
if args.meta:
for kv in args.meta:
k, v = kv.split("=", 1)
metadata[k] = v
decision_id = logger.log(
category=args.category,
options=options,
chosen=args.chosen,
context=args.context,
rationale=args.rationale,
confidence=args.confidence,
tags=tags,
metadata=metadata,
)
if args.json:
print(json.dumps({"decision_id": decision_id, "status": "logged"}))
else:
print(f"Logged: {decision_id}")
return decision_id
def cmd_outcome(args):
logger = DecisionLogger(agent_id=args.agent)
found = logger.record_outcome(
decision_id=args.id,
outcome=args.result,
score=args.score,
search_days=args.search_days,
)
if args.json:
print(json.dumps({"decision_id": args.id, "found": found}))
else:
if found:
print(f"Outcome recorded for {args.id}")
else:
print(f"Decision {args.id} not found in last {args.search_days} days")
sys.exit(1)
def cmd_query(args):
logger = DecisionLogger(agent_id=args.agent)
tags = [t.strip() for t in args.tags.split(",")] if args.tags else None
has_outcome = None
if args.pending:
has_outcome = False
elif args.completed:
has_outcome = True
results = logger.query(
category=args.category,
tags=tags,
confidence=args.confidence,
has_outcome=has_outcome,
days=args.days,
)
if args.json:
print(json.dumps([d.to_dict() for d in results], indent=2))
else:
if not results:
print("No decisions match criteria.")
return
for d in results:
outcome_str = f" -> {d.outcome}" if d.outcome else " [pending]"
score_str = f" ({d.outcome_score:+.1f})" if d.outcome_score is not None else ""
print(f"[{d.confidence}] {d.decision_id} | {d.category} | chose '{d.chosen}' | {d.rationale[:60]}{outcome_str}{score_str}")
def cmd_analyze(args):
logger = DecisionLogger(agent_id=args.agent)
analyzer = PatternAnalyzer(logger)
report = analyzer.analyze(days=args.days)
if args.json:
print(json.dumps(report, indent=2))
else:
print(json.dumps(report, indent=2))
def cmd_summary(args):
logger = DecisionLogger(agent_id=args.agent)
analyzer = PatternAnalyzer(logger)
print(analyzer.summary(days=args.days))
def cmd_stats(args):
logger = DecisionLogger(agent_id=args.agent)
decisions = logger.get_all_decisions(days=args.days)
total = len(decisions)
with_outcome = sum(1 for d in decisions if d.outcome)
scored = [d for d in decisions if d.outcome_score is not None]
avg_score = sum(d.outcome_score for d in scored) / len(scored) if scored else 0
categories = set(d.category for d in decisions)
stats = {
"total_decisions": total,
"with_outcomes": with_outcome,
"pending_outcomes": total - with_outcome,
"avg_score": round(avg_score, 3) if scored else None,
"unique_categories": len(categories),
"categories": list(categories),
"days_searched": args.days,
}
if args.json:
print(json.dumps(stats, indent=2))
else:
print(f"Decisions: {total} ({with_outcome} with outcomes, {total - with_outcome} pending)")
if scored:
print(f"Avg score: {avg_score:+.3f}")
print(f"Categories: {', '.join(sorted(categories)) if categories else 'none'}")
def cmd_export(args):
logger = DecisionLogger(agent_id=args.agent)
decisions = logger.get_all_decisions(days=args.days)
if args.format == "json":
print(json.dumps([d.to_dict() for d in decisions], indent=2))
elif args.format == "csv":
print("timestamp,decision_id,category,chosen,confidence,rationale,outcome,score")
for d in decisions:
rat = d.rationale.replace('"', '""')[:80]
out = (d.outcome or "").replace('"', '""')[:80]
score = str(d.outcome_score) if d.outcome_score is not None else ""
print(f'"{d.timestamp}","{d.decision_id}","{d.category}","{d.chosen}","{d.confidence}","{rat}","{out}",{score}')
elif args.format == "markdown":
print(f"# Decision Log Export ({args.days} days)\n")
print(f"Total: {len(decisions)} decisions\n")
for d in decisions:
status = f"Outcome: {d.outcome}" if d.outcome else "Pending"
score = f" (score: {d.outcome_score:+.1f})" if d.outcome_score is not None else ""
print(f"## [{d.confidence}] {d.category} - {d.decision_id}")
print(f"- **Chosen:** {d.chosen} from {d.options}")
print(f"- **Context:** {d.context}")
print(f"- **Rationale:** {d.rationale}")
print(f"- **Status:** {status}{score}")
if d.tags:
print(f"- **Tags:** {', '.join(d.tags)}")
print()
def main():
parser = argparse.ArgumentParser(description="Decision Logger CLI")
parser.add_argument("--agent", default="nix", help="Agent ID (default: nix)")
parser.add_argument("--json", action="store_true", help="JSON output")
sub = parser.add_subparsers(dest="command", required=True)
# log
p_log = sub.add_parser("log", help="Log a new decision")
p_log.add_argument("--category", "-c", required=True)
p_log.add_argument("--options", "-o", required=True, help="Comma-separated options")
p_log.add_argument("--chosen", required=True)
p_log.add_argument("--context", required=True)
p_log.add_argument("--rationale", "-r", required=True)
p_log.add_argument("--confidence", default="MEDIUM", choices=["HIGH", "MEDIUM", "LOW"])
p_log.add_argument("--tags", "-t", default="", help="Comma-separated tags")
p_log.add_argument("--meta", nargs="*", help="key=value metadata pairs")
p_log.set_defaults(func=cmd_log)
# outcome
p_out = sub.add_parser("outcome", help="Record outcome for a decision")
p_out.add_argument("--id", required=True, help="Decision ID")
p_out.add_argument("--result", required=True, help="What happened")
p_out.add_argument("--score", type=float, help="Score -1.0 to 1.0")
p_out.add_argument("--search-days", type=int, default=30)
p_out.set_defaults(func=cmd_outcome)
# query
p_query = sub.add_parser("query", help="Query decisions")
p_query.add_argument("--category", "-c")
p_query.add_argument("--tags", "-t")
p_query.add_argument("--confidence")
p_query.add_argument("--pending", action="store_true", help="Only pending outcomes")
p_query.add_argument("--completed", action="store_true", help="Only with outcomes")
p_query.add_argument("--days", type=int, default=30)
p_query.set_defaults(func=cmd_query)
# analyze
p_analyze = sub.add_parser("analyze", help="Full pattern analysis")
p_analyze.add_argument("--days", type=int, default=30)
p_analyze.set_defaults(func=cmd_analyze)
# summary
p_summary = sub.add_parser("summary", help="Human-readable summary")
p_summary.add_argument("--days", type=int, default=30)
p_summary.set_defaults(func=cmd_summary)
# stats
p_stats = sub.add_parser("stats", help="Quick stats")
p_stats.add_argument("--days", type=int, default=30)
p_stats.set_defaults(func=cmd_stats)
# export
p_export = sub.add_parser("export", help="Export decisions")
p_export.add_argument("--days", type=int, default=30)
p_export.add_argument("--format", choices=["json", "csv", "markdown"], default="json")
p_export.set_defaults(func=cmd_export)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()