-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcli.py
More file actions
357 lines (295 loc) · 11.9 KB
/
Copy pathcli.py
File metadata and controls
357 lines (295 loc) · 11.9 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
#!/usr/bin/env python3
"""
Interactive CLI for Context Graph Prototype
Allows users to:
- Search for precedent
- Record new decisions
- View entity history
- Explore the graph
"""
import cmd
from models import Entity, EntityType, DecisionTrace, DecisionType
from graph import ContextGraph
from search import PrecedentSearch
from workflow import WorkflowEngine, WorkflowRequest
from example import create_sample_entities, create_historical_decisions
class ContextGraphCLI(cmd.Cmd):
intro = """
╔═══════════════════════════════════════════════════════════════════════════╗
║ CONTEXT GRAPH PROTOTYPE ║
║ ║
║ "A living record of decision traces stitched across entities and time ║
║ so precedent becomes searchable." ║
╚═══════════════════════════════════════════════════════════════════════════╝
Type 'help' for available commands. Type 'demo' to load sample data.
"""
prompt = "context-graph> "
def __init__(self):
super().__init__()
self.graph = ContextGraph()
self.search = PrecedentSearch(self.graph)
self.workflow = WorkflowEngine(self.graph)
self._demo_loaded = False
def do_demo(self, arg):
"""Load demo data with sample entities and decisions."""
if self._demo_loaded:
print("Demo data already loaded.")
return
print("Loading demo data...")
create_sample_entities(self.graph)
create_historical_decisions(self.graph)
self._demo_loaded = True
stats = self.graph.stats()
print(f"Loaded {stats['total_entities']} entities and {stats['total_decisions']} decisions.")
print("Try: search discount enterprise")
def do_stats(self, arg):
"""Show graph statistics."""
stats = self.graph.stats()
print("\nGraph Statistics:")
print(f" Total Entities: {stats['total_entities']}")
print(f" Total Decisions: {stats['total_decisions']}")
print(f" Unique Tags: {stats['unique_tags']}")
print("\n Decisions by Type:")
for dtype, count in stats['decisions_by_type'].items():
print(f" {dtype}: {count}")
print()
def do_search(self, arg):
"""
Search for precedent decisions.
Usage: search <query>
Example: search discount enterprise
"""
if not arg:
print("Usage: search <query>")
return
results = self.search.search(query=arg, limit=5)
if not results:
print("No matching decisions found.")
return
print(f"\nFound {len(results)} matching decisions:\n")
for i, result in enumerate(results, 1):
print(f"{i}. [Score: {result.score:.1f}] {result.decision.description}")
print(f" Outcome: {result.decision.outcome}")
print(f" Type: {result.decision.type.value}")
print(f" Actor: {result.decision.actor_name}")
print(f" Date: {result.decision.timestamp.strftime('%Y-%m-%d %H:%M')}")
print(f" Matches: {', '.join(result.match_reasons)}")
print()
def do_tags(self, arg):
"""
Search by tags.
Usage: tags <tag1> [tag2] ...
Example: tags discount enterprise
"""
if not arg:
print("Usage: tags <tag1> [tag2] ...")
return
tags = arg.split()
results = self.search.search(tags=tags, limit=5)
if not results:
print(f"No decisions found with tags: {tags}")
return
print(f"\nDecisions with tags {tags}:\n")
for result in results:
print(f" - {result.decision.description}")
print(f" Outcome: {result.decision.outcome}")
print(f" Tags: {', '.join(result.decision.tags)}")
print()
def do_exceptions(self, arg):
"""List all exception decisions."""
results = self.search.search(decision_type=DecisionType.EXCEPTION, limit=10)
if not results:
print("No exceptions found.")
return
print("\nException Decisions:\n")
for result in results:
d = result.decision
print(f" [{d.timestamp.strftime('%Y-%m-%d')}] {d.description}")
print(f" Outcome: {d.outcome}")
if d.attributes.get('exception_reason'):
print(f" Reason: {d.attributes['exception_reason']}")
print()
def do_history(self, arg):
"""
View decision history for an entity.
Usage: history <entity_id>
Example: history CUST-001
"""
if not arg:
print("Usage: history <entity_id>")
return
entity = self.graph.get_entity(arg.strip())
if entity:
print(f"\nEntity: {entity.name} ({entity.type.value})")
print(f"Attributes: {entity.attributes}")
else:
print(f"\nEntity {arg} not found in graph (showing decisions anyway)")
history = self.graph.get_entity_history(arg.strip())
if not history:
print("No decisions found for this entity.")
return
print(f"\nDecision History ({len(history)} decisions):\n")
for d in history:
print(f" [{d.timestamp.strftime('%Y-%m-%d %H:%M')}] {d.type.value.upper()}")
print(f" {d.description}")
print(f" Outcome: {d.outcome}")
if d.approvals:
print(f" Approved by: {', '.join(a.approver_name for a in d.approvals)}")
print()
def do_entities(self, arg):
"""List all entities in the graph."""
entities = self.graph.list_entities()
if not entities:
print("No entities in graph. Try 'demo' first.")
return
print("\nEntities:\n")
by_type = {}
for e in entities:
by_type.setdefault(e.type.value, []).append(e)
for etype, elist in sorted(by_type.items()):
print(f" {etype.upper()}:")
for e in elist:
print(f" {e.id}: {e.name}")
print()
def do_suggest(self, arg):
"""
Get a suggestion for a new decision based on precedent.
Usage: suggest <description>
Example: suggest 20% discount for enterprise customer
"""
if not arg:
print("Usage: suggest <description>")
return
# Extract potential tags from description
words = arg.lower().split()
potential_tags = [w for w in words if len(w) > 3]
suggestion = self.search.suggest_decision(
description=arg,
entity_ids=[],
tags=potential_tags
)
if not suggestion:
print("\nNo strong precedent found for this decision.")
print("This would require human review.")
return
print("\nSuggestion based on precedent:")
print(f" Recommended outcome: {suggestion['suggested_outcome']}")
print(f" Confidence: {suggestion['confidence']:.0%}")
print(f" Based on: {suggestion['based_on']} similar decisions")
print("\n Supporting precedent:")
for p in suggestion['top_precedent']:
print(f" - {p['description']}")
print(f" Outcome: {p['outcome']}")
print()
def do_record(self, arg):
"""
Record a new decision interactively.
Usage: record
"""
print("\n--- Record New Decision ---\n")
description = input("Description: ").strip()
if not description:
print("Cancelled.")
return
outcome = input("Outcome: ").strip()
if not outcome:
print("Cancelled.")
return
dtype_str = input("Type (approval/exception/override) [approval]: ").strip().lower()
dtype_map = {
'approval': DecisionType.APPROVAL,
'exception': DecisionType.EXCEPTION,
'override': DecisionType.OVERRIDE,
'': DecisionType.APPROVAL
}
dtype = dtype_map.get(dtype_str, DecisionType.APPROVAL)
actor_name = input("Your name: ").strip() or "Anonymous"
tags_str = input("Tags (comma-separated): ").strip()
tags = [t.strip() for t in tags_str.split(',') if t.strip()]
entity_ids_str = input("Entity IDs (comma-separated, optional): ").strip()
entity_ids = [e.strip() for e in entity_ids_str.split(',') if e.strip()]
decision = DecisionTrace(
type=dtype,
description=description,
outcome=outcome,
actor_id=f"user-{actor_name.lower().replace(' ', '-')}",
actor_name=actor_name,
entity_ids=entity_ids,
tags=tags
)
self.graph.record_decision(decision)
print(f"\nDecision recorded: {decision.id[:8]}...")
print("This decision is now searchable as precedent.")
def do_replay(self, arg):
"""
Replay the context of a historical decision.
Usage: replay <decision_id>
"""
if not arg:
# Show recent decisions to choose from
decisions = self.graph.get_recent_decisions(limit=5)
if not decisions:
print("No decisions in graph.")
return
print("\nRecent decisions:")
for d in decisions:
print(f" {d.id[:8]}: {d.description[:50]}...")
print("\nUsage: replay <decision_id>")
return
# Find decision by partial ID
matches = self.graph.find_decision_ids_by_prefix(arg)
if len(matches) > 1:
print(f"Multiple decisions match '{arg}':")
for did in matches[:10]:
d = self.graph.get_decision(did)
if d:
print(f" {did[:8]}: {d.description[:60]}...")
print("Please provide a longer prefix.")
return
decision_id = matches[0] if matches else None
if not decision_id:
print(f"Decision not found: {arg}")
return
replay = self.graph.replay_context(decision_id)
d = replay['decision']
print(f"\n--- Decision Replay ---")
print(f"ID: {d.id}")
print(f"Type: {d.type.value}")
print(f"Description: {d.description}")
print(f"Outcome: {d.outcome}")
print(f"Actor: {d.actor_name}")
print(f"Time: {d.timestamp.isoformat()}")
if replay['contexts']:
print("\nContext at decision time:")
for system, data in replay['contexts'].items():
print(f" [{system}] {data}")
if replay['approval_chain']:
print("\nApproval chain:")
for a in replay['approval_chain']:
print(f" - {a.approver_name} via {a.channel}")
if a.reason:
print(f" Reason: {a.reason}")
if d.tags:
print(f"\nTags: {', '.join(d.tags)}")
print()
def do_export(self, arg):
"""Export the graph to JSON."""
filename = arg.strip() or "context_graph_export.json"
json_data = self.graph.export_to_json()
with open(filename, 'w') as f:
f.write(json_data)
print(f"Graph exported to {filename}")
def do_quit(self, arg):
"""Exit the CLI."""
print("Goodbye!")
return True
def do_exit(self, arg):
"""Exit the CLI."""
return self.do_quit(arg)
# Shortcuts
do_q = do_quit
def main():
cli = ContextGraphCLI()
cli.cmdloop()
if __name__ == "__main__":
main()