coldmemory 0.3.6__py3-none-any.whl

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.
coldmemory/init_cmd.py ADDED
@@ -0,0 +1,2279 @@
1
+ """One-command ColdMemory onboarding: compile a local store, verify a live quote, and wire detected clients."""
2
+
3
+ from contextlib import contextmanager
4
+ import copy
5
+ from datetime import date, datetime, time as dt_time, timezone
6
+ import errno
7
+ import fcntl
8
+ import json
9
+ import math
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ import site
16
+ import stat
17
+ import sys
18
+ import sysconfig
19
+ import time
20
+ import tomllib
21
+
22
+ from . import cartridge_spec as spec
23
+ from . import hooks_snippet, ingest, verifier
24
+ from .multihop_retriever import DiskEngine
25
+ from .verifier import NO_MATCH, make_backend
26
+
27
+ DEFAULT_ID = "notes"
28
+ DEFAULT_TOOLS = "memory_ask"
29
+ AUTO_CLIENTS = ("claude", "codex", "openbot", "hermes", "grok")
30
+ ALL_CLIENTS = AUTO_CLIENTS
31
+ CLIENT_ALIASES = {"claude-code": "claude", "claudecode": "claude"}
32
+ HERMES_FILES = ("__init__.py", "plugin.yaml")
33
+ _TOKEN = re.compile(r"[a-z0-9]+")
34
+ _URL = re.compile(r"https?://\S+")
35
+ _RULE_HINT = re.compile(r"\b(?:rules?|decisions?|polic(?:y|ies)|constraints?)\b", re.I)
36
+ _ARCHIVE_CITE = re.compile(r"^- (?P<path>.+?):\d+(?:-\d+)? \[current\]$", re.M)
37
+
38
+
39
+ def default_store(home=None, env=None):
40
+ """Default local owner store under XDG_DATA_HOME or ~/.local/share/coldmemory."""
41
+ env = os.environ if env is None else env
42
+ home_dir = Path.home() if home is None else Path(home)
43
+ xdg = env.get("XDG_DATA_HOME", "").strip()
44
+ base = Path(xdg).expanduser() if xdg else home_dir / ".local" / "share"
45
+ return (base / "coldmemory").absolute()
46
+
47
+
48
+ def _codex_home(home_dir, env):
49
+ configured = env.get("CODEX_HOME", "").strip()
50
+ return Path(configured).expanduser() if configured else home_dir / ".codex"
51
+
52
+
53
+ def _grok_home(home_dir, env):
54
+ configured = env.get("GROK_HOME", "").strip()
55
+ return Path(configured).expanduser() if configured else home_dir / ".grok"
56
+
57
+
58
+ def _hermes_home(home_dir, env):
59
+ configured = env.get("HERMES_HOME", "").strip()
60
+ return Path(configured).expanduser() if configured else home_dir / ".hermes"
61
+
62
+
63
+ def _package_root():
64
+ return Path(__file__).resolve().parent.parent
65
+
66
+
67
+ def _hermes_source_dir():
68
+ candidates = [
69
+ _package_root() / "integrations" / "hermes" / "coldmemory",
70
+ Path(sysconfig.get_path("data")) / "share" / "coldmemory" / "integrations" / "hermes" / "coldmemory",
71
+ Path(sys.prefix) / "share" / "coldmemory" / "integrations" / "hermes" / "coldmemory",
72
+ ]
73
+ user_base = site.getuserbase()
74
+ if user_base:
75
+ candidates.append(Path(user_base) / "share" / "coldmemory" / "integrations" / "hermes" / "coldmemory")
76
+ for path in candidates:
77
+ if all((path / name).is_file() for name in HERMES_FILES):
78
+ return path
79
+ return None
80
+
81
+
82
+ def _resolve_sources(raw_sources):
83
+ sources = []
84
+ seen_labels = {}
85
+ for raw in raw_sources:
86
+ kind, sep, _ = raw.partition(":")
87
+ if sep and kind in ingest.KINDS:
88
+ src = ingest.parse_source(raw)
89
+ else:
90
+ path = Path(raw).expanduser()
91
+ if not path.exists():
92
+ raise ValueError(f"folder not found: {raw}")
93
+ if not path.is_dir():
94
+ raise ValueError(f"expected a folder of notes, not a file: {raw}")
95
+ resolved = path.resolve(strict=True)
96
+ src = ingest.Source("obsidian", resolved.name, str(resolved))
97
+ if src.label in seen_labels:
98
+ if seen_labels[src.label] == (src.kind, src.root):
99
+ continue
100
+ raise ValueError(f"two sources share the folder name '{src.label}'; pass distinct folders")
101
+ seen_labels[src.label] = (src.kind, src.root)
102
+ sources.append(src)
103
+ if not sources:
104
+ raise ValueError("pass at least one notes folder")
105
+ return sources
106
+
107
+
108
+ def _check_store_outside_sources(store_path, sources):
109
+ resolved_store = store_path.resolve(strict=False)
110
+ for src in sources:
111
+ root = Path(src.root).resolve(strict=False)
112
+ if root == resolved_store or root in resolved_store.parents or root == store_path or root in store_path.parents:
113
+ raise ValueError(f"the store ({store_path}) must be outside every source folder ({src.root})")
114
+
115
+
116
+ def _ensure_private_store(store_path):
117
+ if not store_path.exists():
118
+ store_path.mkdir(mode=0o700, parents=True, exist_ok=True)
119
+ os.chmod(store_path, 0o700)
120
+ try:
121
+ spec._check_private(store_path, directory=True)
122
+ except ValueError as error:
123
+ raise ValueError(f"{store_path}: {error} (run: chmod 700 {shlex.quote(str(store_path))})") from error
124
+
125
+
126
+ @contextmanager
127
+ def _store_init_lock(store_path):
128
+ """Serialize concurrent init calls against one store so two vaults never claim the same bundle ID."""
129
+ lock_path = store_path / ".init.lock"
130
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
131
+ with os.fdopen(fd, "r+") as handle:
132
+ fcntl.flock(handle, fcntl.LOCK_EX)
133
+ yield
134
+
135
+
136
+ def _source_signature(sources):
137
+ return [(s.kind, s.root) for s in sources]
138
+
139
+
140
+ def _inspect_bundle(store_path, ident, sources):
141
+ home = store_path / ident
142
+ if not home.exists() and not home.is_symlink():
143
+ return "free", None
144
+ if not home.is_dir() or home.is_symlink():
145
+ return "collision", None
146
+ # An empty private directory with at most a regular lock file (e.g. after a rejected candidate verify) has no live bundle.
147
+ try:
148
+ spec._check_private(home, directory=True)
149
+ entries = list(home.iterdir())
150
+ except (OSError, ValueError):
151
+ return "collision", None
152
+ if not entries or (len(entries) == 1 and entries[0].name == "lock" and not entries[0].is_symlink() and entries[0].is_file()):
153
+ return "free", None
154
+ try:
155
+ bundle = spec.load(store_path, ident)
156
+ except (OSError, ValueError, KeyError, TypeError):
157
+ return "collision", None
158
+ if (bundle.manifest.get("scope") == "private" and bundle.manifest.get("version") == 1
159
+ and _source_signature(bundle.sources) == _source_signature(sources)):
160
+ return "same", bundle
161
+ return "collision", bundle
162
+
163
+
164
+ def _resolve_bundle_id(store_path, requested_id, sources, *, force=False):
165
+ if requested_id is not None:
166
+ ident = spec.slug(requested_id)
167
+ status, existing = _inspect_bundle(store_path, ident, sources)
168
+ if status in ("free", "same"):
169
+ return ident, status, existing
170
+ if force:
171
+ home = store_path / ident
172
+ if home.exists() and (not home.is_dir() or home.is_symlink()):
173
+ raise ValueError(f"cannot overwrite non-directory path: {home}")
174
+ return ident, "overwrite", existing
175
+ owner_hint = ""
176
+ if existing is not None:
177
+ roots = ", ".join(s.root for s in existing.sources)
178
+ owner_hint = f" (currently points to {roots})"
179
+ raise ValueError(
180
+ f"bundle ID '{ident}' already exists in {store_path}{owner_hint}; "
181
+ "choose another --id or pass --force to overwrite"
182
+ )
183
+
184
+ base = DEFAULT_ID
185
+ if store_path.is_dir():
186
+ for candidate in (base, *[p.name for p in sorted(store_path.iterdir()) if spec.SLUG.fullmatch(p.name)]):
187
+ status, existing = _inspect_bundle(store_path, candidate, sources)
188
+ if status == "same":
189
+ return candidate, "same", existing
190
+ status, _ = _inspect_bundle(store_path, base, sources)
191
+ if status == "free":
192
+ return base, "free", None
193
+ for index in range(2, 10000):
194
+ candidate = f"{base}-{index}"
195
+ status, _ = _inspect_bundle(store_path, candidate, sources)
196
+ if status == "free":
197
+ return candidate, "suffixed", None
198
+ raise ValueError(f"could not pick an unused bundle ID under {store_path}; pass --id explicitly")
199
+
200
+
201
+ def _bundle_unchanged(store_path, existing_bundle, corpus):
202
+ """True when the existing bundle already matches disk notes and approved queue entries (caller holds bundle lock)."""
203
+ if any(spec.freshness(existing_bundle, corpus).values()):
204
+ return False
205
+ graph = corpus.graph()
206
+ approved, outdated = 0, 0
207
+ for entry in spec._read_queue(store_path / existing_bundle.id):
208
+ if not entry["approved"]:
209
+ continue
210
+ if all(graph.get(s["key"], {}).get("sha256") == s["sha256"]
211
+ and not corpus.notes[s["key"]].stale for s in entry["sources"]):
212
+ approved += 1
213
+ else:
214
+ outdated += 1
215
+ counts = existing_bundle.manifest["counts"]
216
+ return approved == counts["approved_notes"] and outdated == counts.get("outdated_approved_notes", 0)
217
+
218
+
219
+ def _find_unchanged_revision(store_path, bundle_id, sources, corpus):
220
+ """Return an existing staged revision (excluding active/previous pointers) matching sources, disk notes and queue."""
221
+ home = store_path / bundle_id
222
+ if not home.is_dir():
223
+ return None
224
+ state = spec._pointer(home)
225
+ excluded = {rev for rev in (state.get("active"), state.get("previous")) if rev}
226
+ candidates = []
227
+ for entry in home.iterdir():
228
+ if not spec.HEX.fullmatch(entry.name) or entry.name in excluded or not entry.is_dir():
229
+ continue
230
+ try:
231
+ rev = spec.load(store_path, bundle_id, entry.name)
232
+ except (OSError, ValueError, KeyError, TypeError):
233
+ continue
234
+ if (rev.manifest.get("scope") == "private" and rev.manifest.get("version") == 1
235
+ and _source_signature(rev.sources) == _source_signature(sources)
236
+ and _bundle_unchanged(store_path, rev, corpus)):
237
+ candidates.append(rev)
238
+ if not candidates:
239
+ return None
240
+ return max(candidates, key=lambda b: (b.manifest.get("built_at", 0), b.revision))
241
+
242
+
243
+ def _candidate_queries(corpus):
244
+ """Build deterministic verification queries using the verifier's own searchable token vocabulary."""
245
+ def priority(note):
246
+ has_rule = bool(ingest.decision_section(note) or _RULE_HINT.search(f"{note.rel} {note.title}"))
247
+ return (note.stale, not has_rule, note.key)
248
+
249
+ def collect_tokens(lines, *, skip_fences):
250
+ words = []
251
+ in_fence = ""
252
+ for line in lines:
253
+ cleaned = (_URL.sub(" ", line) if skip_fences else line).strip()
254
+ if skip_fences and cleaned.startswith(("```", "~~~")):
255
+ marker = cleaned[:3]
256
+ if not in_fence:
257
+ in_fence = marker
258
+ elif in_fence == marker:
259
+ in_fence = ""
260
+ continue
261
+ if skip_fences and (in_fence or not cleaned or cleaned.startswith("---")):
262
+ continue
263
+ if not cleaned:
264
+ continue
265
+ if cleaned.startswith("#"):
266
+ cleaned = cleaned.lstrip("#").strip()
267
+ if not cleaned:
268
+ continue
269
+ for token in _TOKEN.findall(cleaned.lower()):
270
+ if token not in verifier.STOP and token not in words:
271
+ words.append(token)
272
+ if len(words) >= 6:
273
+ return words
274
+ return words
275
+
276
+ ordered = sorted(corpus.notes.values(), key=priority)
277
+ queries = []
278
+ seen = set()
279
+
280
+ def add_words(words):
281
+ if words:
282
+ query = " ".join(words[:5])
283
+ if query not in seen:
284
+ seen.add(query)
285
+ queries.append(query)
286
+
287
+ for note in ordered:
288
+ sample_lines = [note.title, *note.aliases, *note.tags]
289
+ section = ingest.decision_section(note)
290
+ if section:
291
+ sample_lines.extend(note.lines[section[0]:section[2]])
292
+ for _, heading, _ in note.sections:
293
+ if heading:
294
+ sample_lines.append(heading)
295
+ sample_lines.extend(note.lines[note.body_start:])
296
+ add_words(collect_tokens(sample_lines, skip_fences=True))
297
+ if len(queries) >= 5:
298
+ return queries
299
+
300
+ # Fallback to the verifier's exact searchable content (including fenced blocks and URLs).
301
+ for note in ordered:
302
+ searchable_lines = [note.title, *note.aliases, *note.tags]
303
+ fence_headers = []
304
+ for begin, heading, end in note.sections:
305
+ if heading:
306
+ searchable_lines.append(heading)
307
+ for line in note.lines[begin:end]:
308
+ if line.strip().startswith(("```", "~~~")):
309
+ fence_headers.append(line)
310
+ else:
311
+ searchable_lines.append(line)
312
+ words = collect_tokens(searchable_lines, skip_fences=False)
313
+ if not words and fence_headers:
314
+ words = collect_tokens(fence_headers, skip_fences=False)
315
+ add_words(words)
316
+ if len(queries) >= 5:
317
+ return queries
318
+ return queries or ["notes"]
319
+
320
+
321
+ def _extract_verified_preview(answer, bundle, corpus):
322
+ """Return preview lines for the first exact [current] citation matching candidate bundle.graph and live disk."""
323
+ if answer.startswith(NO_MATCH):
324
+ return None
325
+ lines = answer.split("\n")
326
+ rel_prefix = ""
327
+ header = []
328
+ for line in lines:
329
+ if line.startswith("Verified Sources"):
330
+ header.append(line)
331
+ elif line.startswith("Paths are relative to "):
332
+ rel_prefix = line[len("Paths are relative to "):].strip()
333
+ header.append(line)
334
+ elif line.startswith("- "):
335
+ break
336
+ by_path = {note.path: note for note in corpus.notes.values()}
337
+ by_key = {note.key: note for note in corpus.notes.values()}
338
+ for i, line in enumerate(lines):
339
+ match = _ARCHIVE_CITE.match(line)
340
+ if not match:
341
+ continue
342
+ cited = match.group("path")
343
+ note = by_path.get(os.path.join(rel_prefix, cited)) if rel_prefix else by_path.get(cited)
344
+ if note is None:
345
+ note = by_key.get(cited)
346
+ if note is None:
347
+ note = next((n for p, n in by_path.items() if p.endswith("/" + cited)), None)
348
+ if note is None:
349
+ continue
350
+ expected_sha = bundle.graph.get(note.key, {}).get("sha256")
351
+ if not expected_sha or expected_sha != note.sha256:
352
+ continue
353
+ try:
354
+ disk_sha = spec.sha256_file(Path(note.path))
355
+ except OSError:
356
+ continue
357
+ if disk_sha != expected_sha:
358
+ continue
359
+ block = [line]
360
+ j = i + 1
361
+ while j < len(lines) and lines[j].startswith(" "):
362
+ block.append(lines[j])
363
+ j += 1
364
+ return [*header, *block][:6]
365
+ return None
366
+
367
+
368
+ class _SmokeVerificationError(Exception):
369
+ def __init__(self, query, bundle_id, revision):
370
+ super().__init__(query)
371
+ self.query = query
372
+ self.bundle_id = bundle_id
373
+ self.revision = revision
374
+
375
+
376
+ def _verify_candidate(bundle, corpus, custom_query=None):
377
+ """Run the archive verifier directly against a candidate bundle before activating or pruning history."""
378
+ engine = DiskEngine(bundle, make_backend("disk", bundle, None))
379
+ queries = [custom_query] if custom_query else _candidate_queries(corpus)
380
+ last_query, last_preview = queries[0], []
381
+ for query in queries:
382
+ archive_answer = engine.ask(query, 180)
383
+ preview = _extract_verified_preview(archive_answer, bundle, corpus)
384
+ last_query = query
385
+ if preview is not None:
386
+ return query, preview, True
387
+ return last_query, last_preview, False
388
+
389
+
390
+ def _normalize_client(name):
391
+ key = name.strip().lower()
392
+ key = CLIENT_ALIASES.get(key, key)
393
+ if key not in ALL_CLIENTS:
394
+ valid = ", ".join(["auto", "none", *ALL_CLIENTS])
395
+ raise ValueError(f"unknown client '{name}'; choose from: {valid}")
396
+ return key
397
+
398
+
399
+ def detect_clients(home=None, env=None, which=shutil.which):
400
+ """Detect installed local AI coding clients without modifying anything."""
401
+ env = os.environ if env is None else env
402
+ home_dir = Path.home() if home is None else Path(home)
403
+ codex_dir = _codex_home(home_dir, env)
404
+ hermes_dir = _hermes_home(home_dir, env)
405
+ detected = []
406
+ if (home_dir / ".claude").is_dir() or (home_dir / ".claude.json").is_file() or bool(which("claude")):
407
+ detected.append("claude")
408
+ if codex_dir.is_dir() or bool(which("codex")):
409
+ detected.append("codex")
410
+ if (home_dir / ".config" / "OpenBot").is_dir() or (home_dir / ".openbot").is_dir() or bool(which("openbot")):
411
+ detected.append("openbot")
412
+ if hermes_dir.is_dir() or bool(which("hermes")):
413
+ detected.append("hermes")
414
+ if _grok_home(home_dir, env).is_dir() or bool(which("grok")):
415
+ detected.append("grok")
416
+ return detected
417
+
418
+
419
+ def resolve_clients(spec_str, home=None, env=None, which=shutil.which):
420
+ raw = (spec_str or "auto").strip().lower()
421
+ if raw == "none":
422
+ return []
423
+ if raw == "auto":
424
+ return detect_clients(home=home, env=env, which=which)
425
+ ordered = []
426
+ for part in raw.split(","):
427
+ if not part.strip():
428
+ continue
429
+ client = _normalize_client(part)
430
+ if client not in ordered:
431
+ ordered.append(client)
432
+ return ordered
433
+
434
+
435
+ def _mcp_server_config(store_path, package_root, python=sys.executable):
436
+ return hooks_snippet.server_config(
437
+ store_path, package_root=package_root, python=python,
438
+ scope="private", local_unsigned=True, tools=DEFAULT_TOOLS,
439
+ )
440
+
441
+
442
+ def _push_hooks_dict(store_path, package_root, python=sys.executable):
443
+ return json.loads(
444
+ hooks_snippet.push_hooks(store_path, package_root=package_root, python=python,
445
+ scope="private", local_unsigned=True)
446
+ )["hooks"]
447
+
448
+
449
+ def _has_unquoted_expansion(command):
450
+ """True if command contains command substitution (` or $()) outside single quotes, or unquoted newline/CR."""
451
+ quote = None
452
+ i, n = 0, len(command)
453
+ while i < n:
454
+ ch = command[i]
455
+ if quote == "'":
456
+ if ch == "'":
457
+ quote = None
458
+ i += 1
459
+ continue
460
+ if ch == "\\":
461
+ if i + 1 < n and command[i + 1] in ("\n", "\r"):
462
+ return True
463
+ i += 2
464
+ continue
465
+ if quote == '"':
466
+ if ch == '"':
467
+ quote = None
468
+ elif ch == "`" or command.startswith("$(", i):
469
+ return True
470
+ i += 1
471
+ continue
472
+ if ch in ("'", '"'):
473
+ quote = ch
474
+ elif ch in ("\n", "\r") or ch == "`" or command.startswith("$(", i):
475
+ return True
476
+ i += 1
477
+ return False
478
+
479
+
480
+ def _strip_shell_comment(command):
481
+ """Strip a POSIX shell comment starting with unquoted # at word start, preserving embedded # and quoted newlines.
482
+
483
+ Returns None when an unquoted newline/CR appears (which acts as a POSIX shell command separator)."""
484
+ quote = None
485
+ word_start = True
486
+ i, n = 0, len(command)
487
+ while i < n:
488
+ ch = command[i]
489
+ if quote == "'":
490
+ if ch == "'":
491
+ quote = None
492
+ word_start = False
493
+ i += 1
494
+ continue
495
+ if ch == "\\":
496
+ if i + 1 < n and command[i + 1] in ("\n", "\r"):
497
+ return None
498
+ word_start = False
499
+ i += 2
500
+ continue
501
+ if quote == '"':
502
+ if ch == '"':
503
+ quote = None
504
+ word_start = False
505
+ i += 1
506
+ continue
507
+ if ch in ("\n", "\r"):
508
+ return None
509
+ if ch == "#" and word_start:
510
+ if "\n" in command[i:] or "\r" in command[i:]:
511
+ return None
512
+ return command[:i]
513
+ if ch in ("'", '"'):
514
+ quote = ch
515
+ word_start = False
516
+ elif ch.isspace() or ch in (";", "&", "|", "("):
517
+ word_start = True
518
+ else:
519
+ word_start = False
520
+ i += 1
521
+ return command
522
+
523
+
524
+ _REDIR_OPS = frozenset({"<", "<<", "<<-", "<<<", "<&", "<>", ">", ">>", ">&", ">|", "&>", "&>>"})
525
+ _MULTI_SHELL_OPS = ("<<<", "<<-", "&>>", "&&", "||", ";;", "|&", "<<", ">>", "<&", ">&", "<>", ">|", "&>")
526
+ _SINGLE_SHELL_OPS = frozenset({";", "&", "|", "(", ")", "<", ">"})
527
+ _PYTHON_INTERP = re.compile(r"^(?:python(?:\d+(?:\.\d+)*t?)?|pypy(?:\d+(?:\.\d+)*)?)(?:\.exe)?$", re.I)
528
+ _STANDARD_HOOK_KEYS = frozenset({"type", "command", "timeout"})
529
+ _STANDARD_MATCHER_KEYS = frozenset({"matcher", "hooks"})
530
+
531
+
532
+ def _tokenize_shell_with_ops(command):
533
+ """Tokenize POSIX shell text into (text, is_operator) tuples, preserving quote vs operator boundaries."""
534
+ tokens = []
535
+ buf = []
536
+ has_word = False
537
+ i, n = 0, len(command)
538
+
539
+ def flush():
540
+ nonlocal has_word
541
+ if has_word:
542
+ tokens.append(("".join(buf), False))
543
+ buf.clear()
544
+ has_word = False
545
+
546
+ while i < n:
547
+ ch = command[i]
548
+ if ch.isspace():
549
+ flush()
550
+ i += 1
551
+ continue
552
+ if ch == "'":
553
+ has_word = True
554
+ end = command.find("'", i + 1)
555
+ if end < 0:
556
+ raise ValueError("unterminated single quote")
557
+ buf.append(command[i + 1:end])
558
+ i = end + 1
559
+ continue
560
+ if ch == '"':
561
+ has_word = True
562
+ i += 1
563
+ while i < n and command[i] != '"':
564
+ if command[i] == "\\" and i + 1 < n and command[i + 1] in ('"', "\\", "$", "`", "\n"):
565
+ if command[i + 1] != "\n":
566
+ buf.append(command[i + 1])
567
+ i += 2
568
+ else:
569
+ buf.append(command[i])
570
+ i += 1
571
+ if i >= n:
572
+ raise ValueError("unterminated double quote")
573
+ i += 1
574
+ continue
575
+ if ch == "\\":
576
+ has_word = True
577
+ if i + 1 < n:
578
+ if command[i + 1] != "\n":
579
+ buf.append(command[i + 1])
580
+ i += 2
581
+ else:
582
+ raise ValueError("trailing backslash")
583
+ continue
584
+ matched_op = next((op for op in _MULTI_SHELL_OPS if command.startswith(op, i)), None)
585
+ if matched_op is not None:
586
+ flush()
587
+ tokens.append((matched_op, True))
588
+ i += len(matched_op)
589
+ continue
590
+ if ch in _SINGLE_SHELL_OPS:
591
+ flush()
592
+ tokens.append((ch, True))
593
+ i += 1
594
+ continue
595
+ has_word = True
596
+ buf.append(ch)
597
+ i += 1
598
+ flush()
599
+ return tokens
600
+
601
+
602
+ def _command_is_signed(args_list):
603
+ """True unless an existing ColdMemory command/args list explicitly uses private local-unsigned mode.
604
+
605
+ Matches argparse's unambiguous prefix abbreviations (e.g. --tr... for --trust-key, --sc... for --scope,
606
+ --l... for --local-unsigned) and fails closed when local-unsigned is absent."""
607
+ if not isinstance(args_list, list):
608
+ return True
609
+ has_local_unsigned = False
610
+ for idx, raw in enumerate(args_list):
611
+ tok = str(raw)
612
+ flag, eq, val = tok.partition("=")
613
+ if flag.startswith("--"):
614
+ if len(flag) >= 4 and "--trust-key".startswith(flag):
615
+ return True
616
+ if len(flag) >= 4 and "--scope".startswith(flag):
617
+ scope_val = val if eq else (str(args_list[idx + 1]) if idx + 1 < len(args_list) else "")
618
+ if scope_val != "private":
619
+ return True
620
+ if len(flag) >= 3 and "--local-unsigned".startswith(flag) and not eq:
621
+ has_local_unsigned = True
622
+ return not has_local_unsigned
623
+
624
+
625
+ def _split_coldmemory_hook_tokens(tokens):
626
+ """Return (kind, has_custom_env, hook_args) for a standalone coldmemory.push/brief command, else None."""
627
+ if not tokens:
628
+ return None
629
+ i = 0
630
+ has_custom_env = False
631
+ while i < len(tokens):
632
+ tok = tokens[i]
633
+ if Path(tok).name == "env":
634
+ i += 1
635
+ while i < len(tokens):
636
+ arg = tokens[i]
637
+ if arg == "--":
638
+ i += 1
639
+ break
640
+ if arg in ("-u", "--unset", "-C", "--chdir") and i + 1 < len(tokens):
641
+ has_custom_env = True
642
+ i += 2
643
+ elif (arg in ("-i", "--ignore-environment", "-0", "--null")
644
+ or arg.startswith(("-u", "--unset=", "-C", "--chdir="))):
645
+ has_custom_env = True
646
+ i += 1
647
+ elif arg.startswith("-"):
648
+ return None
649
+ elif "=" in arg and not arg.startswith("="):
650
+ if arg.partition("=")[0] != "PYTHONPATH":
651
+ has_custom_env = True
652
+ i += 1
653
+ else:
654
+ break
655
+ continue
656
+ if "=" in tok and not tok.startswith("="):
657
+ if tok.partition("=")[0] != "PYTHONPATH":
658
+ has_custom_env = True
659
+ i += 1
660
+ continue
661
+ break
662
+ rest = tokens[i:]
663
+ if not rest:
664
+ return None
665
+ prog = Path(rest[0]).name
666
+ if prog == "coldmemory" and len(rest) >= 2 and rest[1] == "brief":
667
+ return "brief", has_custom_env, rest[2:]
668
+ if _PYTHON_INTERP.fullmatch(prog):
669
+ j = 1
670
+ while j < len(rest) and rest[j].startswith("-"):
671
+ flag = rest[j]
672
+ mod_flag = re.fullmatch(r"-[bBdEhiIOqRsSuv]*m(.*)", flag)
673
+ if mod_flag:
674
+ if mod_flag.group(1):
675
+ mod, next_idx = mod_flag.group(1), j + 1
676
+ elif j + 1 < len(rest):
677
+ mod, next_idx = rest[j + 1], j + 2
678
+ else:
679
+ return None
680
+ if mod == "coldmemory.push":
681
+ return "push", has_custom_env, rest[next_idx:]
682
+ if mod == "coldmemory" and next_idx < len(rest) and rest[next_idx] == "brief":
683
+ return "brief", has_custom_env, rest[next_idx + 1:]
684
+ return None
685
+ if flag in ("-W", "-X", "--check-hash-based-pycs") and j + 1 < len(rest):
686
+ j += 2
687
+ elif re.fullmatch(r"-[bBdEhiIOqRsSuv]+", flag) or flag.startswith(("-W", "-X", "--check-hash-based-pycs=")):
688
+ j += 1
689
+ else:
690
+ return None
691
+ return None
692
+
693
+
694
+ def _tokens_are_coldmemory_hook(tokens):
695
+ return _split_coldmemory_hook_tokens(tokens) is not None
696
+
697
+
698
+ def _hook_args_are_customized(tokens):
699
+ """True when a standalone ColdMemory hook carries custom env vars or extra CLI arguments (e.g. --deadline)."""
700
+ parsed = _split_coldmemory_hook_tokens(tokens)
701
+ if parsed is None:
702
+ return True
703
+ _, has_custom_env, hook_args = parsed
704
+ if has_custom_env:
705
+ return True
706
+ i = 0
707
+ while i < len(hook_args):
708
+ flag, eq, val = str(hook_args[i]).partition("=")
709
+ if len(flag) >= 4 and "--store".startswith(flag):
710
+ if eq:
711
+ i += 1
712
+ elif i + 1 < len(hook_args):
713
+ i += 2
714
+ else:
715
+ return True
716
+ elif len(flag) >= 4 and "--scope".startswith(flag):
717
+ scope_val = val if eq else (str(hook_args[i + 1]) if i + 1 < len(hook_args) else None)
718
+ if scope_val != "private":
719
+ return True
720
+ i += 1 if eq else 2
721
+ elif len(flag) >= 3 and "--local-unsigned".startswith(flag) and not eq:
722
+ i += 1
723
+ else:
724
+ return True
725
+ return False
726
+
727
+
728
+ def _mcp_entry_is_customized(entry):
729
+ """True unless an existing stdio MCP entry is a standard local-unsigned Python `-m coldmemory.mcp_server` launcher."""
730
+ if not isinstance(entry, dict):
731
+ return True
732
+ cmd = entry.get("command")
733
+ if not isinstance(cmd, str) or not cmd.strip() or not _PYTHON_INTERP.fullmatch(Path(cmd).name):
734
+ return True
735
+ args_list = entry.get("args")
736
+ if not isinstance(args_list, list):
737
+ return True
738
+ i = 0
739
+ saw_module = False
740
+ while i < len(args_list) and str(args_list[i]).startswith("-"):
741
+ flag = str(args_list[i])
742
+ mod_flag = re.fullmatch(r"-[bBdEhiIOqRsSuv]*m(.*)", flag)
743
+ if mod_flag:
744
+ if mod_flag.group(1):
745
+ mod, next_idx = mod_flag.group(1), i + 1
746
+ elif i + 1 < len(args_list):
747
+ mod, next_idx = str(args_list[i + 1]), i + 2
748
+ else:
749
+ return True
750
+ if mod != "coldmemory.mcp_server":
751
+ return True
752
+ i = next_idx
753
+ saw_module = True
754
+ break
755
+ if flag in ("-W", "-X", "--check-hash-based-pycs") and i + 1 < len(args_list):
756
+ i += 2
757
+ elif re.fullmatch(r"-[bBdEhiIOqRsSuv]+", flag) or flag.startswith(("-W", "-X", "--check-hash-based-pycs=")):
758
+ i += 1
759
+ else:
760
+ return True
761
+ if not saw_module:
762
+ return True
763
+ while i < len(args_list):
764
+ flag, eq, val = str(args_list[i]).partition("=")
765
+ if len(flag) >= 4 and "--store".startswith(flag):
766
+ if eq:
767
+ i += 1
768
+ elif i + 1 < len(args_list):
769
+ i += 2
770
+ else:
771
+ return True
772
+ elif len(flag) >= 4 and "--scope".startswith(flag):
773
+ scope_val = val if eq else (str(args_list[i + 1]) if i + 1 < len(args_list) else None)
774
+ if scope_val != "private":
775
+ return True
776
+ i += 1 if eq else 2
777
+ elif len(flag) >= 3 and "--local-unsigned".startswith(flag) and not eq:
778
+ i += 1
779
+ elif len(flag) >= 3 and "--backend".startswith(flag):
780
+ backend_val = val if eq else (str(args_list[i + 1]) if i + 1 < len(args_list) else None)
781
+ if backend_val != "disk":
782
+ return True
783
+ i += 1 if eq else 2
784
+ elif len(flag) >= 4 and "--tools".startswith(flag):
785
+ tools_val = val if eq else (str(args_list[i + 1]) if i + 1 < len(args_list) else None)
786
+ if tools_val != DEFAULT_TOOLS:
787
+ return True
788
+ i += 1 if eq else 2
789
+ else:
790
+ return True
791
+ return False
792
+
793
+
794
+ def _parse_standalone_hook(command):
795
+ """Classify a hook command as ('standalone', tokens), ('redirected', tokens), or ('other', None).
796
+
797
+ Only recognizes supported standalone ColdMemory invocations (coldmemory.push or coldmemory brief)
798
+ with optional trailing shell comment or simple redirections; compound, wrapped and unrelated hooks stay intact."""
799
+ if not isinstance(command, str) or not command.strip():
800
+ return "other", None
801
+ cleaned = _strip_shell_comment(command)
802
+ if cleaned is None or not cleaned.strip() or _has_unquoted_expansion(cleaned):
803
+ return "other", None
804
+ try:
805
+ toks = _tokenize_shell_with_ops(cleaned)
806
+ except ValueError:
807
+ return "other", None
808
+ words = []
809
+ has_redir = False
810
+ i = 0
811
+ while i < len(toks):
812
+ tok, is_op = toks[i]
813
+ if is_op:
814
+ if tok in _REDIR_OPS:
815
+ has_redir = True
816
+ if words and words[-1].isdigit():
817
+ words.pop()
818
+ i += 2
819
+ continue
820
+ return "other", None
821
+ words.append(tok)
822
+ i += 1
823
+ if not _tokens_are_coldmemory_hook(words):
824
+ return "other", None
825
+ return ("redirected" if has_redir else "standalone"), words
826
+
827
+
828
+ def _is_coldmemory_hook_command(command):
829
+ """True only when command is a clean standalone invocation of coldmemory.push or coldmemory brief."""
830
+ kind, _ = _parse_standalone_hook(command)
831
+ return kind == "standalone"
832
+
833
+
834
+ def _hook_is_customized(entry, item, *, expected_matcher=None):
835
+ """True when a ColdMemory hook carries custom metadata (matcher restriction, 'if' condition, or custom timeout)."""
836
+ if any(k not in _STANDARD_MATCHER_KEYS for k in entry):
837
+ return True
838
+ actual_matcher = entry.get("matcher")
839
+ if actual_matcher != expected_matcher:
840
+ return True
841
+ if not isinstance(item, dict):
842
+ return True
843
+ if any(k not in _STANDARD_HOOK_KEYS for k in item):
844
+ return True
845
+ if item.get("type", "command") != "command":
846
+ return True
847
+ if "timeout" in item and item["timeout"] not in (5, 30):
848
+ return True
849
+ return False
850
+
851
+
852
+ def _strip_coldmemory_hooks(entry, *, force=False, path=None, expected_commands=(), expected_matcher=None):
853
+ """Return (remaining_entry_or_None, had_coldmemory_hook) without dropping unrelated commands in a matcher."""
854
+ if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
855
+ return entry, False
856
+ kept = []
857
+ removed = False
858
+ for item in entry["hooks"]:
859
+ cmd = item.get("command") if isinstance(item, dict) else None
860
+ if isinstance(cmd, str) and cmd in expected_commands:
861
+ if not force and _hook_is_customized(entry, item, expected_matcher=expected_matcher):
862
+ raise ValueError(
863
+ f"{path}: existing ColdMemory hook has custom settings (matcher, 'if' condition, or timeout); "
864
+ "update it manually or pass --force to replace it"
865
+ )
866
+ removed = True
867
+ continue
868
+ kind, tokens = _parse_standalone_hook(cmd)
869
+ if kind == "standalone":
870
+ if not force and _command_is_signed(tokens):
871
+ raise ValueError(
872
+ f"{path}: existing ColdMemory hook uses a signed/custom scope; pass --force to replace it"
873
+ )
874
+ if not force and (_hook_is_customized(entry, item, expected_matcher=expected_matcher)
875
+ or _hook_args_are_customized(tokens)):
876
+ raise ValueError(
877
+ f"{path}: existing ColdMemory hook has custom settings or arguments "
878
+ "(matcher, 'if' condition, timeout, env, or CLI flags such as --deadline); "
879
+ "update it manually or pass --force to replace it"
880
+ )
881
+ removed = True
882
+ elif kind == "redirected":
883
+ raise ValueError(
884
+ f"{path}: existing ColdMemory hook uses shell redirection and cannot be rewritten automatically; "
885
+ "update or remove it manually"
886
+ )
887
+ else:
888
+ kept.append(item)
889
+ if not removed:
890
+ return entry, False
891
+ if not kept:
892
+ return None, True
893
+ return {**entry, "hooks": kept}, True
894
+
895
+
896
+ _REMOTE_ONLY_KEYS = frozenset({
897
+ "url", "type", "bearer_token_env_var", "http_headers", "env_http_headers", "headers",
898
+ "scopes", "oauth_resource",
899
+ })
900
+
901
+
902
+ def _is_remote_mcp_entry(entry):
903
+ if not isinstance(entry, dict):
904
+ return False
905
+ transport = entry.get("type")
906
+ return "url" in entry or (transport is not None and transport != "stdio")
907
+
908
+
909
+ def _merge_json_mcp(existing_text, server_cfg, path, *, force=False):
910
+ if existing_text.strip():
911
+ try:
912
+ data = json.loads(existing_text)
913
+ except ValueError as error:
914
+ raise ValueError(f"{path} is not valid JSON: {error}") from error
915
+ if not isinstance(data, dict):
916
+ raise ValueError(f"{path} must contain a JSON object")
917
+ else:
918
+ data = {}
919
+ servers = data.get("mcpServers")
920
+ if servers is None:
921
+ servers = {}
922
+ data["mcpServers"] = servers
923
+ elif not isinstance(servers, dict):
924
+ raise ValueError(f"{path}: 'mcpServers' must be a JSON object")
925
+ existing_cm = servers.get("coldmemory")
926
+ if isinstance(existing_cm, dict):
927
+ if _is_remote_mcp_entry(existing_cm):
928
+ if not force:
929
+ raise ValueError(
930
+ f"{path}: existing mcpServers.coldmemory uses a non-stdio/remote transport; "
931
+ "pass --force to replace it with local stdio"
932
+ )
933
+ base_cm = {k: v for k, v in existing_cm.items() if k not in _REMOTE_ONLY_KEYS}
934
+ elif not force and _command_is_signed(existing_cm.get("args", [])):
935
+ raise ValueError(
936
+ f"{path}: existing mcpServers.coldmemory uses a signed/custom scope; pass --force to replace it"
937
+ )
938
+ elif (not force
939
+ and not (existing_cm.get("command") == server_cfg["command"]
940
+ and existing_cm.get("args") == server_cfg["args"])
941
+ and _mcp_entry_is_customized(existing_cm)):
942
+ raise ValueError(
943
+ f"{path}: existing mcpServers.coldmemory uses a custom launcher or arguments "
944
+ "(e.g. wrapper command, --backend, --url, or --tools); update it manually or pass --force to replace it"
945
+ )
946
+ else:
947
+ base_cm = existing_cm
948
+ existing_env = base_cm.get("env") if isinstance(base_cm.get("env"), dict) else {}
949
+ merged_env = {**existing_env, **server_cfg["env"]}
950
+ merged_cm = {**base_cm, **server_cfg, "env": merged_env}
951
+ else:
952
+ merged_cm = dict(server_cfg)
953
+ if existing_cm == merged_cm and existing_text.strip():
954
+ return existing_text, False
955
+ servers["coldmemory"] = merged_cm
956
+ return json.dumps(data, indent=2) + "\n", True
957
+
958
+
959
+ def _merge_json_hooks(existing_text, desired_hooks, path, *, force=False):
960
+ if existing_text.strip():
961
+ try:
962
+ data = json.loads(existing_text)
963
+ except ValueError as error:
964
+ raise ValueError(f"{path} is not valid JSON: {error}") from error
965
+ if not isinstance(data, dict):
966
+ raise ValueError(f"{path} must contain a JSON object")
967
+ else:
968
+ data = {}
969
+ hooks = data.get("hooks")
970
+ if hooks is None:
971
+ hooks = {}
972
+ data["hooks"] = hooks
973
+ elif not isinstance(hooks, dict):
974
+ raise ValueError(f"{path}: 'hooks' must be a JSON object")
975
+ expected_commands = {
976
+ item["command"]
977
+ for entries in desired_hooks.values()
978
+ for entry in entries
979
+ for item in entry.get("hooks", [])
980
+ if isinstance(item, dict) and isinstance(item.get("command"), str)
981
+ }
982
+ changed = not existing_text.strip()
983
+ for event, desired_entries in desired_hooks.items():
984
+ current = hooks.get(event)
985
+ if current is None:
986
+ current = []
987
+ elif not isinstance(current, list):
988
+ raise ValueError(f"{path}: 'hooks.{event}' must be a JSON list")
989
+ first_idx = None
990
+ kept = []
991
+ expected_matcher = next(
992
+ (e.get("matcher") for e in desired_entries if isinstance(e, dict) and "matcher" in e),
993
+ None,
994
+ )
995
+ for item in current:
996
+ remainder, had_cm = _strip_coldmemory_hooks(
997
+ item, force=force, path=path, expected_commands=expected_commands, expected_matcher=expected_matcher
998
+ )
999
+ if had_cm and first_idx is None:
1000
+ first_idx = len(kept)
1001
+ if remainder is not None:
1002
+ kept.append(remainder)
1003
+ if first_idx is None:
1004
+ updated = kept + list(desired_entries)
1005
+ else:
1006
+ updated = kept[:first_idx] + list(desired_entries) + kept[first_idx:]
1007
+ if updated != current or event not in hooks:
1008
+ hooks[event] = updated
1009
+ changed = True
1010
+ if not changed:
1011
+ return existing_text, False
1012
+ return json.dumps(data, indent=2) + "\n", True
1013
+
1014
+
1015
+ def _toml_equal(a, b):
1016
+ """NaN-safe structural equality for parsed TOML objects."""
1017
+ if type(a) is not type(b):
1018
+ return False
1019
+ if isinstance(a, float):
1020
+ return (math.isnan(a) and math.isnan(b)) or a == b
1021
+ if isinstance(a, dict):
1022
+ return a.keys() == b.keys() and all(_toml_equal(a[k], b[k]) for k in a)
1023
+ if isinstance(a, list):
1024
+ return len(a) == len(b) and all(_toml_equal(x, y) for x, y in zip(a, b))
1025
+ return a == b
1026
+
1027
+
1028
+ def _toml_value(value):
1029
+ """Serialize a parsed TOML value back to valid inline TOML."""
1030
+ if isinstance(value, bool):
1031
+ return "true" if value else "false"
1032
+ if isinstance(value, int):
1033
+ return str(value)
1034
+ if isinstance(value, float):
1035
+ if math.isnan(value):
1036
+ return "nan"
1037
+ if math.isinf(value):
1038
+ return "inf" if value > 0 else "-inf"
1039
+ return repr(value)
1040
+ if isinstance(value, str):
1041
+ return hooks_snippet._toml_str(value)
1042
+ if isinstance(value, (datetime, date, dt_time)):
1043
+ return value.isoformat()
1044
+ if isinstance(value, list):
1045
+ return "[" + ", ".join(_toml_value(item) for item in value) + "]"
1046
+ if isinstance(value, dict):
1047
+ items = ", ".join(f"{hooks_snippet._toml_key(k)} = {_toml_value(v)}" for k, v in value.items())
1048
+ return "{ " + items + " }" if items else "{}"
1049
+ raise ValueError(f"unsupported TOML value type: {type(value).__name__}")
1050
+
1051
+
1052
+ def _lookup_path(mapping, path):
1053
+ cur = mapping
1054
+ for part in path:
1055
+ if not isinstance(cur, dict) or part not in cur:
1056
+ return None, False
1057
+ cur = cur[part]
1058
+ return cur, True
1059
+
1060
+
1061
+ def _render_codex_toml_block(server_cfg, extra_paths=None):
1062
+ text = hooks_snippet.codex_toml(server_cfg) + "\n"
1063
+ if extra_paths:
1064
+ for path, val in extra_paths:
1065
+ dotted = ".".join(hooks_snippet._toml_key(part) for part in path)
1066
+ text += f"{dotted} = {_toml_value(val)}\n"
1067
+ return text
1068
+
1069
+
1070
+ def _without_coldmemory_mcp(parsed):
1071
+ """Deep-copy a parsed Codex config without mcp_servers.coldmemory so we can prove nothing else changed."""
1072
+ cloned = copy.deepcopy(parsed)
1073
+ servers = cloned.get("mcp_servers")
1074
+ if isinstance(servers, dict):
1075
+ servers.pop("coldmemory", None)
1076
+ if not servers:
1077
+ cloned.pop("mcp_servers", None)
1078
+ return cloned
1079
+
1080
+
1081
+ def _parse_toml_header_line(line):
1082
+ """Return (is_array, raw_header) if line is a TOML [table] or [[array.table]] header, else None.
1083
+
1084
+ Properly skips brackets inside quoted keys such as [[skills."config[legacy]"]]."""
1085
+ s = line.lstrip()
1086
+ if not s.startswith("["):
1087
+ return None
1088
+ is_array = s.startswith("[[")
1089
+ i = 2 if is_array else 1
1090
+ n = len(s)
1091
+ start = i
1092
+ while i < n:
1093
+ ch = s[i]
1094
+ if ch == '"':
1095
+ i += 1
1096
+ while i < n:
1097
+ if s[i] == "\\":
1098
+ i += 2
1099
+ elif s[i] == '"':
1100
+ i += 1
1101
+ break
1102
+ else:
1103
+ i += 1
1104
+ continue
1105
+ if ch == "'":
1106
+ i += 1
1107
+ while i < n and s[i] != "'":
1108
+ i += 1
1109
+ i += 1
1110
+ continue
1111
+ if ch == "#":
1112
+ return None
1113
+ if ch == "]":
1114
+ if is_array:
1115
+ if i + 1 < n and s[i + 1] == "]":
1116
+ rest = s[i + 2:].strip()
1117
+ if not rest or rest.startswith("#"):
1118
+ return True, s[start:i].strip()
1119
+ return None
1120
+ rest = s[i + 1:].strip()
1121
+ if not rest or rest.startswith("#"):
1122
+ return False, s[start:i].strip()
1123
+ return None
1124
+ i += 1
1125
+ return None
1126
+
1127
+
1128
+ def _parse_toml_header_path(raw_header):
1129
+ """Parse a TOML table header into its unescaped key tuple using tomllib."""
1130
+ try:
1131
+ parsed = tomllib.loads(f"[{raw_header}]\n")
1132
+ except Exception:
1133
+ return None
1134
+ keys = []
1135
+ node = parsed
1136
+ while isinstance(node, dict) and len(node) == 1:
1137
+ key, node = next(iter(node.items()))
1138
+ keys.append(key)
1139
+ return tuple(keys)
1140
+
1141
+
1142
+ def _toml_bracket_delta(line, delim):
1143
+ """Return (net_bracket_delta, next_multiline_delim), ignoring brackets inside TOML strings and comments."""
1144
+ delta = 0
1145
+ i, n = 0, len(line)
1146
+ while i < n:
1147
+ if delim is None:
1148
+ ch = line[i]
1149
+ if ch == "#":
1150
+ break
1151
+ if line.startswith('"""', i):
1152
+ delim = '"""'
1153
+ i += 3
1154
+ continue
1155
+ if line.startswith("'''", i):
1156
+ delim = "'''"
1157
+ i += 3
1158
+ continue
1159
+ if ch == '"':
1160
+ i += 1
1161
+ while i < n:
1162
+ if line[i] == "\\":
1163
+ i += 2
1164
+ elif line[i] == '"':
1165
+ i += 1
1166
+ break
1167
+ else:
1168
+ i += 1
1169
+ continue
1170
+ if ch == "'":
1171
+ i += 1
1172
+ while i < n and line[i] != "'":
1173
+ i += 1
1174
+ i += 1
1175
+ continue
1176
+ if ch in ("[", "{"):
1177
+ delta += 1
1178
+ elif ch in ("]", "}"):
1179
+ delta -= 1
1180
+ i += 1
1181
+ elif delim == '"""':
1182
+ if line[i] == "\\":
1183
+ i += 2
1184
+ continue
1185
+ if line.startswith('"""', i):
1186
+ run = 3
1187
+ while i + run < n and line[i + run] == '"':
1188
+ run += 1
1189
+ if run <= 5:
1190
+ delim = None
1191
+ i += run
1192
+ continue
1193
+ i += 1
1194
+ else: # '''
1195
+ if line.startswith("'''", i):
1196
+ run = 3
1197
+ while i + run < n and line[i + run] == "'":
1198
+ run += 1
1199
+ if run <= 5:
1200
+ delim = None
1201
+ i += run
1202
+ continue
1203
+ i += 1
1204
+ return delta, delim
1205
+
1206
+
1207
+ def _split_toml_kv(line):
1208
+ """Split a TOML key = value line at the first unquoted '=' (handling quoted keys containing '=')."""
1209
+ i, n = 0, len(line)
1210
+ while i < n:
1211
+ ch = line[i]
1212
+ if ch == '"':
1213
+ i += 1
1214
+ while i < n:
1215
+ if line[i] == "\\":
1216
+ i += 2
1217
+ elif line[i] == '"':
1218
+ i += 1
1219
+ break
1220
+ else:
1221
+ i += 1
1222
+ continue
1223
+ if ch == "'":
1224
+ i += 1
1225
+ while i < n and line[i] != "'":
1226
+ i += 1
1227
+ i += 1
1228
+ continue
1229
+ if ch == "#":
1230
+ return None, None
1231
+ if ch == "=":
1232
+ return line[:i].strip(), line[i + 1:]
1233
+ i += 1
1234
+ return None, None
1235
+
1236
+
1237
+ def _toml_trailing_comment(text, start_ml=None):
1238
+ """Return any trailing TOML comment (with preceding horizontal whitespace, without newline) outside strings."""
1239
+ i, n = 0, len(text)
1240
+ ml = start_ml
1241
+ while i < n:
1242
+ if ml is not None:
1243
+ if ml == '"""' and text[i] == "\\":
1244
+ i += 2
1245
+ continue
1246
+ if text.startswith(ml, i):
1247
+ i += 3
1248
+ ml = None
1249
+ continue
1250
+ i += 1
1251
+ continue
1252
+ ch = text[i]
1253
+ if text.startswith('"""', i):
1254
+ ml = '"""'
1255
+ i += 3
1256
+ elif text.startswith("'''", i):
1257
+ ml = "'''"
1258
+ i += 3
1259
+ elif ch == '"':
1260
+ i += 1
1261
+ while i < n:
1262
+ if text[i] == "\\":
1263
+ i += 2
1264
+ elif text[i] == '"':
1265
+ i += 1
1266
+ break
1267
+ else:
1268
+ i += 1
1269
+ elif ch == "'":
1270
+ i += 1
1271
+ while i < n and text[i] != "'":
1272
+ i += 1
1273
+ i += 1
1274
+ elif ch == "#":
1275
+ start = i
1276
+ while start > 0 and text[start - 1] in " \t":
1277
+ start -= 1
1278
+ return text[start:].rstrip("\r\n")
1279
+ else:
1280
+ i += 1
1281
+ return ""
1282
+
1283
+
1284
+ def _codex_server_is_disabled(toml_text):
1285
+ """True when the parsed Codex TOML explicitly sets mcp_servers.coldmemory.enabled = false."""
1286
+ if not toml_text or not toml_text.strip():
1287
+ return False
1288
+ try:
1289
+ data = tomllib.loads(toml_text)
1290
+ except Exception:
1291
+ return False
1292
+ servers = data.get("mcp_servers")
1293
+ cm = servers.get("coldmemory") if isinstance(servers, dict) else None
1294
+ return isinstance(cm, dict) and cm.get("enabled") is False
1295
+
1296
+
1297
+ def _grok_list_disables_server(toml_text):
1298
+ try:
1299
+ listed = tomllib.loads(toml_text or "").get("disabled_mcp_servers")
1300
+ except Exception:
1301
+ return False
1302
+ return isinstance(listed, list) and "coldmemory" in listed
1303
+
1304
+
1305
+ def _merge_codex_toml(existing_text, server_cfg, path, *, force=False):
1306
+ parsed_before = {}
1307
+ existing_cm = None
1308
+ extra_before = {}
1309
+ replacing_remote = False
1310
+ desired_cfg = dict(server_cfg)
1311
+ if existing_text.strip():
1312
+ try:
1313
+ parsed_before = tomllib.loads(existing_text)
1314
+ except Exception as error:
1315
+ raise ValueError(f"{path} is not valid TOML: {error}") from error
1316
+ servers = parsed_before.get("mcp_servers")
1317
+ if servers is not None and not isinstance(servers, dict):
1318
+ raise ValueError(f"{path}: 'mcp_servers' must be a TOML table")
1319
+ existing_cm = servers.get("coldmemory") if isinstance(servers, dict) else None
1320
+ if existing_cm is not None and not isinstance(existing_cm, dict):
1321
+ raise ValueError(f"{path}: 'mcp_servers.coldmemory' must be a TOML table")
1322
+ if isinstance(existing_cm, dict):
1323
+ replacing_remote = _is_remote_mcp_entry(existing_cm)
1324
+ if replacing_remote and not force:
1325
+ raise ValueError(
1326
+ f"{path}: existing [mcp_servers.coldmemory] uses a non-stdio/remote transport; "
1327
+ "pass --force to replace it with local stdio"
1328
+ )
1329
+ if not replacing_remote and not force and _command_is_signed(existing_cm.get("args", [])):
1330
+ raise ValueError(
1331
+ f"{path}: existing [mcp_servers.coldmemory] uses a signed/custom scope; pass --force to replace it"
1332
+ )
1333
+ if (not replacing_remote and not force
1334
+ and not (existing_cm.get("command") == server_cfg["command"]
1335
+ and existing_cm.get("args") == server_cfg["args"])
1336
+ and _mcp_entry_is_customized(existing_cm)):
1337
+ raise ValueError(
1338
+ f"{path}: existing [mcp_servers.coldmemory] uses a custom launcher or arguments "
1339
+ "(e.g. wrapper command, --backend, --url, or --tools); update it manually or pass --force to replace it"
1340
+ )
1341
+ existing_env = existing_cm.get("env") if isinstance(existing_cm.get("env"), dict) else {}
1342
+ desired_cfg = {**server_cfg, "env": {**existing_env, **server_cfg["env"]}}
1343
+ if not replacing_remote:
1344
+ extra_before = {k: v for k, v in existing_cm.items() if k not in ("command", "args", "env")}
1345
+ if all(existing_cm.get(k) == desired_cfg[k] for k in ("command", "args", "env")):
1346
+ return existing_text, False
1347
+ else:
1348
+ # Forced remote conversion strips remote-only keys while preserving sibling env and transport-independent options.
1349
+ extra_before = {
1350
+ k: v for k, v in existing_cm.items()
1351
+ if k not in ("command", "args", "env") and k not in _REMOTE_ONLY_KEYS
1352
+ }
1353
+
1354
+ managed_root_keys = ({"command", "args", "env"} | _REMOTE_ONLY_KEYS) if replacing_remote else {"command", "args", "env"}
1355
+ managed_subtables = ({"env"} | _REMOTE_ONLY_KEYS) if replacing_remote else {"env"}
1356
+
1357
+ def _collect_inline_extra(paths):
1358
+ items = []
1359
+ for rel_path in paths:
1360
+ val, found = _lookup_path(extra_before, rel_path)
1361
+ if found:
1362
+ items.append((rel_path, val))
1363
+ return items
1364
+
1365
+ block = _render_codex_toml_block(desired_cfg)
1366
+ if not existing_text.strip():
1367
+ updated = block
1368
+ else:
1369
+ # Split strictly on TOML LF/CRLF newlines so UTF-8 paths containing U+2028/U+2029 stay intact.
1370
+ lines = re.findall(r"[^\n]*(?:\n|$)", existing_text)[:-1]
1371
+ out = []
1372
+ skip_mode = None # None | "root" | "subtable"
1373
+ current_table = ()
1374
+ inserted = False
1375
+ multiline = None
1376
+ preserved_extra_lines = []
1377
+ inline_extra_paths = []
1378
+ skipping_managed_key = False
1379
+ inline_servers_out_idx = None
1380
+ bracket_depth = 0
1381
+ outer_bracket_depth = 0
1382
+ for line in lines:
1383
+ hdr = _parse_toml_header_line(line) if (multiline is None and outer_bracket_depth == 0) else None
1384
+ if hdr is not None:
1385
+ if skip_mode == "root" and preserved_extra_lines:
1386
+ out.extend(preserved_extra_lines)
1387
+ preserved_extra_lines = []
1388
+ is_array, raw_header = hdr
1389
+ header_path = _parse_toml_header_path(raw_header)
1390
+ key_path = header_path if not is_array else None
1391
+ current_table = header_path or (("__array__",),)
1392
+ if key_path and len(key_path) >= 2 and key_path[:2] == ("mcp_servers", "coldmemory"):
1393
+ if len(key_path) == 2:
1394
+ if not inserted:
1395
+ out.append(_render_codex_toml_block(desired_cfg, extra_paths=_collect_inline_extra(inline_extra_paths)))
1396
+ inline_extra_paths.clear()
1397
+ inserted = True
1398
+ skip_mode = "root"
1399
+ skipping_managed_key = False
1400
+ inline_servers_out_idx = None
1401
+ bracket_depth = 0
1402
+ continue
1403
+ if key_path[2] in managed_subtables:
1404
+ # Skip managed subtable (e.g. env, http_headers) without prematurely inserting root table.
1405
+ skip_mode = "subtable"
1406
+ skipping_managed_key = False
1407
+ inline_servers_out_idx = None
1408
+ bracket_depth = 0
1409
+ continue
1410
+ if skip_mode is not None and out and out[-1].strip():
1411
+ out.append("\n")
1412
+ skip_mode = None
1413
+ skipping_managed_key = False
1414
+ inline_servers_out_idx = None
1415
+ bracket_depth = 0
1416
+ if skip_mode is None:
1417
+ # Handle inline `coldmemory = { ... }` (or dotted `mcp_servers.coldmemory = { ... }`) assignments.
1418
+ stripped = line.strip()
1419
+ if skipping_managed_key:
1420
+ delta, next_ml = _toml_bracket_delta(line, multiline)
1421
+ bracket_depth += delta
1422
+ if next_ml is None and bracket_depth <= 0:
1423
+ if inline_servers_out_idx is not None:
1424
+ trailing = _toml_trailing_comment(line, start_ml=multiline)
1425
+ if trailing:
1426
+ out[inline_servers_out_idx] = out[inline_servers_out_idx][:-1] + trailing + "\n"
1427
+ inline_servers_out_idx = None
1428
+ skipping_managed_key = False
1429
+ bracket_depth = 0
1430
+ elif (hdr is None and multiline is None and outer_bracket_depth == 0
1431
+ and stripped and not stripped.startswith("#")):
1432
+ key_part, rhs = _split_toml_kv(line)
1433
+ kv_path = _parse_toml_header_path(key_part) if key_part else None
1434
+ full_path = (*current_table, *kv_path) if kv_path else ()
1435
+ if full_path == ("mcp_servers",):
1436
+ # Top-level inline `mcp_servers = { ... }` cannot be extended with `[mcp_servers.coldmemory]`.
1437
+ updated_servers = {
1438
+ k: v for k, v in (parsed_before.get("mcp_servers") or {}).items() if k != "coldmemory"
1439
+ }
1440
+ updated_servers["coldmemory"] = {**desired_cfg, **extra_before}
1441
+ indent = line[:len(line) - len(line.lstrip(" \t"))]
1442
+ delta, next_ml = _toml_bracket_delta(rhs, None)
1443
+ bracket_depth = delta
1444
+ if next_ml is not None or bracket_depth > 0:
1445
+ out.append(f"{indent}mcp_servers = {_toml_value(updated_servers)}\n")
1446
+ inline_servers_out_idx = len(out) - 1
1447
+ skipping_managed_key = True
1448
+ else:
1449
+ trailing = _toml_trailing_comment(rhs)
1450
+ out.append(f"{indent}mcp_servers = {_toml_value(updated_servers)}{trailing}\n")
1451
+ inserted = True
1452
+ elif (current_table in ((), ("mcp_servers",))
1453
+ and len(full_path) >= 2 and full_path[:2] == ("mcp_servers", "coldmemory")):
1454
+ if len(full_path) == 2:
1455
+ for k in extra_before:
1456
+ if (k,) not in inline_extra_paths:
1457
+ inline_extra_paths.append((k,))
1458
+ elif full_path[2] not in managed_root_keys:
1459
+ rel_path = full_path[2:]
1460
+ if rel_path not in inline_extra_paths:
1461
+ inline_extra_paths.append(rel_path)
1462
+ delta, next_ml = _toml_bracket_delta(rhs, None)
1463
+ bracket_depth = delta
1464
+ if next_ml is not None or bracket_depth > 0:
1465
+ skipping_managed_key = True
1466
+ else:
1467
+ out.append(line)
1468
+ else:
1469
+ out.append(line)
1470
+ elif skip_mode == "root":
1471
+ stripped = line.strip()
1472
+ if skipping_managed_key:
1473
+ delta, next_ml = _toml_bracket_delta(line, multiline)
1474
+ bracket_depth += delta
1475
+ if next_ml is None and bracket_depth <= 0:
1476
+ skipping_managed_key = False
1477
+ bracket_depth = 0
1478
+ elif multiline is None and outer_bracket_depth == 0 and stripped and not stripped.startswith("#"):
1479
+ key_part, rhs = _split_toml_kv(line)
1480
+ key_path = _parse_toml_header_path(key_part) if key_part else None
1481
+ top_key = key_path[0] if key_path else None
1482
+ if key_part is not None and top_key in managed_root_keys:
1483
+ delta, next_ml = _toml_bracket_delta(rhs, None)
1484
+ bracket_depth = delta
1485
+ if next_ml is not None or bracket_depth > 0:
1486
+ skipping_managed_key = True
1487
+ else:
1488
+ preserved_extra_lines.append(line)
1489
+ elif stripped or preserved_extra_lines:
1490
+ preserved_extra_lines.append(line)
1491
+ if hdr is None:
1492
+ delta, next_ml = _toml_bracket_delta(line, multiline)
1493
+ outer_bracket_depth = max(0, outer_bracket_depth + delta)
1494
+ multiline = next_ml
1495
+ if skip_mode == "root" and preserved_extra_lines:
1496
+ out.extend(preserved_extra_lines)
1497
+ if not inserted:
1498
+ if out and not out[-1].endswith("\n"):
1499
+ out[-1] = out[-1] + "\n"
1500
+ if out and out[-1].strip():
1501
+ out.append("\n")
1502
+ out.append(_render_codex_toml_block(desired_cfg, extra_paths=_collect_inline_extra(inline_extra_paths)))
1503
+ updated = "".join(out)
1504
+
1505
+ try:
1506
+ verified = tomllib.loads(updated)
1507
+ except Exception as error:
1508
+ raise ValueError(
1509
+ f"could not safely update {path} (conflicting mcp_servers.coldmemory entry): {error}"
1510
+ ) from error
1511
+ updated_cm = verified.get("mcp_servers", {}).get("coldmemory")
1512
+ if not isinstance(updated_cm, dict) or not all(updated_cm.get(k) == desired_cfg[k] for k in ("command", "args", "env")):
1513
+ raise ValueError(f"could not verify updated [mcp_servers.coldmemory] in {path}")
1514
+ extra_after = {k: v for k, v in updated_cm.items() if k not in ("command", "args", "env")}
1515
+ if replacing_remote and any(k in extra_after for k in _REMOTE_ONLY_KEYS):
1516
+ raise ValueError(f"could not remove all remote transport keys from [mcp_servers.coldmemory] in {path}")
1517
+ if not _toml_equal(extra_before, extra_after):
1518
+ raise ValueError(
1519
+ f"refusing to drop custom options in [mcp_servers.coldmemory] of {path}; pass --force to replace it"
1520
+ )
1521
+ if not _toml_equal(_without_coldmemory_mcp(parsed_before), _without_coldmemory_mcp(verified)):
1522
+ raise ValueError(f"refusing to rewrite {path}: unrelated TOML settings would have changed")
1523
+ return updated, updated != existing_text
1524
+
1525
+
1526
+ def _unique_backup_path(path):
1527
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
1528
+ candidate = path.with_name(f"{path.name}.coldmemory-bak-{stamp}")
1529
+ if not candidate.exists():
1530
+ return candidate
1531
+ for idx in range(1, 1000):
1532
+ numbered = path.with_name(f"{path.name}.coldmemory-bak-{stamp}-{idx}")
1533
+ if not numbered.exists():
1534
+ return numbered
1535
+ raise ValueError(f"could not allocate backup path for {path}")
1536
+
1537
+
1538
+ def _file_snapshot(path, *, locked_fd=None):
1539
+ if locked_fd is not None:
1540
+ st = os.fstat(locked_fd)
1541
+ if not stat.S_ISREG(st.st_mode):
1542
+ raise ValueError(f"refusing to edit non-regular config file: {path}")
1543
+ os.lseek(locked_fd, 0, os.SEEK_SET)
1544
+ chunks = []
1545
+ while chunk := os.read(locked_fd, 65536):
1546
+ chunks.append(chunk)
1547
+ raw_bytes = b"".join(chunks)
1548
+ raw_text = raw_bytes.decode("utf-8")
1549
+ return (st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns, raw_bytes), raw_bytes, raw_text, stat.S_IMODE(st.st_mode)
1550
+ if path.is_symlink():
1551
+ raise ValueError(f"refusing to edit symlinked config file: {path}")
1552
+ if not path.exists():
1553
+ return None, b"", "", 0o600
1554
+ st = os.lstat(path)
1555
+ if not stat.S_ISREG(st.st_mode):
1556
+ raise ValueError(f"refusing to edit non-regular config file: {path}")
1557
+ raw_bytes = path.read_bytes()
1558
+ raw_text = raw_bytes.decode("utf-8")
1559
+ return (st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns, raw_bytes), raw_bytes, raw_text, stat.S_IMODE(st.st_mode)
1560
+
1561
+
1562
+ @contextmanager
1563
+ def _lock_existing_file(path):
1564
+ """Hold an exclusive advisory lock on an existing regular config file across read -> backup -> replace."""
1565
+ try:
1566
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1567
+ except FileNotFoundError:
1568
+ yield None
1569
+ return
1570
+ except OSError as error:
1571
+ if error.errno == errno.ELOOP:
1572
+ raise ValueError(f"refusing to edit symlinked config file: {path}") from error
1573
+ raise
1574
+ try:
1575
+ st = os.fstat(fd)
1576
+ if not stat.S_ISREG(st.st_mode):
1577
+ raise ValueError(f"refusing to edit non-regular config file: {path}")
1578
+ fcntl.flock(fd, fcntl.LOCK_EX)
1579
+ yield fd
1580
+ finally:
1581
+ os.close(fd)
1582
+
1583
+
1584
+ def _create_backup_file(path, before_bytes, mode):
1585
+ """Atomically allocate and write a unique timestamped backup file owned by this attempt."""
1586
+ for _ in range(100):
1587
+ candidate = _unique_backup_path(path)
1588
+ try:
1589
+ bak_fd = os.open(candidate, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
1590
+ except FileExistsError:
1591
+ continue
1592
+ try:
1593
+ with os.fdopen(bak_fd, "wb") as bak_stream:
1594
+ bak_stream.write(before_bytes)
1595
+ bak_stream.flush()
1596
+ os.fsync(bak_stream.fileno())
1597
+ os.chmod(candidate, mode)
1598
+ return candidate
1599
+ except Exception:
1600
+ candidate.unlink(missing_ok=True)
1601
+ raise
1602
+ raise ValueError(f"could not create unique backup file for {path}")
1603
+
1604
+
1605
+ def _preflight_file(path, merge_fn, *, max_attempts=5):
1606
+ """Read, lock, and merge one target file once; returns (preview_report, cached_preflight, new_text)."""
1607
+ for _ in range(max_attempts):
1608
+ with _lock_existing_file(path) as locked_fd:
1609
+ before_sig, _, before_text, _ = _file_snapshot(path, locked_fd=locked_fd)
1610
+ if (locked_fd is None) != (before_sig is None):
1611
+ continue
1612
+ new_text, changed = merge_fn(before_text)
1613
+ status = "unchanged" if not changed else ("would update" if before_sig is not None else "would create")
1614
+ cached = (before_sig, new_text, changed)
1615
+ return {"path": path, "status": status, "backup": None}, cached, new_text
1616
+ with _lock_existing_file(path) as locked_fd:
1617
+ before_sig, _, before_text, _ = _file_snapshot(path, locked_fd=locked_fd)
1618
+ new_text, changed = merge_fn(before_text)
1619
+ status = "unchanged" if not changed else ("would update" if before_sig is not None else "would create")
1620
+ cached = (before_sig, new_text, changed) if (locked_fd is None) == (before_sig is None) else None
1621
+ return {"path": path, "status": status, "backup": None}, cached, new_text
1622
+
1623
+
1624
+ def _apply_file_cas(path, merge_fn, *, preflight=None, max_attempts=5):
1625
+ """Merge and atomically replace a config file with a timestamped backup.
1626
+
1627
+ Reuses a preflight snapshot when the file has not changed on disk; re-merges under
1628
+ the lock if the file changed since preflight. Uses atomic no-replace creation (os.link)
1629
+ for absent files, advisory flock on existing files, and atomic O_EXCL backups."""
1630
+ cached = preflight
1631
+ for _ in range(max_attempts):
1632
+ with _lock_existing_file(path) as locked_fd:
1633
+ before_sig, before_bytes, before_text, mode = _file_snapshot(path, locked_fd=locked_fd)
1634
+ if (locked_fd is None) != (before_sig is None):
1635
+ cached = None
1636
+ continue
1637
+ if locked_fd is not None:
1638
+ try:
1639
+ path_st = os.lstat(path)
1640
+ except FileNotFoundError:
1641
+ cached = None
1642
+ continue
1643
+ if not stat.S_ISREG(path_st.st_mode):
1644
+ raise ValueError(f"refusing to edit non-regular config file: {path}")
1645
+ if path_st.st_ino != before_sig[0]:
1646
+ cached = None
1647
+ continue
1648
+ if cached is not None and cached[0] == before_sig:
1649
+ _, new_text, changed = cached
1650
+ else:
1651
+ new_text, changed = merge_fn(before_text)
1652
+ cached = None
1653
+ if not changed:
1654
+ return {"path": path, "status": "unchanged", "backup": None, "_text": new_text}
1655
+ new_bytes = new_text.encode("utf-8")
1656
+ path.parent.mkdir(parents=True, exist_ok=True)
1657
+ tmp = path.with_name(f".{path.name}.coldmemory-{os.getpid()}.tmp")
1658
+ backup = None
1659
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
1660
+ try:
1661
+ with os.fdopen(fd, "wb") as stream:
1662
+ stream.write(new_bytes)
1663
+ stream.flush()
1664
+ os.fsync(stream.fileno())
1665
+ os.chmod(tmp, mode)
1666
+ if before_sig is None:
1667
+ # Atomic no-replace creation: if a concurrent writer created path first, retry the merge.
1668
+ try:
1669
+ os.link(tmp, path)
1670
+ except FileExistsError:
1671
+ tmp.unlink(missing_ok=True)
1672
+ continue
1673
+ tmp.unlink(missing_ok=True)
1674
+ return {
1675
+ "path": path, "status": "created", "backup": None, "_text": new_text,
1676
+ "_rollback": (path, "created", None, new_bytes, mode, None),
1677
+ }
1678
+ backup = _create_backup_file(path, before_bytes, mode)
1679
+ now_sig, _, _, _ = _file_snapshot(path)
1680
+ if now_sig != before_sig:
1681
+ tmp.unlink(missing_ok=True)
1682
+ backup.unlink(missing_ok=True)
1683
+ backup = None
1684
+ continue
1685
+ os.replace(tmp, path)
1686
+ return {
1687
+ "path": path, "status": "updated", "backup": backup, "_text": new_text,
1688
+ "_rollback": (path, "updated", backup, new_bytes, mode, before_bytes),
1689
+ }
1690
+ except Exception:
1691
+ tmp.unlink(missing_ok=True)
1692
+ if backup is not None:
1693
+ backup.unlink(missing_ok=True)
1694
+ raise
1695
+ raise ValueError(f"{path} changed repeatedly during update; retry after concurrent edits finish")
1696
+
1697
+
1698
+ @contextmanager
1699
+ def _client_apply_lock(lock_path):
1700
+ """Serialize paired config updates for one client so MCP and hooks never point at different stores."""
1701
+ if lock_path is None:
1702
+ yield
1703
+ return
1704
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
1705
+ fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
1706
+ try:
1707
+ st = os.fstat(fd)
1708
+ if not stat.S_ISREG(st.st_mode):
1709
+ raise ValueError(f"refusing to lock non-regular file: {lock_path}")
1710
+ fcntl.flock(fd, fcntl.LOCK_EX)
1711
+ try:
1712
+ yield
1713
+ finally:
1714
+ fcntl.flock(fd, fcntl.LOCK_UN)
1715
+ finally:
1716
+ os.close(fd)
1717
+
1718
+
1719
+ def _finalize_client_report(client, summary, files, notes, file_texts):
1720
+ final_summary = summary
1721
+ final_notes = list(notes)
1722
+ if client in ("codex", "grok"):
1723
+ name = "Codex" if client == "codex" else "Grok"
1724
+ for path, text in file_texts:
1725
+ if path.name == "config.toml" and _codex_server_is_disabled(text):
1726
+ final_summary = (
1727
+ "1-tool MCP (memory_ask, 234 tok) configured but DISABLED (enabled = false preserved)"
1728
+ + (" + push hooks written (run /hooks in Codex to trust)" if client == "codex" else "")
1729
+ )
1730
+ final_notes.insert(
1731
+ 0,
1732
+ f"Warning: [mcp_servers.coldmemory] is disabled (enabled = false preserved in {path}); "
1733
+ f"set enabled = true to enable memory_ask in {name}.",
1734
+ )
1735
+ break
1736
+ if client == "grok" and path.name == "config.toml" and _grok_list_disables_server(text):
1737
+ final_summary = "1-tool MCP (memory_ask, 234 tok) configured but DISABLED (disabled_mcp_servers preserved)"
1738
+ final_notes.insert(
1739
+ 0,
1740
+ f"Warning: disabled_mcp_servers in {path} lists coldmemory; "
1741
+ "run `grok mcp enable coldmemory` to enable memory_ask in Grok.",
1742
+ )
1743
+ break
1744
+ return {"client": client, "summary": final_summary, "files": files, "notes": final_notes}
1745
+
1746
+
1747
+ def _preflight_clients(clients, store_path, package_root, *, force=False, home=None, env=None, python=sys.executable):
1748
+ """Build the client plan and preflight every target file once, returning (plan_entries, preview_reports)."""
1749
+ env = os.environ if env is None else env
1750
+ home_dir = Path.home() if home is None else Path(home)
1751
+ server_cfg = _mcp_server_config(store_path, package_root, python=python)
1752
+ push_hooks = _push_hooks_dict(store_path, package_root, python=python)
1753
+
1754
+ plans = []
1755
+ for client in clients:
1756
+ if client == "claude":
1757
+ mcp_path = home_dir / ".claude.json"
1758
+ settings_path = home_dir / ".claude" / "settings.json"
1759
+ plans.append((
1760
+ "claude",
1761
+ "1-tool MCP (memory_ask, 234 tok) + compaction-proof push hooks (automatic)",
1762
+ [
1763
+ (mcp_path, lambda text, p=mcp_path: _merge_json_mcp(text, server_cfg, p, force=force)),
1764
+ (settings_path, lambda text, p=settings_path: _merge_json_hooks(text, push_hooks, p, force=force)),
1765
+ ],
1766
+ [],
1767
+ home_dir / ".claude" / ".coldmemory.lock",
1768
+ ))
1769
+ elif client == "codex":
1770
+ codex_dir = _codex_home(home_dir, env)
1771
+ toml_path = codex_dir / "config.toml"
1772
+ hooks_path = codex_dir / "hooks.json"
1773
+ plans.append((
1774
+ "codex",
1775
+ "1-tool MCP (memory_ask, 234 tok) + push hooks written (run /hooks in Codex to trust)",
1776
+ [
1777
+ (toml_path, lambda text, p=toml_path: _merge_codex_toml(text, server_cfg, p, force=force)),
1778
+ (hooks_path, lambda text, p=hooks_path: _merge_json_hooks(text, push_hooks, p, force=force)),
1779
+ ],
1780
+ [
1781
+ "In Codex, run /hooks once to review and trust the new or updated hooks before they activate.",
1782
+ ],
1783
+ codex_dir / ".coldmemory.lock",
1784
+ ))
1785
+ elif client == "grok":
1786
+ grok_dir = _grok_home(home_dir, env)
1787
+ grok_toml = grok_dir / "config.toml"
1788
+ plans.append((
1789
+ "grok",
1790
+ "1-tool MCP (memory_ask, 234 tok); Grok loads its instructions natively (no hooks)",
1791
+ [(grok_toml, lambda text, p=grok_toml: _merge_codex_toml(text, server_cfg, p, force=force))],
1792
+ [
1793
+ "Grok's session, prompt and compact hooks cannot inject model context, so no hooks are written; "
1794
+ "the MCP initialize instructions ground every session.",
1795
+ ],
1796
+ grok_dir / ".coldmemory.lock",
1797
+ ))
1798
+ elif client == "openbot":
1799
+ form = hooks_snippet.snippet("openbot", store_path, package_root=package_root, python=python,
1800
+ scope="private", local_unsigned=True, tools=DEFAULT_TOOLS)
1801
+ openbot_notes = [
1802
+ "Manual step required — in OpenBot Desktop (Settings -> MCP servers -> Connect to a custom MCP), paste:",
1803
+ *[f" {line}" for line in form.splitlines()],
1804
+ ]
1805
+ if "claude" in clients:
1806
+ openbot_notes.append(
1807
+ f"OpenBot Claude agents automatically reuse push hooks from {home_dir / '.claude' / 'settings.json'}."
1808
+ )
1809
+ else:
1810
+ openbot_notes.append(
1811
+ "Optional: also include --clients claude,openbot --apply if your OpenBot Claude agents use ~/.claude/settings.json push hooks."
1812
+ )
1813
+ plans.append((
1814
+ "openbot",
1815
+ "Desktop MCP form fields (memory_ask; manual paste in OpenBot UI)",
1816
+ [],
1817
+ openbot_notes,
1818
+ None,
1819
+ ))
1820
+ elif client == "hermes":
1821
+ hermes_dir = _hermes_home(home_dir, env)
1822
+ src_dir = _hermes_source_dir()
1823
+ dest_dir = hermes_dir / "plugins" / "coldmemory"
1824
+ hermes_ops = []
1825
+ if src_dir is not None:
1826
+ for name in HERMES_FILES:
1827
+ src_text = (src_dir / name).read_text(encoding="utf-8")
1828
+ dest_file = dest_dir / name
1829
+ hermes_ops.append((dest_file, lambda current, desired=src_text: (desired, current != desired)))
1830
+ plans.append((
1831
+ "hermes",
1832
+ "Native Hermes MemoryProvider plugin (files copied; env + config.yaml manual step remaining)",
1833
+ hermes_ops,
1834
+ [
1835
+ "Manual step remaining — set in your Hermes environment and config:",
1836
+ f" export COLDMEMORY_STORE={shlex.quote(str(store_path))}",
1837
+ " export COLDMEMORY_SCOPE=private",
1838
+ " export COLDMEMORY_LOCAL_UNSIGNED=1",
1839
+ " unset COLDMEMORY_TRUST_KEY # clear any previous signed-store trust key",
1840
+ f" export PYTHONPATH={shlex.quote(str(package_root))}${{PYTHONPATH:+:$PYTHONPATH}} # keep ahead of $HERMES_HOME/plugins (even when installed, never put $HERMES_HOME/plugins first on PYTHONPATH)",
1841
+ f" # in {hermes_dir / 'config.yaml'}:",
1842
+ " memory:",
1843
+ " provider: coldmemory",
1844
+ ],
1845
+ hermes_dir / ".coldmemory.lock" if hermes_ops else None,
1846
+ ))
1847
+
1848
+ preflighted = []
1849
+ preview_reports = []
1850
+ for client, summary, ops, notes, lock_path in plans:
1851
+ if client == "hermes" and not ops:
1852
+ files = [{"path": _hermes_home(home_dir, env) / "plugins" / "coldmemory",
1853
+ "status": "source plugin files not found", "backup": None}]
1854
+ preflighted.append((client, summary, [], notes, files, None))
1855
+ preview_reports.append({"client": client, "summary": summary, "files": files, "notes": notes})
1856
+ else:
1857
+ op_plans = []
1858
+ files = []
1859
+ file_texts = []
1860
+ for path, merge_fn in ops:
1861
+ item, cached, new_text = _preflight_file(path, merge_fn)
1862
+ files.append(item)
1863
+ file_texts.append((path, new_text))
1864
+ op_plans.append((path, merge_fn, cached))
1865
+ preflighted.append((client, summary, op_plans, notes, None, lock_path))
1866
+ preview_reports.append(_finalize_client_report(client, summary, files, notes, file_texts))
1867
+ return preflighted, preview_reports
1868
+
1869
+
1870
+ def _rollback_client_write(path, status, backup, written_bytes, mode, prev_bytes):
1871
+ """Restore one file written during a failed paired client update if it still holds this run's exact bytes."""
1872
+ try:
1873
+ with _lock_existing_file(path) as locked_fd:
1874
+ if locked_fd is None:
1875
+ return False
1876
+ cur_sig, cur_bytes, _, _ = _file_snapshot(path, locked_fd=locked_fd)
1877
+ path_st = os.lstat(path)
1878
+ if not stat.S_ISREG(path_st.st_mode) or path_st.st_ino != cur_sig[0]:
1879
+ return False
1880
+ if cur_bytes != written_bytes:
1881
+ return False
1882
+ if status == "created":
1883
+ now_sig, now_bytes, _, _ = _file_snapshot(path)
1884
+ if now_sig != cur_sig or now_bytes != written_bytes:
1885
+ return False
1886
+ path.unlink()
1887
+ return True
1888
+ tmp = path.with_name(f".{path.name}.coldmemory-rb-{os.getpid()}.tmp")
1889
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
1890
+ try:
1891
+ with os.fdopen(fd, "wb") as stream:
1892
+ stream.write(prev_bytes)
1893
+ stream.flush()
1894
+ os.fsync(stream.fileno())
1895
+ os.chmod(tmp, mode)
1896
+ now_sig, now_bytes, _, _ = _file_snapshot(path)
1897
+ if now_sig != cur_sig or now_bytes != written_bytes:
1898
+ tmp.unlink(missing_ok=True)
1899
+ return False
1900
+ os.replace(tmp, path)
1901
+ except Exception:
1902
+ tmp.unlink(missing_ok=True)
1903
+ raise
1904
+ if backup is not None:
1905
+ backup.unlink(missing_ok=True)
1906
+ return True
1907
+ except (OSError, ValueError):
1908
+ return False
1909
+
1910
+
1911
+ def _apply_preflighted_clients(preflighted):
1912
+ """Apply a preflighted client plan, serializing paired config updates per client.
1913
+
1914
+ Reuses cached merges when files are unchanged on disk. If a later file in a client's
1915
+ paired update fails, restores earlier files written for that client when they still hold
1916
+ this run's exact bytes, and reports any remaining modified files and their backup paths."""
1917
+ reports = []
1918
+ completed = []
1919
+ for client, summary, op_plans, notes, static_files, lock_path in preflighted:
1920
+ file_texts = []
1921
+ if static_files is not None:
1922
+ files = static_files
1923
+ else:
1924
+ files = []
1925
+ client_written = []
1926
+ rolled_back = []
1927
+ unrolled = []
1928
+ try:
1929
+ with _client_apply_lock(lock_path if op_plans else None):
1930
+ try:
1931
+ for path, merge_fn, cached in op_plans:
1932
+ item = _apply_file_cas(path, merge_fn, preflight=cached)
1933
+ rb = item.pop("_rollback", None)
1934
+ text = item.pop("_text", "")
1935
+ files.append(item)
1936
+ file_texts.append((path, text))
1937
+ if rb is not None:
1938
+ client_written.append(rb)
1939
+ except (OSError, ValueError):
1940
+ for rb in reversed(client_written):
1941
+ if _rollback_client_write(*rb):
1942
+ rolled_back.append(rb[0])
1943
+ else:
1944
+ unrolled.append((rb[0], rb[1], rb[2]))
1945
+ unrolled.reverse()
1946
+ raise
1947
+ except (OSError, ValueError) as error:
1948
+ remaining = completed + unrolled
1949
+ notes_err = []
1950
+ if rolled_back:
1951
+ notes_err.append("rolled back " + ", ".join(str(p) for p in rolled_back))
1952
+ if remaining:
1953
+ detail = "; ".join(
1954
+ f"{st} {p}" + (f" (backup: {bak})" if bak else "")
1955
+ for p, st, bak in remaining
1956
+ )
1957
+ notes_err.append(f"earlier client files already modified: {detail}")
1958
+ if notes_err:
1959
+ raise ValueError(f"{error} ({'; '.join(notes_err)})") from error
1960
+ raise
1961
+ for rb in client_written:
1962
+ completed.append((rb[0], rb[1], rb[2]))
1963
+ reports.append(_finalize_client_report(client, summary, files, notes, file_texts))
1964
+ return reports
1965
+
1966
+
1967
+ def _format_source_args(sources):
1968
+ return " ".join(shlex.quote(f"{s.kind}:{s.root}") for s in sources)
1969
+
1970
+
1971
+ def _fresh_note_path(folder):
1972
+ base = Path(folder)
1973
+ candidate = base / "first-note.md"
1974
+ if not os.path.lexists(candidate):
1975
+ return candidate
1976
+ for idx in range(2, 1000):
1977
+ numbered = base / f"first-note-{idx}.md"
1978
+ if not os.path.lexists(numbered):
1979
+ return numbered
1980
+ return base / f"first-note-{os.getpid()}.md"
1981
+
1982
+
1983
+ def _format_retry_flags(args):
1984
+ parts = []
1985
+ if args.store:
1986
+ parts += ["--store", shlex.quote(str(args.store))]
1987
+ if args.id:
1988
+ parts += ["--id", shlex.quote(str(args.id))]
1989
+ if args.clients and args.clients != "auto":
1990
+ parts += ["--clients", shlex.quote(str(args.clients))]
1991
+ if args.force:
1992
+ parts.append("--force")
1993
+ if args.dry_run:
1994
+ parts.append("--dry-run")
1995
+ elif args.apply:
1996
+ parts.append("--apply")
1997
+ if args.query:
1998
+ parts += ["--query", shlex.quote(str(args.query))]
1999
+ return (" " + " ".join(parts)) if parts else ""
2000
+
2001
+
2002
+ def _cli_invocation(*, python=sys.executable, argv0=None, env=None, which=shutil.which):
2003
+ """Return a copy-pasteable ColdMemory CLI command matching the active entrypoint or interpreter."""
2004
+ prog = (sys.argv[0] if sys.argv else "") if argv0 is None else argv0
2005
+ if prog and Path(prog).name == "coldmemory":
2006
+ if os.sep in prog:
2007
+ return shlex.quote(prog)
2008
+ if which(prog, path=(env or os.environ).get("PATH", "")):
2009
+ return shlex.quote(prog)
2010
+ sibling = Path(python).with_name("coldmemory")
2011
+ if sibling.is_file() and os.access(sibling, os.X_OK):
2012
+ return shlex.quote(str(sibling))
2013
+ return f"{shlex.quote(str(python))} -m coldmemory"
2014
+
2015
+
2016
+ def _empty_vault_message(sources, skipped, args, *, cli="coldmemory"):
2017
+ folders = ", ".join(s.root for s in sources)
2018
+ target_file = _fresh_note_path(sources[0].root)
2019
+ lines = [
2020
+ f"ColdMemory found 0 readable notes in {folders}.",
2021
+ f"Indexed extensions: {', '.join(ingest.SUFFIXES)} (hidden files/folders and symlinks are skipped).",
2022
+ ]
2023
+ if skipped:
2024
+ reasons = ", ".join(f"{count} {reason}" for reason, count in sorted(skipped.items()))
2025
+ lines.append(f"Skipped files: {reasons}.")
2026
+ lines += [
2027
+ "",
2028
+ "Add a first note (without overwriting existing files) and re-run:",
2029
+ f" (set -o noclobber; printf '# First Note\\n\\n## Decision\\n\\nUse UTC timestamps everywhere.\\n' > {shlex.quote(str(target_file))})",
2030
+ ]
2031
+ if sources[0].kind == "repo":
2032
+ lines.append(f" git -C {shlex.quote(sources[0].root)} add {shlex.quote(target_file.name)}")
2033
+ lines.append(f" {cli} init {_format_source_args(sources)}{_format_retry_flags(args)}")
2034
+ return "\n".join(lines)
2035
+
2036
+
2037
+ def run(args, *, home=None, env=None, python=sys.executable, which=shutil.which, stdout=None, stderr=None):
2038
+ started = time.perf_counter()
2039
+ out = sys.stdout if stdout is None else stdout
2040
+ err = sys.stderr if stderr is None else stderr
2041
+ env = os.environ if env is None else env
2042
+ home_dir = Path.home() if home is None else Path(home)
2043
+ cli = _cli_invocation(python=python, env=env, which=which)
2044
+ store_path = (Path(args.store).expanduser().absolute()
2045
+ if args.store else default_store(home=home_dir, env=env))
2046
+ sources = _resolve_sources(args.vault)
2047
+ _check_store_outside_sources(store_path, sources)
2048
+
2049
+ if store_path.exists():
2050
+ try:
2051
+ spec._check_private(store_path, directory=True)
2052
+ except ValueError as error:
2053
+ raise ValueError(f"{store_path}: {error} (run: chmod 700 {shlex.quote(str(store_path))})") from error
2054
+
2055
+ clients = resolve_clients(args.clients, home=home_dir, env=env, which=which)
2056
+ package_root = _package_root()
2057
+
2058
+ # Single-pass preflight of client configs BEFORE refreshing notes or touching the store.
2059
+ preflighted_plan, preview_reports = _preflight_clients(
2060
+ clients, store_path, package_root, force=args.force, home=home_dir, env=env, python=python
2061
+ )
2062
+
2063
+ if args.dry_run:
2064
+ bundle_id, id_state, _ = _resolve_bundle_id(store_path, args.id, sources, force=args.force)
2065
+ corpus = ingest.Corpus(sources)
2066
+ corpus.cache = None # Never write note cache files during --dry-run.
2067
+ corpus.refresh()
2068
+ if not corpus.notes:
2069
+ print(_empty_vault_message(sources, corpus.skipped, args, cli=cli), file=err)
2070
+ return 1
2071
+ elapsed = time.perf_counter() - started
2072
+ print(f"ColdMemory dry run ({elapsed:.2f}s) — no store or client files were written", file=out)
2073
+ print(f" Store: {store_path} (0700)", file=out)
2074
+ print(f" Bundle: {bundle_id} ({len(corpus.notes)} readable notes, {id_state})", file=out)
2075
+ for src in sources:
2076
+ print(f" Source: {src.kind}:{src.root}", file=out)
2077
+ _print_client_reports(preview_reports, apply_changes=False, dry_run=True, sources=sources, store_path=store_path,
2078
+ bundle_id=bundle_id, clients_arg=args.clients, force=args.force, query=args.query,
2079
+ cli=cli, out=out)
2080
+ return 0
2081
+
2082
+ initial_corpus = None
2083
+ if not store_path.exists():
2084
+ initial_corpus = ingest.Corpus(sources)
2085
+ initial_corpus.refresh()
2086
+ if not initial_corpus.notes:
2087
+ print(_empty_vault_message(sources, initial_corpus.skipped, args, cli=cli), file=err)
2088
+ return 1
2089
+
2090
+ _ensure_private_store(store_path)
2091
+ verified_result = {}
2092
+
2093
+ def verify_before_activate(candidate, locked_corpus):
2094
+ q, ans, ok = _verify_candidate(candidate, locked_corpus, custom_query=args.query)
2095
+ if not ok:
2096
+ raise _SmokeVerificationError(q, candidate.id, candidate.revision)
2097
+ verified_result["query"] = q
2098
+ verified_result["answer"] = ans
2099
+
2100
+ empty_skipped = None
2101
+ with _store_init_lock(store_path):
2102
+ bundle_id, id_state, existing_bundle = _resolve_bundle_id(store_path, args.id, sources, force=args.force)
2103
+ reused_revision = False
2104
+ bundle = None
2105
+ active_bundle = None
2106
+ home = spec._home(store_path, bundle_id, create=True)
2107
+ try:
2108
+ # Reuse the pre-store scan for a brand-new free bundle; otherwise do a single locked corpus walk.
2109
+ # Lock files (.init.lock and <bundle>/lock) are never unlinked so concurrent waiters always share the same inode.
2110
+ with spec._locked(home):
2111
+ if initial_corpus is not None and id_state == "free":
2112
+ corpus = initial_corpus
2113
+ else:
2114
+ corpus = ingest.Corpus(sources)
2115
+ corpus.refresh()
2116
+ if not corpus.notes:
2117
+ empty_skipped = dict(corpus.skipped)
2118
+ else:
2119
+ if id_state in ("same", "overwrite") and existing_bundle is not None:
2120
+ live = spec.load(store_path, bundle_id)
2121
+ same_live = (
2122
+ live.manifest.get("scope") == "private"
2123
+ and live.manifest.get("version") == 1
2124
+ and _source_signature(live.sources) == _source_signature(sources)
2125
+ )
2126
+ if same_live and _bundle_unchanged(store_path, live, corpus):
2127
+ bundle = live
2128
+ active_bundle = live
2129
+ reused_revision = True
2130
+ verify_before_activate(bundle, corpus)
2131
+ elif live.trained and (same_live or args.force) and (
2132
+ staged := _find_unchanged_revision(store_path, bundle_id, sources, corpus)) is not None:
2133
+ bundle = staged
2134
+ active_bundle = live
2135
+ reused_revision = True
2136
+ verify_before_activate(bundle, corpus)
2137
+ if bundle is None:
2138
+ bundle = spec._compile_bundle_locked(
2139
+ store_path, bundle_id, sources, "private",
2140
+ allow_overwrite=args.force, verify=verify_before_activate, corpus=corpus,
2141
+ )
2142
+ active_bundle = spec.load(store_path, bundle_id)
2143
+ except _SmokeVerificationError as failed:
2144
+ rev_dir = store_path / failed.bundle_id / failed.revision
2145
+ if rev_dir.exists():
2146
+ state = spec._pointer(store_path / failed.bundle_id)
2147
+ if state.get("active") == failed.revision:
2148
+ disposition = f"Existing active revision {failed.revision[:12]} remains on disk"
2149
+ else:
2150
+ disposition = f"Pre-existing staged revision {failed.revision[:12]} remains on disk"
2151
+ else:
2152
+ disposition = f"New unactivated candidate revision {failed.revision[:12]} was discarded before activation"
2153
+ print(
2154
+ f"coldmemory init: live verification failed — query {failed.query!r} returned no verified file:line quote "
2155
+ f"from bundle '{failed.bundle_id}'. {disposition} and client configs were not modified.",
2156
+ file=err,
2157
+ )
2158
+ return 1
2159
+ except verifier.Changing:
2160
+ print(
2161
+ f"coldmemory init: notes in bundle '{bundle_id}' kept changing during live verification; "
2162
+ "no candidate was activated and client configs were not modified. Wait for edits to settle and retry.",
2163
+ file=err,
2164
+ )
2165
+ return 1
2166
+ if empty_skipped is not None:
2167
+ print(_empty_vault_message(sources, empty_skipped, args, cli=cli), file=err)
2168
+ return 1
2169
+
2170
+ query, answer = verified_result["query"], verified_result["answer"]
2171
+ staged_only = active_bundle.revision != bundle.revision
2172
+ apply_deferred = bool(args.apply and staged_only)
2173
+ reports = _apply_preflighted_clients(preflighted_plan) if (args.apply and not apply_deferred) else preview_reports
2174
+ elapsed = time.perf_counter() - started
2175
+
2176
+ counts = active_bundle.manifest["counts"]
2177
+ if staged_only:
2178
+ reason = "live trained revision unchanged" if active_bundle.trained else "active revision changed concurrently"
2179
+ print(f"ColdMemory staged revision compiled in {elapsed:.2f}s ({reason})", file=out)
2180
+ else:
2181
+ print(f"ColdMemory ready in {elapsed:.2f}s", file=out)
2182
+ print(f" Store: {store_path} (0700)", file=out)
2183
+ if staged_only:
2184
+ label = "active trained rev kept" if active_bundle.trained else "active rev differs"
2185
+ note_tag = (
2186
+ f" ({label}; revision {bundle.revision[:12]} staged — "
2187
+ f"run '{cli} activate --store {shlex.quote(str(store_path))} --id {bundle_id} "
2188
+ f"--revision {bundle.revision}' to switch)"
2189
+ )
2190
+ elif reused_revision:
2191
+ note_tag = " (reused unchanged revision)"
2192
+ elif id_state == "same":
2193
+ note_tag = " (recompiled existing bundle)"
2194
+ elif id_state == "suffixed":
2195
+ note_tag = f" (auto-picked to avoid colliding with '{DEFAULT_ID}')"
2196
+ else:
2197
+ note_tag = ""
2198
+ print(f" Bundle: {bundle_id} ({counts['notes']} notes, active rev {active_bundle.revision[:12]}){note_tag}",
2199
+ file=out)
2200
+ print(file=out)
2201
+ if staged_only:
2202
+ print(f"Staged check (verified archive quote from staged rev {bundle.revision[:12]} for {query!r}; not yet active):",
2203
+ file=out)
2204
+ else:
2205
+ print(f"Live check (verified archive quote for {query!r}):", file=out)
2206
+ for line in answer:
2207
+ print(f" {line}", file=out)
2208
+ _print_client_reports(reports, apply_changes=(args.apply and not apply_deferred), dry_run=False, sources=sources,
2209
+ store_path=store_path, bundle_id=bundle_id, clients_arg=args.clients, force=args.force,
2210
+ query=args.query, deferred_revision=(bundle.revision if apply_deferred else None),
2211
+ cli=cli, out=out)
2212
+ return 0
2213
+
2214
+
2215
+ def _print_client_reports(reports, *, apply_changes, dry_run, sources, store_path, bundle_id, clients_arg,
2216
+ force=False, query=None, deferred_revision=None, cli="coldmemory", out=None):
2217
+ src_args = _format_source_args(sources)
2218
+ clients_flag = f" --clients {shlex.quote(clients_arg)}" if clients_arg and clients_arg != "auto" else ""
2219
+ force_flag = " --force" if force else ""
2220
+ query_flag = f" --query {shlex.quote(query)}" if query else ""
2221
+ print(file=out)
2222
+ if not reports:
2223
+ if clients_arg and clients_arg.strip().lower() == "none":
2224
+ print("Clients: skipped (--clients none).", file=out)
2225
+ return
2226
+ print("Clients: none detected automatically.", file=out)
2227
+ hint_clients = clients_flag or " --clients claude,codex"
2228
+ print(f" Wire later: {cli} init {src_args} "
2229
+ f"--store {shlex.quote(str(store_path))} --id {bundle_id}{hint_clients}{force_flag}{query_flag} --apply", file=out)
2230
+ return
2231
+ if deferred_revision:
2232
+ heading = "Clients deferred (staged revision not yet active — no client config edited):"
2233
+ else:
2234
+ heading = "Clients:" if apply_changes else "Clients detected (preview — no client config edited):"
2235
+ print(heading, file=out)
2236
+ any_pending = False
2237
+ for report in reports:
2238
+ print(f" [{report['client']}] {report['summary']}", file=out)
2239
+ for item in report["files"]:
2240
+ bak = f" (backup: {item['backup']})" if item["backup"] else ""
2241
+ print(f" {item['status']}: {item['path']}{bak}", file=out)
2242
+ if item["status"].startswith("would "):
2243
+ any_pending = True
2244
+ for note in report["notes"]:
2245
+ print(f" {note}", file=out)
2246
+ if deferred_revision:
2247
+ print(file=out)
2248
+ print("Next: activate the staged revision first, then apply client configs:", file=out)
2249
+ print(f" {cli} activate --store {shlex.quote(str(store_path))} --id {bundle_id} "
2250
+ f"--revision {deferred_revision}", file=out)
2251
+ print(f" {cli} init {src_args} --store {shlex.quote(str(store_path))} --id {bundle_id}"
2252
+ f"{clients_flag}{force_flag}{query_flag} --apply", file=out)
2253
+ elif not apply_changes and (any_pending or dry_run):
2254
+ print(file=out)
2255
+ print("Next: run with --apply to write supported client configs safely (backups created first):", file=out)
2256
+ print(f" {cli} init {src_args} --store {shlex.quote(str(store_path))} --id {bundle_id}"
2257
+ f"{clients_flag}{force_flag}{query_flag} --apply",
2258
+ file=out)
2259
+
2260
+
2261
+ def register(commands):
2262
+ sub = commands.add_parser(
2263
+ "init",
2264
+ help="compile a local private store, verify one live quote, and preview or wire detected clients",
2265
+ )
2266
+ sub.set_defaults(run=run)
2267
+ sub.add_argument("vault", nargs="+", help="notes folder(s), or kind:/path (obsidian:/..., notion:/..., repo:/...)")
2268
+ sub.add_argument("--store", help="store folder (default: $XDG_DATA_HOME/coldmemory or ~/.local/share/coldmemory)")
2269
+ sub.add_argument("--id", help=f"bundle ID (default: {DEFAULT_ID}, auto-suffixed on collision)")
2270
+ sub.add_argument("--force", action="store_true",
2271
+ help="overwrite an existing --id for different sources/signing mode; with --apply, also replace signed, remote, or customized ColdMemory entries in selected clients")
2272
+ sub.add_argument("--clients", default="auto",
2273
+ help="auto (default), none, or comma-separated: claude,codex,openbot,hermes,grok")
2274
+ mode = sub.add_mutually_exclusive_group()
2275
+ mode.add_argument("--apply", action="store_true",
2276
+ help="write detected client configs with timestamped backups (close running clients first)")
2277
+ mode.add_argument("--dry-run", action="store_true", help="preview store and client actions without writing files")
2278
+ sub.add_argument("--query", help="custom smoke-test query for the live memory_ask verification")
2279
+ return sub