albert-memory 0.4.0__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.
Files changed (74) hide show
  1. albert/__init__.py +3 -0
  2. albert/admin.py +532 -0
  3. albert/api.py +698 -0
  4. albert/automatic_memory_release.json +14 -0
  5. albert/benchmark.py +272 -0
  6. albert/benchmark_cli.py +37 -0
  7. albert/capture.py +1051 -0
  8. albert/capture_installer.py +1000 -0
  9. albert/capture_promotion.py +298 -0
  10. albert/capture_retention.py +72 -0
  11. albert/capture_sdk.py +558 -0
  12. albert/capture_security.py +79 -0
  13. albert/chunking.py +79 -0
  14. albert/classifier.py +263 -0
  15. albert/claude_adapter.py +357 -0
  16. albert/claude_lifecycle.py +418 -0
  17. albert/claude_package.json +19 -0
  18. albert/claude_plugin/.claude-plugin/plugin.json +11 -0
  19. albert/claude_plugin/.mcp.json +13 -0
  20. albert/claude_plugin/hooks/hooks.json +70 -0
  21. albert/clusters.py +140 -0
  22. albert/codex_adapter.py +308 -0
  23. albert/codex_hooks/hooks.json +49 -0
  24. albert/codex_lifecycle.py +485 -0
  25. albert/codex_package.json +19 -0
  26. albert/compatibility.py +121 -0
  27. albert/config.py +144 -0
  28. albert/console.py +508 -0
  29. albert/console_backends.py +236 -0
  30. albert/console_map.py +518 -0
  31. albert/console_ops.py +919 -0
  32. albert/credentials.py +616 -0
  33. albert/cursor_adapter.py +320 -0
  34. albert/cursor_hooks/hooks.json +11 -0
  35. albert/cursor_rules/albert-memory.mdc +11 -0
  36. albert/db.py +68 -0
  37. albert/embeddings.py +91 -0
  38. albert/graph.py +623 -0
  39. albert/graph_builders.py +879 -0
  40. albert/graph_cypher.py +669 -0
  41. albert/graph_store.py +376 -0
  42. albert/host_targets/claude-code.json +45 -0
  43. albert/host_targets/codex.json +45 -0
  44. albert/host_targets/openclaw.json +45 -0
  45. albert/host_targets.py +271 -0
  46. albert/links.py +428 -0
  47. albert/mcp_server.py +457 -0
  48. albert/memory_safety.py +111 -0
  49. albert/models.py +611 -0
  50. albert/openclaw_adapter.py +326 -0
  51. albert/openclaw_adapter_trust.json +5 -0
  52. albert/openclaw_package.json +22 -0
  53. albert/openclaw_plugin/index.js +135 -0
  54. albert/openclaw_plugin/openclaw.plugin.json +25 -0
  55. albert/openclaw_plugin/package.json +12 -0
  56. albert/portability.py +291 -0
  57. albert/provenance.py +105 -0
  58. albert/recorder.py +166 -0
  59. albert/release_gate.py +83 -0
  60. albert/schemas.py +617 -0
  61. albert/scope.py +26 -0
  62. albert/search.py +447 -0
  63. albert/security.py +150 -0
  64. albert/services.py +1316 -0
  65. albert/session_context.py +162 -0
  66. albert/trace_feed.py +165 -0
  67. albert/trace_writer.py +131 -0
  68. albert/tracing.py +75 -0
  69. albert/worker.py +202 -0
  70. albert/workspaces.py +256 -0
  71. albert_memory-0.4.0.dist-info/METADATA +554 -0
  72. albert_memory-0.4.0.dist-info/RECORD +74 -0
  73. albert_memory-0.4.0.dist-info/WHEEL +4 -0
  74. albert_memory-0.4.0.dist-info/entry_points.txt +14 -0
@@ -0,0 +1,418 @@
1
+ """Transactional lifecycle management for the supported Claude Code plugin target."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import getpass
6
+ import json
7
+ import os
8
+ import re
9
+ import shlex
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import uuid
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ import typer
19
+
20
+ from albert.capture_installer import InstallError, _brain_check, _validate_secret
21
+ from albert.capture_sdk import generate_queue_key
22
+ from albert.claude_adapter import CLAUDE_EVENTS
23
+ from albert.host_targets import HostTargetError, assert_owned_install_root, negotiate_host_target
24
+
25
+ app = typer.Typer(help="Securely install and operate Albert for Claude Code.")
26
+ PLUGIN_ID = "albert-memory"
27
+ VERSION_PATTERN = re.compile(r"(?:Claude Code\s+)?v?(\d+)\.(\d+)\.(\d+)")
28
+ Runner = Callable[[list[str]], subprocess.CompletedProcess[str]]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class ClaudeInstallPaths:
33
+ root: Path
34
+
35
+ @property
36
+ def credentials(self) -> Path:
37
+ return self.root / "credentials.env"
38
+
39
+ @property
40
+ def marker(self) -> Path:
41
+ return self.root / "install.json"
42
+
43
+ @property
44
+ def plugin(self) -> Path:
45
+ return self.root / "plugin"
46
+
47
+ @property
48
+ def adapter(self) -> Path:
49
+ return self.root / "bin" / "albert-claude-adapter"
50
+
51
+ @property
52
+ def launcher(self) -> Path:
53
+ return self.root / "bin" / "albert-claude"
54
+
55
+ @property
56
+ def queue(self) -> Path:
57
+ return self.root / "capture.db"
58
+
59
+
60
+ def _run(command: list[str]) -> subprocess.CompletedProcess[str]:
61
+ return subprocess.run(command, text=True, capture_output=True, check=False)
62
+
63
+
64
+ def _checked(runner: Runner, command: list[str], label: str) -> subprocess.CompletedProcess[str]:
65
+ result = runner(command)
66
+ if result.returncode:
67
+ detail = (result.stderr or result.stdout).strip().splitlines()
68
+ suffix = f": {detail[-1]}" if detail else ""
69
+ raise InstallError(f"{label} failed{suffix}")
70
+ return result
71
+
72
+
73
+ def _detect_claude(runner: Runner) -> tuple[int, int, int]:
74
+ result = _checked(runner, ["claude", "--version"], "Claude Code detection")
75
+ match = VERSION_PATTERN.search(result.stdout)
76
+ if not match:
77
+ raise InstallError("unsupported Claude Code version output")
78
+ version = tuple(int(value) for value in match.groups())
79
+ try:
80
+ negotiate_host_target("claude-code", version, {"capture", "recall"})
81
+ except HostTargetError as exc:
82
+ raise InstallError(str(exc)) from None
83
+ return version
84
+
85
+
86
+ def _write_private(path: Path, content: str, mode: int) -> None:
87
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
88
+ path.write_text(content, encoding="utf-8")
89
+ os.chmod(path, mode)
90
+
91
+
92
+ def _credential_text(
93
+ api_url: str, token: str, queue_key: str, queue_path: Path, workspace_id: str | None
94
+ ) -> str:
95
+ values = {
96
+ "ALBERT_API_URL": api_url.rstrip("/"),
97
+ "ALBERT_CAPTURE_QUEUE_KEY": queue_key,
98
+ "ALBERT_CAPTURE_QUEUE_PATH": str(queue_path),
99
+ "ALBERT_CAPTURE_SCOPE": "claude-code:default",
100
+ "ALBERT_CAPTURE_TOKEN": token,
101
+ }
102
+ if workspace_id:
103
+ values["ALBERT_WORKSPACE_ID"] = workspace_id
104
+ return json.dumps(values, sort_keys=True) + "\n"
105
+
106
+
107
+ def _adapter_text(credentials: Path) -> str:
108
+ return (
109
+ "#!/bin/sh\n"
110
+ f"export ALBERT_CAPTURE_CREDENTIAL_FILE={shlex.quote(str(credentials))}\n"
111
+ f"exec {shlex.quote(sys.executable)} -m albert.claude_adapter\n"
112
+ )
113
+
114
+
115
+ def _launcher_text(plugin: Path) -> str:
116
+ return (
117
+ "#!/bin/sh\n"
118
+ f"exec claude --plugin-dir {shlex.quote(str(plugin))} \"$@\"\n"
119
+ )
120
+
121
+
122
+ def _load_install(
123
+ paths: ClaudeInstallPaths, *, require_credentials: bool = True
124
+ ) -> tuple[dict, dict]:
125
+ if not paths.marker.exists() or (require_credentials and not paths.credentials.exists()):
126
+ raise InstallError("no Albert-owned Claude Code installation found")
127
+ try:
128
+ marker = json.loads(paths.marker.read_text(encoding="utf-8"))
129
+ values = (
130
+ json.loads(paths.credentials.read_text(encoding="utf-8"))
131
+ if paths.credentials.exists()
132
+ else {}
133
+ )
134
+ except (OSError, json.JSONDecodeError) as exc:
135
+ raise InstallError("Claude Code installation metadata is invalid") from exc
136
+ if marker.get("owner") != PLUGIN_ID or marker.get("host") != "claude-code":
137
+ raise InstallError("installation ownership marker is invalid")
138
+ if not isinstance(values, dict) or not all(
139
+ isinstance(key, str) and isinstance(value, str) for key, value in values.items()
140
+ ):
141
+ raise InstallError("credential file is invalid")
142
+ return marker, values
143
+
144
+
145
+ def _stage_plugin(staged: ClaudeInstallPaths, source: Path, adapter_command: Path) -> None:
146
+ if source.is_symlink() or not source.is_dir():
147
+ raise InstallError("Claude plugin source must be a regular directory")
148
+ if any(path.is_symlink() for path in source.rglob("*")):
149
+ raise InstallError("Claude plugin source must not contain symlinks")
150
+ shutil.copytree(source, staged.plugin, symlinks=False)
151
+ hooks_path = staged.plugin / "hooks" / "hooks.json"
152
+ try:
153
+ hooks = json.loads(hooks_path.read_text(encoding="utf-8"))
154
+ entries = hooks["hooks"]
155
+ if set(entries) != {
156
+ "PreCompact",
157
+ "SessionEnd",
158
+ "SessionStart",
159
+ "Stop",
160
+ "StopFailure",
161
+ "UserPromptSubmit",
162
+ }:
163
+ raise InstallError("Claude plugin hook manifest contains unsupported events")
164
+ for matchers in entries.values():
165
+ if not isinstance(matchers, list) or len(matchers) != 1:
166
+ raise InstallError("Claude plugin hook manifest is untrusted")
167
+ for matcher in matchers:
168
+ if set(matcher) != {"hooks"} or len(matcher["hooks"]) != 1:
169
+ raise InstallError("Claude plugin hook manifest is untrusted")
170
+ for hook in matcher["hooks"]:
171
+ if hook != {
172
+ "type": "command",
173
+ "command": "albert-claude-adapter",
174
+ "timeout": 2,
175
+ }:
176
+ raise InstallError("Claude plugin hook manifest is untrusted")
177
+ hook["command"] = str(adapter_command)
178
+ except (KeyError, TypeError, json.JSONDecodeError) as exc:
179
+ raise InstallError("Claude plugin hook manifest is malformed") from exc
180
+ hooks_path.write_text(json.dumps(hooks, indent=2, sort_keys=True) + "\n", encoding="utf-8")
181
+
182
+
183
+ def install_claude(
184
+ *,
185
+ api_url: str,
186
+ token: str,
187
+ workspace_id: str | None,
188
+ paths: ClaudeInstallPaths,
189
+ runner: Runner = _run,
190
+ brain_check: Callable[[str, str, str, str | None], None] | None = None,
191
+ plugin_source: Path | None = None,
192
+ ) -> None:
193
+ """Validate, stage, atomically replace, and prove a Claude Code installation."""
194
+ version = _detect_claude(runner)
195
+ try:
196
+ target = negotiate_host_target(
197
+ "claude-code",
198
+ version,
199
+ {"capture", "recall", "reload", "rollback", "uninstall", "upgrade"},
200
+ )
201
+ assert_owned_install_root(paths.root, expected_marker=target.ownership["marker"])
202
+ except HostTargetError as exc:
203
+ raise InstallError(str(exc)) from None
204
+ token = _validate_secret(token)
205
+ api_url = api_url.rstrip("/")
206
+ if not api_url.startswith(("http://", "https://")):
207
+ raise InstallError("Brain URL must use http:// or https://")
208
+ previous_marker: dict = {}
209
+ previous_credentials: dict = {}
210
+ if paths.root.exists():
211
+ previous_marker, previous_credentials = _load_install(
212
+ paths, require_credentials=False
213
+ )
214
+ if not previous_credentials and not previous_marker.get("revoked"):
215
+ raise InstallError("Claude Code installation credentials are missing")
216
+ queue_key = previous_credentials.get("ALBERT_CAPTURE_QUEUE_KEY")
217
+ if not queue_key and previous_marker.get("revoked"):
218
+ queue_key = previous_marker.get("reconnect_queue_key")
219
+ if not isinstance(queue_key, str) or not queue_key:
220
+ raise InstallError("revoked Claude Code installation reconnect state is invalid")
221
+ queue_key = queue_key or generate_queue_key()
222
+ check = brain_check or (
223
+ lambda url, secret, key, workspace: _brain_check(
224
+ url, secret, key, workspace, smoke=True, event_classes=CLAUDE_EVENTS
225
+ )
226
+ )
227
+ check(api_url, token, queue_key, workspace_id)
228
+
229
+ source = plugin_source or Path(__file__).with_name("claude_plugin")
230
+ backup = paths.root.with_name(f".{paths.root.name}.rollback-{uuid.uuid4().hex}")
231
+ staging = paths.root.with_name(f".{paths.root.name}.staging-{uuid.uuid4().hex}")
232
+ staged = ClaudeInstallPaths(staging)
233
+ swapped = False
234
+ try:
235
+ _write_private(
236
+ staged.credentials,
237
+ _credential_text(api_url, token, queue_key, paths.queue, workspace_id),
238
+ 0o600,
239
+ )
240
+ _write_private(staged.adapter, _adapter_text(paths.credentials), 0o700)
241
+ _write_private(staged.launcher, _launcher_text(paths.plugin), 0o700)
242
+ _stage_plugin(staged, source, paths.adapter)
243
+ marker = {
244
+ "api_url": api_url,
245
+ "claude_version": ".".join(str(value) for value in version),
246
+ "hook_fidelity": target.hooks["fidelity"],
247
+ "host": "claude-code",
248
+ "host_target_schema": target.schema_version,
249
+ "host_target_version": target.descriptor_version,
250
+ "owner": PLUGIN_ID,
251
+ }
252
+ _write_private(staged.marker, json.dumps(marker, sort_keys=True) + "\n", 0o600)
253
+ for filename in ("capture.db", "capture.claude-state.db"):
254
+ existing = paths.root / filename
255
+ if existing.exists():
256
+ if existing.is_symlink() or not existing.is_file():
257
+ raise InstallError("Claude state path is unsafe")
258
+ shutil.copy2(existing, staging / filename)
259
+ os.chmod(staging / filename, 0o600)
260
+ _checked(
261
+ runner,
262
+ ["claude", "plugin", "validate", "--strict", str(staged.plugin)],
263
+ "Claude plugin validation",
264
+ )
265
+ if paths.root.exists():
266
+ paths.root.rename(backup)
267
+ staging.rename(paths.root)
268
+ swapped = True
269
+ _checked(
270
+ runner,
271
+ ["claude", "plugin", "validate", "--strict", str(paths.plugin)],
272
+ "Claude installed plugin validation",
273
+ )
274
+ check(api_url, token, queue_key, workspace_id)
275
+ except Exception:
276
+ if backup.exists():
277
+ if paths.root.exists():
278
+ shutil.rmtree(paths.root)
279
+ backup.rename(paths.root)
280
+ elif swapped and paths.root.exists():
281
+ shutil.rmtree(paths.root)
282
+ if staging.exists():
283
+ shutil.rmtree(staging)
284
+ raise
285
+ else:
286
+ if backup.exists():
287
+ shutil.rmtree(backup)
288
+
289
+
290
+ def doctor_claude(
291
+ paths: ClaudeInstallPaths,
292
+ *,
293
+ smoke: bool = False,
294
+ runner: Runner = _run,
295
+ brain_check: Callable[[str, str, str, str | None], None] | None = None,
296
+ ) -> None:
297
+ version = _detect_claude(runner)
298
+ try:
299
+ target = negotiate_host_target("claude-code", version, {"capture", "recall"})
300
+ assert_owned_install_root(paths.root, expected_marker=target.ownership["marker"])
301
+ except HostTargetError as exc:
302
+ raise InstallError(str(exc)) from None
303
+ _, values = _load_install(paths)
304
+ _checked(
305
+ runner,
306
+ ["claude", "plugin", "validate", "--strict", str(paths.plugin)],
307
+ "Claude plugin validation",
308
+ )
309
+ check = brain_check or (
310
+ lambda url, secret, key, workspace: _brain_check(
311
+ url,
312
+ secret,
313
+ key,
314
+ workspace,
315
+ smoke=smoke,
316
+ event_classes=CLAUDE_EVENTS,
317
+ )
318
+ )
319
+ check(
320
+ values["ALBERT_API_URL"],
321
+ values["ALBERT_CAPTURE_TOKEN"],
322
+ values["ALBERT_CAPTURE_QUEUE_KEY"],
323
+ values.get("ALBERT_WORKSPACE_ID"),
324
+ )
325
+
326
+
327
+ def revoke_claude(paths: ClaudeInstallPaths) -> None:
328
+ """Remove only the target credential; plugin and unrelated host state remain."""
329
+ try:
330
+ target = negotiate_host_target("claude-code", (2, 1, 312), {"revoke"})
331
+ assert_owned_install_root(paths.root, expected_marker=target.ownership["marker"])
332
+ except HostTargetError as exc:
333
+ raise InstallError(str(exc)) from None
334
+ marker, values = _load_install(paths)
335
+ marker["reconnect_queue_key"] = values["ALBERT_CAPTURE_QUEUE_KEY"]
336
+ marker["revoked"] = True
337
+ _write_private(paths.marker, json.dumps(marker, sort_keys=True) + "\n", 0o600)
338
+ paths.credentials.unlink()
339
+
340
+
341
+ def uninstall_claude(paths: ClaudeInstallPaths, *, runner: Runner = _run) -> None:
342
+ _detect_claude(runner)
343
+ try:
344
+ target = negotiate_host_target("claude-code", (2, 1, 312), {"uninstall"})
345
+ assert_owned_install_root(paths.root, expected_marker=target.ownership["marker"])
346
+ except HostTargetError as exc:
347
+ raise InstallError(str(exc)) from None
348
+ _load_install(paths, require_credentials=False)
349
+ shutil.rmtree(paths.root)
350
+
351
+
352
+ def _default_paths() -> ClaudeInstallPaths:
353
+ return ClaudeInstallPaths(Path("~/.claude/albert").expanduser())
354
+
355
+
356
+ @app.command("install")
357
+ def install_command(
358
+ api_url: str = typer.Option(..., "--api-url"),
359
+ workspace_id: str | None = typer.Option(None, "--workspace-id"),
360
+ token_stdin: bool = typer.Option(False, "--token-stdin"),
361
+ token_fd: int | None = typer.Option(None, "--token-fd", min=0),
362
+ ) -> None:
363
+ try:
364
+ if token_stdin and token_fd is not None:
365
+ raise InstallError("choose only one private token input mode")
366
+ if token_fd is not None:
367
+ with os.fdopen(os.dup(token_fd), encoding="utf-8") as stream:
368
+ token = stream.read(8193)
369
+ elif token_stdin:
370
+ token = sys.stdin.read(8193)
371
+ else:
372
+ token = getpass.getpass("Albert capture token: ")
373
+ if len(token) > 8192:
374
+ raise InstallError("credential is too long")
375
+ install_claude(
376
+ api_url=api_url,
377
+ token=token.strip(),
378
+ workspace_id=workspace_id,
379
+ paths=_default_paths(),
380
+ )
381
+ typer.echo("Albert Memory installed; use ~/.claude/albert/bin/albert-claude.")
382
+ except (InstallError, OSError) as exc:
383
+ typer.echo(f"Install failed safely: {exc}", err=True)
384
+ raise typer.Exit(1) from None
385
+
386
+
387
+ @app.command("doctor")
388
+ def doctor_command(smoke: bool = typer.Option(False, "--smoke")) -> None:
389
+ try:
390
+ doctor_claude(_default_paths(), smoke=smoke)
391
+ typer.echo("Albert Memory Claude Code doctor passed.")
392
+ except InstallError as exc:
393
+ typer.echo(f"Doctor failed: {exc}", err=True)
394
+ raise typer.Exit(1) from None
395
+
396
+
397
+ @app.command("revoke")
398
+ def revoke_command() -> None:
399
+ try:
400
+ revoke_claude(_default_paths())
401
+ typer.echo("Albert credential removed; plugin and unrelated Claude settings remain.")
402
+ except InstallError as exc:
403
+ typer.echo(f"Revoke failed safely: {exc}", err=True)
404
+ raise typer.Exit(1) from None
405
+
406
+
407
+ @app.command("uninstall")
408
+ def uninstall_command() -> None:
409
+ try:
410
+ uninstall_claude(_default_paths())
411
+ typer.echo("Albert-owned Claude Code files removed; unrelated settings remain.")
412
+ except InstallError as exc:
413
+ typer.echo(f"Uninstall failed safely: {exc}", err=True)
414
+ raise typer.Exit(1) from None
415
+
416
+
417
+ if __name__ == "__main__":
418
+ app()
@@ -0,0 +1,19 @@
1
+ {
2
+ "schema": 1,
3
+ "package": "albert-memory",
4
+ "package_version": "0.4.0",
5
+ "family": "claude-code",
6
+ "owner": "JIGGAI/albert",
7
+ "supported_claude": ">=2.1.78,<2.2.0",
8
+ "tested_claude": "2.1.312",
9
+ "hook_fidelity": "full-with-best-effort-failure-hook",
10
+ "install_root": "~/.claude/albert",
11
+ "rollback_source_template": "https://github.com/JIGGAI/albert/tree/{source_revision}/src/albert/claude_plugin",
12
+ "components": {
13
+ "adapter": "albert.claude_adapter:main",
14
+ "connector": "albert.claude_lifecycle:app",
15
+ "host_target": "albert/host_targets/claude-code.json",
16
+ "ownership_marker": "albert-memory",
17
+ "plugin_manifest": "albert/claude_plugin/.claude-plugin/plugin.json"
18
+ }
19
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "albert-memory",
3
+ "displayName": "Albert Memory",
4
+ "version": "0.4.0",
5
+ "description": "Policy-safe automatic memory lifecycle hooks for Claude Code",
6
+ "author": {
7
+ "name": "JIGGAI"
8
+ },
9
+ "repository": "https://github.com/JIGGAI/albert",
10
+ "license": "MIT"
11
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "mcpServers": {
3
+ "albert": {
4
+ "type": "stdio",
5
+ "command": "albert-mcp",
6
+ "args": ["--transport", "stdio"],
7
+ "env": {
8
+ "ALBERT_API_URL": "${ALBERT_API_URL:-http://127.0.0.1:8080}",
9
+ "ALBERT_MCP_API_KEY": "${ALBERT_MCP_API_KEY}"
10
+ }
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,70 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "albert-claude-adapter",
9
+ "timeout": 2
10
+ }
11
+ ]
12
+ }
13
+ ],
14
+ "UserPromptSubmit": [
15
+ {
16
+ "hooks": [
17
+ {
18
+ "type": "command",
19
+ "command": "albert-claude-adapter",
20
+ "timeout": 2
21
+ }
22
+ ]
23
+ }
24
+ ],
25
+ "PreCompact": [
26
+ {
27
+ "hooks": [
28
+ {
29
+ "type": "command",
30
+ "command": "albert-claude-adapter",
31
+ "timeout": 2
32
+ }
33
+ ]
34
+ }
35
+ ],
36
+ "Stop": [
37
+ {
38
+ "hooks": [
39
+ {
40
+ "type": "command",
41
+ "command": "albert-claude-adapter",
42
+ "timeout": 2
43
+ }
44
+ ]
45
+ }
46
+ ],
47
+ "StopFailure": [
48
+ {
49
+ "hooks": [
50
+ {
51
+ "type": "command",
52
+ "command": "albert-claude-adapter",
53
+ "timeout": 2
54
+ }
55
+ ]
56
+ }
57
+ ],
58
+ "SessionEnd": [
59
+ {
60
+ "hooks": [
61
+ {
62
+ "type": "command",
63
+ "command": "albert-claude-adapter",
64
+ "timeout": 2
65
+ }
66
+ ]
67
+ }
68
+ ]
69
+ }
70
+ }
albert/clusters.py ADDED
@@ -0,0 +1,140 @@
1
+ """Deterministic clustering of the memory map and names for the clusters.
2
+
3
+ Pure functions over ids, link weights and titles: no database, no randomness,
4
+ so the same snapshot always yields the same clusters in the same order.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from collections import Counter, defaultdict
12
+
13
+ MAX_ROUNDS = 20
14
+ NAME_TERMS = 2
15
+ # A second word joins a name only when at least this share of members carry it.
16
+ SECOND_TERM_SHARE = 0.5
17
+ _TERM = re.compile(r"[a-z][a-z0-9'-]*")
18
+ STOP_WORDS = frozenset(
19
+ """
20
+ a about above after again against all also am an and any are as at be because been before
21
+ being below between both but by can could did do does doing done down during each few for
22
+ from further get gets got had has have having he her here hers him his how i if in into is
23
+ it its just may me more most must my no nor not now of off on once one only or other our
24
+ out over own per same she should so some such than that the their them then there these
25
+ they this those through to too under until up use used uses using very via was we were
26
+ what when where which while who why will with without would you your
27
+ new note notes update updated updates misc general
28
+ reference project feedback user
29
+ january february march april may june july august september october november december
30
+ jan feb mar apr jun jul aug sep sept oct nov dec
31
+ monday tuesday wednesday thursday friday saturday sunday
32
+ utc gmt est edt cst cdt mst mdt pst pdt
33
+ """.split()
34
+ )
35
+
36
+
37
+ def cluster_nodes(
38
+ node_ids: list[str], links: list[tuple[str, str, float]], *, min_size: int = 3
39
+ ) -> dict[str, int]:
40
+ """Assign nodes to clusters by weighted label propagation.
41
+
42
+ Nodes are visited in id order and adopt the label carrying the most link
43
+ weight among their neighbours (ties go to the smallest label). Clusters are
44
+ numbered by descending size, then smallest member id; nodes in groups
45
+ smaller than `min_size` are left out of the result.
46
+ """
47
+ known = set(node_ids)
48
+ neighbours: dict[str, dict[str, float]] = defaultdict(dict)
49
+ for first, second, weight in links:
50
+ if first == second or first not in known or second not in known:
51
+ continue
52
+ strength = max(float(weight), 0.0)
53
+ neighbours[first][second] = max(neighbours[first].get(second, 0.0), strength)
54
+ neighbours[second][first] = max(neighbours[second].get(first, 0.0), strength)
55
+ order = sorted(neighbours)
56
+ labels = {node: node for node in order}
57
+ for _ in range(MAX_ROUNDS):
58
+ changed = False
59
+ for node in order:
60
+ totals: dict[str, float] = defaultdict(float)
61
+ for other, strength in neighbours[node].items():
62
+ totals[labels[other]] += strength
63
+ best = min(totals, key=lambda label: (-round(totals[label], 9), label))
64
+ if best != labels[node]:
65
+ labels[node] = best
66
+ changed = True
67
+ if not changed:
68
+ break
69
+ groups: dict[str, list[str]] = defaultdict(list)
70
+ for node, label in labels.items():
71
+ groups[label].append(node)
72
+ kept = sorted(
73
+ (sorted(members) for members in groups.values() if len(members) >= min_size),
74
+ key=lambda members: (-len(members), members[0]),
75
+ )
76
+ return {node: index for index, members in enumerate(kept) for node in members}
77
+
78
+
79
+ def _terms(title: str) -> list[str]:
80
+ """Distinct naming terms of a title, in the order they appear."""
81
+ terms: list[str] = []
82
+ for term in _TERM.findall(title.lower()):
83
+ if len(term) >= 3 and term not in STOP_WORDS and term not in terms:
84
+ terms.append(term)
85
+ return terms
86
+
87
+
88
+ def _display(term: str) -> str:
89
+ return term.upper() if len(term) <= 3 else term.capitalize()
90
+
91
+
92
+ def name_clusters(titles: dict[str, str], assignment: dict[str, int]) -> dict[int, str]:
93
+ """Name each cluster by its most distinctive title terms (TF-IDF across clusters)."""
94
+ clusters = sorted(set(assignment.values()))
95
+ frequency: dict[int, Counter[str]] = {cluster: Counter() for cluster in clusters}
96
+ sizes: Counter[int] = Counter(assignment.values())
97
+ position: dict[int, dict[str, int]] = {cluster: defaultdict(int) for cluster in clusters}
98
+ for node, cluster in assignment.items():
99
+ terms = _terms(titles.get(node, ""))
100
+ frequency[cluster].update(terms)
101
+ for index, term in enumerate(terms):
102
+ position[cluster][term] += index
103
+ spread: Counter[str] = Counter()
104
+ for counts in frequency.values():
105
+ spread.update(counts.keys())
106
+ names: dict[int, str] = {}
107
+ taken: set[str] = set()
108
+ for cluster in clusters:
109
+ scored = sorted(
110
+ (
111
+ (
112
+ (count / sizes[cluster]) * (1.0 + math.log((1 + len(clusters)) / spread[term])),
113
+ term,
114
+ )
115
+ for term, count in frequency[cluster].items()
116
+ ),
117
+ key=lambda item: (-round(item[0], 9), item[1]),
118
+ )
119
+ ranked = [term for _score, term in scored]
120
+ name = ""
121
+ # One strong word beats a name padded with a word few members share.
122
+ start = min(NAME_TERMS, len(ranked))
123
+ if start == 2 and frequency[cluster][ranked[1]] / sizes[cluster] < SECOND_TERM_SHARE:
124
+ start = 1
125
+ # Widen only to keep names distinct.
126
+ for width in range(start, len(ranked) + 1):
127
+ # Read like the titles do: order the chosen terms by where they usually sit.
128
+ chosen = sorted(
129
+ ranked[:width],
130
+ key=lambda term: (position[cluster][term] / frequency[cluster][term], term),
131
+ )
132
+ candidate = " ".join(_display(term) for term in chosen)
133
+ if candidate and candidate not in taken:
134
+ name = candidate
135
+ break
136
+ if not name:
137
+ name = f"Cluster {cluster + 1}"
138
+ taken.add(name)
139
+ names[cluster] = name
140
+ return names