loki-mode 7.75.0 → 7.77.0

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.
package/mcp/__init__.py CHANGED
@@ -57,4 +57,4 @@ try:
57
57
  except ImportError:
58
58
  __all__ = ['mcp']
59
59
 
60
- __version__ = '7.75.0'
60
+ __version__ = '7.77.0'
@@ -157,10 +157,15 @@ class ConsolidationPipeline:
157
157
  if lock_file is not None:
158
158
  fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
159
159
  lock_file.close()
160
- try:
161
- lock_path.unlink()
162
- except OSError:
163
- pass
160
+ # Do NOT unlink the lock inode here. Unlinking on release is a
161
+ # flock+unlink inode-replacement race: waiter B blocked on
162
+ # inode-1 acquires it after holder A unlinks inode-1, then a
163
+ # third consolidation C opens the path, finds it gone, creates
164
+ # inode-2 and flocks inode-2 -- entering _consolidate_locked
165
+ # while B is still inside, breaking the BUG-MEM-003
166
+ # single-consolidation guarantee. Same class fixed in
167
+ # storage._file_lock. Persistent lock files are the standard
168
+ # flock pattern; the file is reused across runs.
164
169
 
165
170
  def _consolidate_locked(self, since_hours: int) -> ConsolidationResult:
166
171
  """Run the consolidation pipeline under an exclusive lock."""
@@ -226,9 +231,9 @@ class ConsolidationPipeline:
226
231
  # Re-read the target pattern fresh immediately before
227
232
  # merging (BUG-MEM C1, lost-update). The whole-run
228
233
  # snapshot at step 4 can be stale by now: a concurrent
229
- # engine.increment_pattern_usage() (load_pattern then
230
- # save_pattern) may have bumped usage_count/last_used
231
- # AFTER the snapshot. merge_with_existing() builds the
234
+ # storage.increment_pattern_usage() (atomic read-mutate-
235
+ # write under one exclusive lock) may have bumped
236
+ # usage_count/last_used AFTER the snapshot. merge_with_existing() builds the
232
237
  # merged record from best_match.usage_count/last_used,
233
238
  # so merging from the stale snapshot clobbers that bump.
234
239
  # Re-reading narrows the window to this single write.
package/memory/engine.py CHANGED
@@ -7,6 +7,7 @@ from __future__ import annotations
7
7
  import json
8
8
  import logging
9
9
  import os
10
+ import re
10
11
  from datetime import datetime, timedelta, timezone
11
12
  from pathlib import Path
12
13
  from typing import Any, Callable, Dict, List, Optional, Union
@@ -304,6 +305,13 @@ class MemoryEngine:
304
305
  else:
305
306
  date_str = timestamp.strftime("%Y-%m-%d")
306
307
 
308
+ # Reject a junk date directory derived from a poisoned/round-tripped
309
+ # timestamp (mirrors storage.save_episode). Traversal is already
310
+ # contained by _resolve_path; this just stops non-date dirs being
311
+ # created. Only an exact YYYY-MM-DD string is allowed.
312
+ if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str):
313
+ date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
314
+
307
315
  episode_id = trace_dict.get("id", f"ep-{date_str}-{self._generate_id()}")
308
316
  trace_dict["id"] = episode_id
309
317
 
@@ -580,21 +588,13 @@ class MemoryEngine:
580
588
  Args:
581
589
  pattern_id: Pattern identifier
582
590
  """
583
- # Load pattern via storage (which acquires read lock)
584
- pattern_data = self.storage.load_pattern(pattern_id)
585
- if pattern_data is None:
586
- return
587
-
588
- # Update fields. `or 0` guards against an explicit null usage_count
589
- # (corrupt/hand-edited record) crashing the increment with a TypeError;
590
- # a null and 0 are equivalent here so `or` is safe.
591
- pattern_data["usage_count"] = (pattern_data.get("usage_count") or 0) + 1
592
- pattern_data["last_used"] = datetime.now(timezone.utc).isoformat()
593
-
594
- # Write back via save_pattern which holds an exclusive lock during
595
- # the full read-modify-write (upsert) cycle
596
- pattern_obj = self._dict_to_pattern(pattern_data)
597
- self.storage.save_pattern(pattern_obj)
591
+ # Delegate the entire read-modify-write to storage, which performs it
592
+ # under a single exclusive lock. Doing the read here (load_pattern's
593
+ # shared lock is released immediately) and writing a detached snapshot
594
+ # back via save_pattern (wholesale entry replacement) loses updates
595
+ # when two agents increment concurrently. A no-op if the pattern is
596
+ # missing.
597
+ self.storage.increment_pattern_usage(pattern_id)
598
598
 
599
599
  # -------------------------------------------------------------------------
600
600
  # Skill Operations
package/memory/ingest.py CHANGED
@@ -26,6 +26,7 @@ Safety:
26
26
  """
27
27
  from __future__ import annotations
28
28
 
29
+ import hashlib
29
30
  import json
30
31
  import os
31
32
  import re
@@ -165,6 +166,52 @@ def _log_to_errors(memory_base: str, function_name: str, exc: BaseException) ->
165
166
  return
166
167
 
167
168
 
169
+ def _deterministic_episode_id(stable_key: str) -> str:
170
+ """Derive a stable, idempotent episode id from a stable key.
171
+
172
+ Re-ingesting the same session/summary must NOT create a new episode.
173
+ EpisodeTrace.create() mints a random uuid every call, so without a
174
+ deterministic id the index dedup (which keys on episode_id) counts
175
+ the same session twice, inflating episode_count / total_cost_usd /
176
+ total_tokens. Deriving the id from the stable key (e.g. the session
177
+ or task id) makes re-ingest land on the same filename + the same
178
+ index dedup bucket. Date is intentionally omitted so the id does not
179
+ drift across day boundaries for the same source.
180
+ """
181
+ digest = hashlib.sha1(stable_key.encode("utf-8")).hexdigest()[:12]
182
+ return f"ep-{digest}"
183
+
184
+
185
+ def _existing_episode_path(
186
+ storage: Any, memory_base: str, episode_id: str
187
+ ) -> Optional[str]:
188
+ """Return the on-disk path for an already-stored episode id, or None.
189
+
190
+ Used for the idempotency existence check before writing so a repeat
191
+ ingest of the same source is a no-op rather than an append-new.
192
+ """
193
+ try:
194
+ existing = storage.load_episode(episode_id)
195
+ except Exception:
196
+ return None
197
+ if not existing:
198
+ return None
199
+ # Mirror storage.save_episode's path layout; prefer the stored
200
+ # timestamp date, fall back to a directory scan if absent.
201
+ ts = existing.get("timestamp")
202
+ if isinstance(ts, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", ts[:10] or ""):
203
+ candidate = Path(memory_base) / "episodic" / ts[:10] / f"task-{episode_id}.json"
204
+ if candidate.is_file():
205
+ return str(candidate)
206
+ episodic_dir = Path(memory_base) / "episodic"
207
+ if episodic_dir.is_dir():
208
+ for date_dir in episodic_dir.iterdir():
209
+ candidate = date_dir / f"task-{episode_id}.json"
210
+ if candidate.is_file():
211
+ return str(candidate)
212
+ return None
213
+
214
+
168
215
  def _parse_transcript_line(line: str) -> Optional[Dict[str, Any]]:
169
216
  """Parse one JSONL line; return None on parse error."""
170
217
  try:
@@ -385,12 +432,21 @@ def ingest_from_claude_transcript(
385
432
  engine = MemoryEngine(storage=storage, base_path=memory_base)
386
433
  engine.initialize()
387
434
 
435
+ # The transcript task_id is always stable (sessionId or filename
436
+ # stem), so derive a deterministic episode id from it and skip the
437
+ # write if this session was already ingested (idempotent re-run).
438
+ episode_id = _deterministic_episode_id(task_id)
439
+ already = _existing_episode_path(storage, memory_base, episode_id)
440
+ if already is not None:
441
+ return already
442
+
388
443
  trace = EpisodeTrace.create(
389
444
  task_id=task_id,
390
445
  agent=agent,
391
446
  phase=phase,
392
447
  goal=goal,
393
448
  )
449
+ trace.id = episode_id
394
450
  trace.outcome = outcome
395
451
  trace.duration_seconds = duration
396
452
  # v7.7.18 council fix: apply BOTH scrubbers to file paths --
@@ -440,16 +496,30 @@ def ingest_from_summary(
440
496
  engine = MemoryEngine(storage=storage, base_path=memory_base)
441
497
  engine.initialize()
442
498
 
499
+ # Only a caller-supplied task_id is a stable key. The auto-generated
500
+ # timestamp fallback is unique per call by design, so it must NOT
501
+ # drive a deterministic id (that would alias unrelated captures).
502
+ caller_supplied_key = task_id is not None
443
503
  if task_id is None:
444
504
  ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
445
505
  task_id = f"mcp-capture-{ts}"
446
506
 
507
+ if caller_supplied_key:
508
+ episode_id = _deterministic_episode_id(task_id)
509
+ already = _existing_episode_path(storage, memory_base, episode_id)
510
+ if already is not None:
511
+ return already
512
+ else:
513
+ episode_id = None
514
+
447
515
  trace = EpisodeTrace.create(
448
516
  task_id=task_id,
449
517
  agent=agent,
450
518
  phase=phase,
451
519
  goal=_scrub(goal)[:500],
452
520
  )
521
+ if episode_id is not None:
522
+ trace.id = episode_id
453
523
  trace.outcome = outcome if outcome in ("success", "failure", "partial") else "success"
454
524
  trace.duration_seconds = max(0, int(duration_seconds))
455
525
  trace.files_read = [_scrub_path(_scrub(p)) for p in (files_read or [])]
@@ -9,10 +9,20 @@ Storage: ~/.loki/knowledge/
9
9
  """
10
10
 
11
11
  import json
12
+ import logging
12
13
  import os
13
14
  from pathlib import Path
14
15
  from datetime import datetime, timezone
15
16
 
17
+ try:
18
+ import fcntl # POSIX-only; absent on Windows.
19
+ _HAS_FCNTL = True
20
+ except ImportError: # pragma: no cover - non-POSIX fallback
21
+ fcntl = None
22
+ _HAS_FCNTL = False
23
+
24
+ logger = logging.getLogger(__name__)
25
+
16
26
 
17
27
  class OrganizationKnowledgeGraph:
18
28
  """Aggregates patterns and knowledge across multiple projects."""
@@ -79,11 +89,30 @@ class OrganizationKnowledgeGraph:
79
89
  return unique
80
90
 
81
91
  def save_patterns(self, patterns):
82
- """Save patterns to the knowledge store (appends to JSONL)."""
92
+ """Save patterns to the knowledge store (appends to JSONL).
93
+
94
+ The append is guarded by an exclusive flock and a single flushed
95
+ write so concurrent writers cannot interleave partial lines.
96
+ stdio buffering breaks O_APPEND atomicity and a record longer
97
+ than PIPE_BUF can split mid-line under concurrency, so we both
98
+ hold the lock and emit one contiguous buffer before unlocking.
99
+ """
83
100
  self.ensure_dir()
101
+ # Serialize first so a serialization error cannot leave a partial
102
+ # line on disk while the lock is held.
103
+ buffer = "".join(json.dumps(p) + "\n" for p in patterns)
104
+ if not buffer:
105
+ return
84
106
  with open(self.patterns_file, 'a') as f:
85
- for p in patterns:
86
- f.write(json.dumps(p) + '\n')
107
+ if _HAS_FCNTL:
108
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
109
+ try:
110
+ f.write(buffer)
111
+ f.flush()
112
+ os.fsync(f.fileno())
113
+ finally:
114
+ if _HAS_FCNTL:
115
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
87
116
 
88
117
  def load_patterns(self, limit=100):
89
118
  """Load patterns from the knowledge store."""
@@ -98,6 +127,12 @@ class OrganizationKnowledgeGraph:
98
127
  try:
99
128
  patterns.append(json.loads(line))
100
129
  except json.JSONDecodeError:
130
+ # Resilient: skip the bad row but surface it so silent
131
+ # data loss (e.g. a torn legacy line) is observable.
132
+ logger.warning(
133
+ "knowledge_graph: dropped unparseable patterns.jsonl line: %.120r",
134
+ line,
135
+ )
101
136
  continue
102
137
  if len(patterns) >= limit:
103
138
  break
@@ -297,6 +297,14 @@ class MemoryRetrieval:
297
297
 
298
298
  # Track which legacy entries we've already warned about to avoid log spam.
299
299
  _LEGACY_WARN_LIMIT = 5
300
+
301
+ # Cap on episode files read per keyword scan. The episodic store grows
302
+ # unbounded over a long-lived project, so an uncapped scan reads+parses
303
+ # every episode on every keyword query. Date dirs are walked newest-first,
304
+ # so the cap retains the most recent episodes (the natural relevance order)
305
+ # and only stops unbounded IO; it does not change scoring of retained
306
+ # candidates.
307
+ _KEYWORD_SCAN_MAX_EPISODES = 2000
300
308
  _legacy_warned_count: int = 0
301
309
 
302
310
  def _belongs_to_namespace(self, result: Dict[str, Any]) -> bool:
@@ -1509,7 +1517,14 @@ class MemoryRetrieval:
1509
1517
  if not date_dirs:
1510
1518
  return results
1511
1519
 
1520
+ # Bound the scan so an unbounded episodic store does not force a
1521
+ # read+parse of every episode on each query (see
1522
+ # _KEYWORD_SCAN_MAX_EPISODES). Newest date dirs first keeps the most
1523
+ # recent episodes.
1524
+ scanned = 0
1512
1525
  for date_dir in sorted(date_dirs, reverse=True):
1526
+ if scanned >= self._KEYWORD_SCAN_MAX_EPISODES:
1527
+ break
1513
1528
  if not date_dir.is_dir():
1514
1529
  continue
1515
1530
 
@@ -1519,7 +1534,10 @@ class MemoryRetrieval:
1519
1534
  for episode_file in episode_files:
1520
1535
  if episode_file.name == "index.json":
1521
1536
  continue
1537
+ if scanned >= self._KEYWORD_SCAN_MAX_EPISODES:
1538
+ break
1522
1539
 
1540
+ scanned += 1
1523
1541
  data = self.storage.read_json(
1524
1542
  f"episodic/{date_dir.name}/{episode_file.name}"
1525
1543
  )
package/memory/storage.py CHANGED
@@ -429,6 +429,21 @@ class MemoryStorage:
429
429
  # Episode Storage
430
430
  # -------------------------------------------------------------------------
431
431
 
432
+ @staticmethod
433
+ def _sanitize_episode_id(episode_id) -> str:
434
+ """
435
+ Sanitize an episode id for use in a filename.
436
+
437
+ Separators and "." segments cannot leak into the path (mirrors
438
+ save_skill). save_episode and load_episode must use the SAME transform
439
+ or a round-tripped id with ":", "/", or "." chars would write to one
440
+ file and read from another.
441
+ """
442
+ return "".join(
443
+ c if c.isalnum() or c in "-_" else "_"
444
+ for c in str(episode_id)
445
+ )
446
+
432
447
  def save_episode(self, episode: EpisodeTrace) -> str:
433
448
  """
434
449
  Save an episode trace to storage.
@@ -475,10 +490,7 @@ class MemoryStorage:
475
490
  if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str):
476
491
  date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
477
492
 
478
- safe_episode_id = "".join(
479
- c if c.isalnum() or c in "-_" else "_"
480
- for c in str(episode_id)
481
- )
493
+ safe_episode_id = self._sanitize_episode_id(episode_id)
482
494
 
483
495
  date_dir = self.base_path / "episodic" / date_str
484
496
  date_dir.mkdir(parents=True, exist_ok=True)
@@ -507,10 +519,14 @@ class MemoryStorage:
507
519
  if not episodic_dir.exists():
508
520
  return None
509
521
 
522
+ # Sanitize the same way save_episode does so an id carrying ":", "/",
523
+ # or "." chars resolves to the file it was actually written to.
524
+ safe_episode_id = self._sanitize_episode_id(episode_id)
525
+
510
526
  # Search all date directories
511
527
  for date_dir in episodic_dir.iterdir():
512
528
  if date_dir.is_dir():
513
- file_path = date_dir / f"task-{episode_id}.json"
529
+ file_path = date_dir / f"task-{safe_episode_id}.json"
514
530
  if file_path.exists():
515
531
  data = self._load_json(file_path)
516
532
  if data:
@@ -1519,6 +1535,53 @@ class MemoryStorage:
1519
1535
 
1520
1536
  return False
1521
1537
 
1538
+ def increment_pattern_usage(self, pattern_id: str) -> bool:
1539
+ """Atomically increment a semantic pattern's usage_count, keyed by id.
1540
+
1541
+ The entire read-mutate-write happens inside a single exclusive
1542
+ _file_lock so concurrent increments cannot lose updates. Mirrors the
1543
+ lock-spanning idiom of _persist_boost_semantic / save_pattern: fresh
1544
+ read of patterns.json under the lock -> bump the matching entry ->
1545
+ atomic write (which reuses the same reentrant lock).
1546
+
1547
+ Args:
1548
+ pattern_id: Pattern identifier to increment.
1549
+
1550
+ Returns:
1551
+ True if the pattern was found and incremented, False otherwise.
1552
+ """
1553
+ patterns_path = self.base_path / "semantic" / "patterns.json"
1554
+ if not patterns_path.exists():
1555
+ return False
1556
+
1557
+ with self._file_lock(patterns_path, exclusive=True):
1558
+ if not patterns_path.exists():
1559
+ return False
1560
+ try:
1561
+ with open(patterns_path, "r", encoding="utf-8") as f:
1562
+ patterns_file = json.load(f)
1563
+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):
1564
+ return False
1565
+ if not patterns_file:
1566
+ return False
1567
+
1568
+ patterns = patterns_file.get("patterns", [])
1569
+ for pattern in patterns:
1570
+ if not isinstance(pattern, dict):
1571
+ continue
1572
+ if pattern.get("id") == pattern_id:
1573
+ # `or 0` guards an explicit null usage_count (corrupt or
1574
+ # hand-edited record); null and 0 are equivalent here.
1575
+ pattern["usage_count"] = (pattern.get("usage_count") or 0) + 1
1576
+ pattern["last_used"] = datetime.now(timezone.utc).isoformat()
1577
+ patterns_file["last_updated"] = datetime.now(
1578
+ timezone.utc
1579
+ ).isoformat()
1580
+ self._atomic_write(patterns_path, patterns_file)
1581
+ return True
1582
+
1583
+ return False
1584
+
1522
1585
  def batch_apply_decay(
1523
1586
  self,
1524
1587
  collection: str = "all",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "loki-mode",
3
3
  "mcpName": "io.github.asklokesh/loki-mode",
4
- "version": "7.75.0",
4
+ "version": "7.77.0",
5
5
  "description": "Loki Mode by Autonomi. Autonomous spec-to-product system: takes a PRD, GitHub issue, OpenAPI/JSON/YAML, or one-line brief to a deployed app via the RARV-C closure loop with 8 quality gates. Provider-agnostic (Claude Code, OpenAI Codex, Cline, Aider).",
6
6
  "keywords": [
7
7
  "agent",
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "loki-mode",
4
4
  "displayName": "Loki Mode",
5
- "version": "7.75.0",
5
+ "version": "7.77.0",
6
6
  "description": "Autonomous spec-to-product build system with a built-in trust layer (RARV-C closure loop, 8 quality gates, completion council). Ships Loki's spec-hardening, drift-detection, and deterministic PR verification commands plus the Loki MCP server.",
7
7
  "author": {
8
8
  "name": "Autonomi",