-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmnemo_arc.py
More file actions
458 lines (362 loc) · 13.4 KB
/
mnemo_arc.py
File metadata and controls
458 lines (362 loc) · 13.4 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
"""
mnemo_arc — work arcs for multi-session momentum tracking
A work arc is a named, evolving goal that spans multiple sessions.
It tracks trajectory (what happened each session), direction (where
we're heading), and completion state.
Arc nodes live in the tree like everything else — content-addressed,
supersedable, compressible. No new data structures. Arcs are a
convention on top of the existing node model.
Entry points:
create_arc() — start a new arc
update_arc() — append a trajectory line (manual or auto)
complete_arc() — mark arc as done
pause_arc() — pause without completing
find_active_arcs() — list active/paused arcs
match_session_to_arcs() — find arcs that overlap with session work
detect_arc_candidates() — scan handoff chain for potential arcs
"""
import re
import time
from mnemo import Store, Node, supersede
# ===================================================================
# Arc CRUD
# ===================================================================
def create_arc(
store: Store,
name: str,
goal: str,
domains: list[str] = None,
keywords: list[str] = None,
) -> str:
"""
Create a new work arc.
Returns the arc node address.
"""
# Auto-extract keywords from goal if not provided
if not keywords:
keywords = _extract_keywords(goal)
content = (
f"Arc: {name} (0 sessions, active)\n"
f"\n"
f"Goal: {goal}\n"
f"\n"
f"Trajectory:\n"
f" (no sessions yet)\n"
f"\n"
f"Next: begin work"
)
node = Node(
type="leaf",
content=content,
meta={
"domain": "tasks",
"confidence": 0.9,
"source": "conscious",
"arc": True,
"arc_name": name,
"arc_status": "active",
"arc_sessions": 0,
"arc_domains": domains or [],
"arc_keywords": keywords,
"priority": 0.5,
},
)
store.put(node)
active = store.get_active()
active.add(node.addr)
store.set_active(active)
return node.addr
def update_arc(
store: Store,
arc_addr: str,
progress: str,
next_step: str = "",
domains_touched: list[str] = None,
) -> str | None:
"""
Append a trajectory line to an active arc. Supersedes the old arc node.
Returns the new arc address, or None if arc not found.
"""
old = store.get(arc_addr)
if not old or not old.meta.get("arc"):
return None
sessions = old.meta.get("arc_sessions", 0) + 1
name = old.meta.get("arc_name", "unnamed")
status = old.meta.get("arc_status", "active")
# Parse existing content to extract goal and trajectory
goal, trajectory = _parse_arc_content(old.content)
# Add new trajectory line
age_label = _age_label(time.time())
trajectory.append(f"Session {sessions} ({age_label}): {progress}")
# Update keywords with new domains
arc_keywords = old.meta.get("arc_keywords", [])
new_words = _extract_keywords(progress)
merged = list(set(arc_keywords + new_words))
arc_domains = old.meta.get("arc_domains", [])
if domains_touched:
arc_domains = list(set(arc_domains + domains_touched))
# Build updated content
next_line = next_step or _extract_next(old.content) or "continue work"
content = _build_arc_content(name, sessions, status, goal, trajectory, next_line)
# Supersede
new_meta = dict(old.meta)
new_meta.update({
"arc_sessions": sessions,
"arc_domains": arc_domains,
"arc_keywords": merged,
})
new_addr = supersede(old.addr, content, store,
reason=f"arc progress: {progress[:60]}")
# Update meta on the new node
new_node = store.get(new_addr)
if new_node:
new_node.meta.update(new_meta)
store.put(new_node)
return new_addr
def complete_arc(
store: Store,
arc_addr: str,
outcome: str = "",
) -> str | None:
"""
Mark an arc as completed. Supersedes with final status.
Returns the new arc address, or None if not found.
"""
old = store.get(arc_addr)
if not old or not old.meta.get("arc"):
return None
sessions = old.meta.get("arc_sessions", 0)
name = old.meta.get("arc_name", "unnamed")
goal, trajectory = _parse_arc_content(old.content)
if outcome:
trajectory.append(f"Completed: {outcome}")
content = _build_arc_content(name, sessions, "completed", goal, trajectory,
next_line=None)
new_addr = supersede(old.addr, content, store,
reason=f"arc completed: {outcome[:60]}")
new_node = store.get(new_addr)
if new_node:
new_node.meta["arc_status"] = "completed"
new_node.meta["priority"] = 0 # stop boosting in recall
store.put(new_node)
return new_addr
def pause_arc(
store: Store,
arc_addr: str,
reason: str = "",
) -> str | None:
"""
Pause an arc without completing it. Can be resumed later.
Returns the new arc address, or None if not found.
"""
old = store.get(arc_addr)
if not old or not old.meta.get("arc"):
return None
sessions = old.meta.get("arc_sessions", 0)
name = old.meta.get("arc_name", "unnamed")
goal, trajectory = _parse_arc_content(old.content)
if reason:
trajectory.append(f"Paused: {reason}")
content = _build_arc_content(name, sessions, "paused", goal, trajectory,
next_line=f"resume: {reason}" if reason else "resume")
new_addr = supersede(old.addr, content, store,
reason=f"arc paused: {reason[:60]}")
new_node = store.get(new_addr)
if new_node:
new_node.meta["arc_status"] = "paused"
store.put(new_node)
return new_addr
# ===================================================================
# Arc queries
# ===================================================================
def find_active_arcs(store: Store) -> list[Node]:
"""Find all active and paused arc nodes."""
active = store.get_active()
arcs = []
for addr in active:
node = store.get(addr)
if not node:
continue
if node.meta.get("arc") and node.meta.get("arc_status") in ("active", "paused"):
arcs.append(node)
# Most recently modified first
arcs.sort(key=lambda n: n.created, reverse=True)
return arcs
def match_session_to_arcs(
store: Store,
domains_touched: list[str],
work_keywords: list[str],
) -> list[tuple[Node, float]]:
"""
Find active arcs that overlap with session work.
Returns list of (arc_node, overlap_score) sorted by score descending.
Only includes arcs above 0.2 overlap threshold.
"""
arcs = find_active_arcs(store)
if not arcs:
return []
work_set = set(w.lower() for w in work_keywords)
domain_set = set(d.lower() for d in domains_touched)
matches = []
for arc in arcs:
arc_keywords = set(k.lower() for k in arc.meta.get("arc_keywords", []))
arc_domains = set(d.lower() for d in arc.meta.get("arc_domains", []))
# Keyword overlap (Jaccard)
kw_union = arc_keywords | work_set
kw_inter = arc_keywords & work_set
kw_score = len(kw_inter) / len(kw_union) if kw_union else 0
# Domain overlap (Jaccard)
dm_union = arc_domains | domain_set
dm_inter = arc_domains & domain_set
dm_score = len(dm_inter) / len(dm_union) if dm_union else 0
# Combined: keywords matter more than domains
score = 0.7 * kw_score + 0.3 * dm_score
if score >= 0.2:
matches.append((arc, score))
matches.sort(key=lambda x: x[1], reverse=True)
return matches
def detect_arc_candidates(store: Store) -> list[dict]:
"""
Scan the handoff chain for thematic overlap across sessions.
Proposes arcs when 2+ sequential handoffs share significant overlap.
Returns list of candidate dicts with: name, goal, evidence, domains.
"""
active = store.get_active()
# Collect handoff nodes sorted by creation time
handoffs = []
for addr in active:
node = store.get(addr)
if not node:
continue
if node.meta.get("handoff"):
handoffs.append(node)
handoffs.sort(key=lambda n: n.created)
if len(handoffs) < 2:
return []
# Check which handoffs aren't already covered by an active arc
existing_arcs = find_active_arcs(store)
candidates = []
# Sliding window: compare adjacent handoffs
for i in range(len(handoffs) - 1):
h1 = handoffs[i]
h2 = handoffs[i + 1]
kw1 = set(_extract_keywords(h1.content))
kw2 = set(_extract_keywords(h2.content))
overlap = kw1 & kw2
union = kw1 | kw2
if not union:
continue
score = len(overlap) / len(union)
if score < 0.2:
continue
# Check if this theme is already covered by an existing arc
already_covered = False
for arc in existing_arcs:
arc_kw = set(k.lower() for k in arc.meta.get("arc_keywords", []))
if len(overlap & arc_kw) > len(overlap) * 0.5:
already_covered = True
break
if already_covered:
continue
# Extract domains from handoffs
domains1 = set(h1.meta.get("domains_touched", []))
domains2 = set(h2.meta.get("domains_touched", []))
shared_domains = sorted(domains1 & domains2) or sorted(domains1 | domains2)
# Propose arc name from the overlapping keywords
theme_words = sorted(overlap, key=len, reverse=True)[:3]
proposed_name = " ".join(theme_words) if theme_words else "unnamed theme"
candidates.append({
"name": proposed_name,
"goal": f"Recurring theme across sessions: {', '.join(sorted(overlap)[:6])}",
"evidence": [h1.addr[:8], h2.addr[:8]],
"domains": shared_domains,
"overlap_score": score,
"keywords": sorted(overlap),
})
return candidates
# ===================================================================
# Internal helpers
# ===================================================================
_STOP_WORDS = frozenset({
"the", "a", "an", "is", "are", "was", "were", "be", "been", "being",
"have", "has", "had", "do", "does", "did", "will", "would", "shall",
"should", "may", "might", "must", "can", "could", "to", "of", "in",
"for", "on", "with", "at", "by", "from", "as", "into", "through",
"during", "before", "after", "above", "below", "between", "and",
"but", "or", "nor", "not", "no", "so", "if", "then", "than", "too",
"very", "just", "about", "up", "out", "off", "over", "under", "again",
"further", "once", "here", "there", "when", "where", "why", "how",
"all", "each", "every", "both", "few", "more", "most", "other",
"some", "such", "only", "own", "same", "that", "this", "what", "which",
"who", "whom", "it", "its", "we", "they", "them", "their", "our",
"your", "my", "his", "her", "she", "he", "you", "i", "me", "us",
"session", "handoff", "turns", "nodes", "worked", "active", "tasks",
"domains", "touched", "corrections", "made",
})
def _extract_keywords(text: str) -> list[str]:
"""Extract meaningful keywords from text, filtering stop words."""
words = re.findall(r'[a-z_][a-z0-9_]*', text.lower())
return list(set(
w for w in words
if w not in _STOP_WORDS and len(w) > 2
))
def _parse_arc_content(content: str) -> tuple[str, list[str]]:
"""Parse arc content into (goal, trajectory_lines)."""
goal = ""
trajectory = []
in_trajectory = False
for line in content.split("\n"):
stripped = line.strip()
if stripped.startswith("Goal:"):
goal = stripped[5:].strip()
elif stripped == "Trajectory:":
in_trajectory = True
elif stripped.startswith("Next:") or stripped.startswith("Blockers:"):
in_trajectory = False
elif in_trajectory and stripped and stripped != "(no sessions yet)":
trajectory.append(stripped)
return goal, trajectory
def _extract_next(content: str) -> str:
"""Extract the Next: line from arc content."""
for line in content.split("\n"):
stripped = line.strip()
if stripped.startswith("Next:"):
return stripped[5:].strip()
return ""
def _build_arc_content(
name: str,
sessions: int,
status: str,
goal: str,
trajectory: list[str],
next_line: str | None,
) -> str:
"""Build formatted arc content."""
lines = [
f"Arc: {name} ({sessions} session{'s' if sessions != 1 else ''}, {status})",
"",
f"Goal: {goal}",
"",
"Trajectory:",
]
if trajectory:
for t in trajectory:
# Ensure indentation
if not t.startswith(" "):
t = f" {t}"
lines.append(t)
else:
lines.append(" (no sessions yet)")
if next_line:
lines.append("")
lines.append(f"Next: {next_line}")
return "\n".join(lines)
def _age_label(ts: float) -> str:
"""Human-readable age label like 'today', '1d ago', '3d ago'."""
age_days = int((time.time() - ts) / 86400)
if age_days == 0:
return "today"
elif age_days == 1:
return "1d ago"
else:
return f"{age_days}d ago"