khipumaq 0.1.2__tar.gz

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.
khipumaq-0.1.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 fsgeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: khipumaq
3
+ Version: 0.1.2
4
+ Summary: An episodic store of every prior Claude Code and Codex session — the user's words and the assistant's responses — searchable by the instances that come after.
5
+ Keywords: memory,episodic,llm,agent,arangodb,mcp
6
+ Author: Tony
7
+ Author-email: Tony <fsgeek@cs.ubc.ca>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Dist: mcp[cli]>=1.28,<2
13
+ Requires-Dist: python-arango>=8.3.3
14
+ Requires-Python: >=3.14
15
+ Description-Content-Type: text/markdown
16
+
17
+ # khipumaq
18
+
19
+ *Quechua: one who makes a khipu, the knotted-cord record.* The name states the
20
+ job: keep the record, so it can be read back.
21
+
22
+ `khipumaq` keeps every Claude Code and Codex session you have had — your words
23
+ and the assistant's responses, not summaries — in one searchable store, and
24
+ gives the instances that come after a tool to search it.
25
+
26
+ ## The problem
27
+
28
+ A coding agent starts every session without its past. What was decided last
29
+ week, what you already explained, what a prior instance got wrong: all of it
30
+ is in transcripts on disk, and none of it is reachable from inside a session.
31
+ The agent asks you again, or guesses, or searches the filesystem and finds
32
+ nothing. The information exists; the path to it does not. And Claude Code
33
+ deletes transcripts after about 30 days, so the record does not even wait.
34
+
35
+ ## What it does
36
+
37
+ - **Ingests** Claude Code transcripts (including subagents and Cowork tasks)
38
+ and Codex CLI rollouts into an ArangoDB collection: one episode per
39
+ assistant turn, paired with the user turn before it, labelled by project,
40
+ with the host, machine id, and source path it came from.
41
+ - **Stays current** without you: a SessionEnd hook for Claude Code and Codex
42
+ ingests each session as it closes, and a daily sweep catches anything a hook
43
+ missed. On WSL the sweep also reads the Windows side (Claude Code, Cowork,
44
+ Codex on Windows) through `/mnt/c`.
45
+ - **Serves** it read-only over MCP: `search` (BM25 over both sides of the
46
+ conversation, filterable by project and date, returning how many matched),
47
+ `recall` (one whole episode), and `describe` (what the store holds). At
48
+ start the server says one sentence about itself — how much it holds, how
49
+ fresh it is, and when to reach for it — and says plainly when ingestion
50
+ looks stale.
51
+
52
+ There is no write tool. Episodes come only from the transcripts, so an
53
+ instance cannot edit the record of what it did.
54
+
55
+ ## Install
56
+
57
+ You need Python 3.14, [uv](https://docs.astral.sh/uv/), and an ArangoDB 3.12
58
+ server you control (a local container is fine) with a database and a user
59
+ that can read and write it. khipumaq creates its collection and search view on
60
+ first use.
61
+
62
+ 1. Write `~/.config/khipumaq/db-config.ini` (mode 0600):
63
+
64
+ ```ini
65
+ [database]
66
+ host = 127.0.0.1
67
+ port = 8529
68
+ database = khipumaq
69
+ user_name = khipumaq
70
+ user_password = ...
71
+ ```
72
+
73
+ `$KHIPUMAQ_CONFIG` points elsewhere if you prefer. An optional
74
+ `[khipumaq]` section with `person = <your name>` lets the server's
75
+ sentence name you ("Before asking <name> what happened…"); the default
76
+ is "the user".
77
+
78
+ 2. Wire this machine:
79
+
80
+ ```sh
81
+ uvx --python 3.14 khipumaq install
82
+ uvx --python 3.14 khipumaq sweep # first run ingests everything on disk
83
+ ```
84
+
85
+ `install` adds the Claude Code SessionEnd hook, the MCP server entry, the
86
+ Codex hooks (and the trust Codex requires before running them), a daily
87
+ systemd user timer for the sweep, and — on WSL — the MCP entry for Claude
88
+ Code and Claude Desktop on Windows. `khipumaq uninstall` removes all of it
89
+ and leaves the store alone.
90
+
91
+ 3. Restart Claude Code. Run `install` on each machine whose sessions should
92
+ land in the store; they can all point at one database.
93
+
94
+ Remote or hosted ArangoDB (ArangoDB Cloud, a server across a WAN) should work
95
+ through the same config file but is **not tested**; pull requests welcome.
96
+
97
+ ## Privacy
98
+
99
+ The store holds your conversations in full. It lives where you put it and
100
+ nowhere else: khipumaq sends nothing to any service but your database. Its
101
+ operational event log (`~/.local/state/llm-memory/events.jsonl`) records
102
+ identifiers, digests, and counts, never query text or episode content. Point
103
+ it at a database on a network you trust.
104
+
105
+ ## Status
106
+
107
+ Pre-alpha, and used daily. Design notes and the record of how it got here are
108
+ in `docs/superpowers/specs/2026-09-01-khipumaq-design.md`.
109
+
110
+ ## License
111
+
112
+ MIT. Contributions are accepted under the Developer Certificate of Origin; see
113
+ [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,97 @@
1
+ # khipumaq
2
+
3
+ *Quechua: one who makes a khipu, the knotted-cord record.* The name states the
4
+ job: keep the record, so it can be read back.
5
+
6
+ `khipumaq` keeps every Claude Code and Codex session you have had — your words
7
+ and the assistant's responses, not summaries — in one searchable store, and
8
+ gives the instances that come after a tool to search it.
9
+
10
+ ## The problem
11
+
12
+ A coding agent starts every session without its past. What was decided last
13
+ week, what you already explained, what a prior instance got wrong: all of it
14
+ is in transcripts on disk, and none of it is reachable from inside a session.
15
+ The agent asks you again, or guesses, or searches the filesystem and finds
16
+ nothing. The information exists; the path to it does not. And Claude Code
17
+ deletes transcripts after about 30 days, so the record does not even wait.
18
+
19
+ ## What it does
20
+
21
+ - **Ingests** Claude Code transcripts (including subagents and Cowork tasks)
22
+ and Codex CLI rollouts into an ArangoDB collection: one episode per
23
+ assistant turn, paired with the user turn before it, labelled by project,
24
+ with the host, machine id, and source path it came from.
25
+ - **Stays current** without you: a SessionEnd hook for Claude Code and Codex
26
+ ingests each session as it closes, and a daily sweep catches anything a hook
27
+ missed. On WSL the sweep also reads the Windows side (Claude Code, Cowork,
28
+ Codex on Windows) through `/mnt/c`.
29
+ - **Serves** it read-only over MCP: `search` (BM25 over both sides of the
30
+ conversation, filterable by project and date, returning how many matched),
31
+ `recall` (one whole episode), and `describe` (what the store holds). At
32
+ start the server says one sentence about itself — how much it holds, how
33
+ fresh it is, and when to reach for it — and says plainly when ingestion
34
+ looks stale.
35
+
36
+ There is no write tool. Episodes come only from the transcripts, so an
37
+ instance cannot edit the record of what it did.
38
+
39
+ ## Install
40
+
41
+ You need Python 3.14, [uv](https://docs.astral.sh/uv/), and an ArangoDB 3.12
42
+ server you control (a local container is fine) with a database and a user
43
+ that can read and write it. khipumaq creates its collection and search view on
44
+ first use.
45
+
46
+ 1. Write `~/.config/khipumaq/db-config.ini` (mode 0600):
47
+
48
+ ```ini
49
+ [database]
50
+ host = 127.0.0.1
51
+ port = 8529
52
+ database = khipumaq
53
+ user_name = khipumaq
54
+ user_password = ...
55
+ ```
56
+
57
+ `$KHIPUMAQ_CONFIG` points elsewhere if you prefer. An optional
58
+ `[khipumaq]` section with `person = <your name>` lets the server's
59
+ sentence name you ("Before asking <name> what happened…"); the default
60
+ is "the user".
61
+
62
+ 2. Wire this machine:
63
+
64
+ ```sh
65
+ uvx --python 3.14 khipumaq install
66
+ uvx --python 3.14 khipumaq sweep # first run ingests everything on disk
67
+ ```
68
+
69
+ `install` adds the Claude Code SessionEnd hook, the MCP server entry, the
70
+ Codex hooks (and the trust Codex requires before running them), a daily
71
+ systemd user timer for the sweep, and — on WSL — the MCP entry for Claude
72
+ Code and Claude Desktop on Windows. `khipumaq uninstall` removes all of it
73
+ and leaves the store alone.
74
+
75
+ 3. Restart Claude Code. Run `install` on each machine whose sessions should
76
+ land in the store; they can all point at one database.
77
+
78
+ Remote or hosted ArangoDB (ArangoDB Cloud, a server across a WAN) should work
79
+ through the same config file but is **not tested**; pull requests welcome.
80
+
81
+ ## Privacy
82
+
83
+ The store holds your conversations in full. It lives where you put it and
84
+ nowhere else: khipumaq sends nothing to any service but your database. Its
85
+ operational event log (`~/.local/state/llm-memory/events.jsonl`) records
86
+ identifiers, digests, and counts, never query text or episode content. Point
87
+ it at a database on a network you trust.
88
+
89
+ ## Status
90
+
91
+ Pre-alpha, and used daily. Design notes and the record of how it got here are
92
+ in `docs/superpowers/specs/2026-09-01-khipumaq-design.md`.
93
+
94
+ ## License
95
+
96
+ MIT. Contributions are accepted under the Developer Certificate of Origin; see
97
+ [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "khipumaq"
3
+ version = "0.1.2"
4
+ description = "An episodic store of every prior Claude Code and Codex session — the user's words and the assistant's responses — searchable by the instances that come after."
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "memory",
11
+ "episodic",
12
+ "llm",
13
+ "agent",
14
+ "arangodb",
15
+ "mcp",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 2 - Pre-Alpha",
19
+ "Programming Language :: Python :: 3",
20
+ ]
21
+ dependencies = [
22
+ "mcp[cli]>=1.28,<2",
23
+ "python-arango>=8.3.3",
24
+ ]
25
+
26
+ [[project.authors]]
27
+ name = "Tony"
28
+ email = "fsgeek@cs.ubc.ca"
29
+
30
+ [project.scripts]
31
+ khipumaq = "khipumaq.cli:main"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "opentimestamps-client>=0.7.2",
36
+ "pytest>=9.1.0",
37
+ "pyyaml>=6.0.3",
38
+ ]
39
+
40
+ [build-system]
41
+ requires = ["uv_build>=0.10,<0.13"]
42
+ build-backend = "uv_build"
43
+
44
+ [tool.uv.build-backend]
45
+ module-root = "src"
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "khipumaq"
3
+ version = "0.1.2"
4
+ description = "An episodic store of every prior Claude Code and Codex session — the user's words and the assistant's responses — searchable by the instances that come after."
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Tony", email = "fsgeek@cs.ubc.ca" }]
10
+ keywords = ["memory", "episodic", "llm", "agent", "arangodb", "mcp"]
11
+ classifiers = [
12
+ "Development Status :: 2 - Pre-Alpha",
13
+ "Programming Language :: Python :: 3",
14
+ ]
15
+ dependencies = [
16
+ "mcp[cli]>=1.28,<2", # FastMCP was renamed in mcp 2; migrate deliberately
17
+ "python-arango>=8.3.3",
18
+ ]
19
+
20
+ [project.scripts]
21
+ khipumaq = "khipumaq.cli:main"
22
+
23
+ [dependency-groups]
24
+ # Repo tooling, not shipped: the suite, the June eval scripts (eval/ reads
25
+ # queries.yaml), and the post-commit OpenTimestamps hook.
26
+ dev = [
27
+ "opentimestamps-client>=0.7.2",
28
+ "pytest>=9.1.0",
29
+ "pyyaml>=6.0.3",
30
+ ]
31
+
32
+ [build-system]
33
+ requires = ["uv_build>=0.10,<0.13"]
34
+ build-backend = "uv_build"
35
+
36
+ [tool.uv.build-backend]
37
+ module-root = "src"
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
File without changes
@@ -0,0 +1,194 @@
1
+ """Entry point for the `khipumaq` command.
2
+
3
+ Imports are deferred to the subcommand that needs them: `codex-hook` must
4
+ detach within Codex's one-second hook budget, so it cannot pay for the MCP or
5
+ Arango imports it never uses.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+
14
+ def main(argv=None):
15
+ parser = argparse.ArgumentParser(prog="khipumaq")
16
+ sub = parser.add_subparsers(dest="command", required=True)
17
+ sub.add_parser("serve", help="run the read-only MCP server (stdio)")
18
+ ingest = sub.add_parser("ingest", help="ingest sessions (see `khipumaq ingest -h`)", add_help=False)
19
+ ingest.add_argument("rest", nargs=argparse.REMAINDER)
20
+ sub.add_parser("describe", help="print what the store holds")
21
+ sweep = sub.add_parser("sweep", help="ingest this machine's sessions changed since the last sweep")
22
+ sweep.add_argument("--all", action="store_true", help="ignore the last sweep; ingest every session file")
23
+ install = sub.add_parser("install", help="wire hooks and the MCP server on this machine")
24
+ install.add_argument("--no-codex", action="store_true", help="skip the Codex hooks")
25
+ sub.add_parser("uninstall", help="remove khipumaq's hooks and MCP entry")
26
+ sub.add_parser("codex-hook", help="(run by Codex) detach an ingest of the closing rollout")
27
+ args = parser.parse_args(argv)
28
+
29
+ if args.command == "serve":
30
+ from khipumaq.mcp_server import mcp
31
+
32
+ mcp.run()
33
+ return 0
34
+ if args.command == "ingest":
35
+ from khipumaq.ingest import main as ingest_main
36
+
37
+ return ingest_main(args.rest)
38
+ if args.command == "describe":
39
+ from khipumaq.db import get_database
40
+ from khipumaq.describe import describe
41
+
42
+ print(json.dumps(describe(get_database()), indent=2))
43
+ return 0
44
+ if args.command == "sweep":
45
+ return _sweep(everything=args.all)
46
+ if args.command == "codex-hook":
47
+ from khipumaq.setup import codex_hook
48
+
49
+ return codex_hook()
50
+ if args.command == "install":
51
+ return _install(skip_codex=args.no_codex)
52
+ return _uninstall()
53
+
54
+
55
+ SWEEP_STATE = Path.home() / ".local" / "state" / "khipumaq" / "last-sweep"
56
+ SWEEP_MARGIN = 86400 # re-read a day before the last sweep: sessions still open then
57
+
58
+
59
+ def _sweep(everything):
60
+ """Ingest session files modified since the last successful sweep, so a
61
+ failed hook is caught the next time this runs (spec D4 layer 2). The first
62
+ run, or --all, reads everything still on disk."""
63
+ import socket
64
+ import time
65
+
66
+ from khipumaq.db import get_database
67
+ from khipumaq.ingest import read_machine_id, sweep
68
+ from khipumaq.observability import emit_ingest_event
69
+ from khipumaq.setup import codex_home
70
+
71
+ started = time.time()
72
+ since = None
73
+ if not everything and SWEEP_STATE.exists():
74
+ since = float(SWEEP_STATE.read_text()) - SWEEP_MARGIN
75
+ host, claude_root = socket.gethostname(), Path.home() / ".claude" / "projects"
76
+ result = sweep(get_database(), claude_root, codex_home() / "sessions", since=since,
77
+ host=host, machine_id=read_machine_id())
78
+ for kind, root in (("claude", claude_root), ("codex", codex_home() / "sessions")):
79
+ files, count = result[kind]
80
+ emit_ingest_event(kind=f"sweep-{kind}", label=None, host=host, count=count, source_file=root)
81
+ print(f"sweep: {kind}: {count} episodes from {files} files under {root}")
82
+ _sweep_windows(get_database(), since, host)
83
+ SWEEP_STATE.parent.mkdir(parents=True, exist_ok=True)
84
+ SWEEP_STATE.write_text(str(started))
85
+ return 0
86
+
87
+
88
+ def _sweep_windows(db, since, host):
89
+ """On WSL, also sweep the Windows user's Claude Code, Cowork, and Codex
90
+ transcripts: Windows runs no hooks of ours, so this is their only path in."""
91
+ from khipumaq import wsl
92
+ from khipumaq.ingest import sweep
93
+ from khipumaq.observability import emit_ingest_event
94
+
95
+ profile = wsl.windows_profile()
96
+ if profile is None:
97
+ return
98
+ machine_id = wsl.windows_machine_id()
99
+ totals = {}
100
+ for claude_root, codex_root, label in wsl.sources(profile):
101
+ result = sweep(db, claude_root, codex_root, since=since, host=host, machine_id=machine_id,
102
+ canonical=wsl.windows_path, label=label)
103
+ for kind, (files, count) in result.items():
104
+ name = label or f"windows-{kind}"
105
+ f0, c0 = totals.get(name, (0, 0))
106
+ totals[name] = (f0 + files, c0 + count)
107
+ for name, (files, count) in totals.items():
108
+ emit_ingest_event(kind=f"sweep-{name}", label=None, host=host, count=count,
109
+ source_file=wsl.windows_path(profile))
110
+ print(f"sweep: {name}: {count} episodes from {files} files under {wsl.windows_path(profile)}")
111
+
112
+
113
+ def _claude_paths():
114
+ home = Path.home()
115
+ return home / ".claude" / "settings.json", home / ".claude.json"
116
+
117
+
118
+ def _install(skip_codex):
119
+ from khipumaq import setup
120
+ from khipumaq.db import config_path
121
+
122
+ status = 0
123
+ setup.install_claude(*_claude_paths())
124
+ print("khipumaq: Claude Code SessionEnd hook and MCP server installed.")
125
+ if skip_codex:
126
+ pass
127
+ elif not setup.codex_home().is_dir():
128
+ print(f"khipumaq: no Codex home at {setup.codex_home()}; Codex hooks skipped.")
129
+ elif (codex_bin := setup.codex_binary()) is None:
130
+ print("khipumaq: codex binary not found (set CODEX_BIN); Codex hooks skipped.", file=sys.stderr)
131
+ else:
132
+ try:
133
+ setup.install_codex(setup.codex_home(), codex_bin)
134
+ print("khipumaq: Codex SessionEnd/SubagentStop hooks installed and trusted.")
135
+ except RuntimeError as exc:
136
+ # The hooks are written but untrusted, so Codex will not run them.
137
+ print(f"khipumaq: Codex hooks NOT trusted: {exc}", file=sys.stderr)
138
+ status = 1
139
+ from khipumaq.wsl import windows_path, windows_profile
140
+
141
+ if (profile := windows_profile()) is not None:
142
+ for path in setup.install_windows_clients(profile):
143
+ print(f"khipumaq: MCP server registered for Windows in {windows_path(path)} (via wsl.exe).")
144
+ if setup.has_systemd_user():
145
+ setup.install_timer()
146
+ print("khipumaq: nightly sweep timer enabled (systemctl --user status khipumaq-sweep.timer).")
147
+ else:
148
+ print("khipumaq: no systemd user session; schedule `khipumaq sweep` yourself.", file=sys.stderr)
149
+ try:
150
+ print(f"khipumaq: database config: {config_path()}")
151
+ except FileNotFoundError as exc:
152
+ print(f"khipumaq: {exc}\n Hooks and server will fail until it exists.", file=sys.stderr)
153
+ status = 1
154
+ else:
155
+ status = _ensure_store() or status
156
+ print("khipumaq: restart Claude Code for the MCP server to load.")
157
+ return status
158
+
159
+
160
+ def _ensure_store():
161
+ """Create the episodes collection and its search view on a fresh database;
162
+ an existing store is left as it is."""
163
+ from khipumaq.db import get_database
164
+ from khipumaq.index import EPISODES, ensure_index
165
+
166
+ try:
167
+ db = get_database()
168
+ if db.has_collection(EPISODES):
169
+ print(f"khipumaq: store reachable, {db.collection(EPISODES).count():,} episodes.")
170
+ else:
171
+ ensure_index(db)
172
+ print("khipumaq: store created (episodes collection and search view).")
173
+ except Exception as exc: # noqa: BLE001 — any failure here is worth naming
174
+ print(f"khipumaq: database unreachable ({type(exc).__name__}: {exc}).", file=sys.stderr)
175
+ return 1
176
+ return 0
177
+
178
+
179
+ def _uninstall():
180
+ from khipumaq import setup
181
+
182
+ setup.uninstall_claude(*_claude_paths())
183
+ setup.uninstall_codex(setup.codex_home())
184
+ setup.uninstall_timer()
185
+ from khipumaq.wsl import windows_profile
186
+
187
+ if (profile := windows_profile()) is not None:
188
+ setup.uninstall_windows_clients(profile)
189
+ print("khipumaq: hooks, MCP entry, and sweep timer removed. The store is untouched.")
190
+ return 0
191
+
192
+
193
+ if __name__ == "__main__":
194
+ sys.exit(main())
@@ -0,0 +1,56 @@
1
+ import configparser
2
+ import os
3
+ from pathlib import Path
4
+
5
+ from arango import ArangoClient
6
+
7
+ # The source checkout's config/, where every machine kept it before packaging.
8
+ # Read last, so a machine still running from a checkout keeps working until its
9
+ # config moves to ~/.config/khipumaq/.
10
+ _CHECKOUT_CONFIG = Path(__file__).resolve().parents[2] / "config" / "db-config.ini"
11
+
12
+
13
+ def config_path():
14
+ """Where the database config lives: $KHIPUMAQ_CONFIG if set (and then only
15
+ there), else $XDG_CONFIG_HOME/khipumaq/db-config.ini (default ~/.config),
16
+ else the source checkout's config/db-config.ini. Returns the first that
17
+ exists; raises naming every place looked, so a missing config is never a
18
+ silent fallback to somewhere else."""
19
+ if os.environ.get("KHIPUMAQ_CONFIG"):
20
+ candidates = [Path(os.environ["KHIPUMAQ_CONFIG"])]
21
+ else:
22
+ xdg = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
23
+ candidates = [xdg / "khipumaq" / "db-config.ini", _CHECKOUT_CONFIG]
24
+ for path in candidates:
25
+ if path.exists():
26
+ return path
27
+ raise FileNotFoundError(
28
+ "DB config not found; looked in: " + ", ".join(str(p) for p in candidates)
29
+ )
30
+
31
+
32
+ def _load_config(path):
33
+ parser = configparser.ConfigParser()
34
+ parser.read(path)
35
+ return parser["database"]
36
+
37
+
38
+ def person(path=None):
39
+ """Who these sessions are with, as the server's sentence should name them:
40
+ `person` under an optional [khipumaq] section of the same config file,
41
+ else "the user"."""
42
+ parser = configparser.ConfigParser()
43
+ parser.read(path or config_path())
44
+ return parser.get("khipumaq", "person", fallback="the user")
45
+
46
+
47
+ def get_database(path=None):
48
+ """Return a python-arango Database handle for the scoped llm_memory user.
49
+ Fail-stop: missing config or unreachable server raises rather than degrading."""
50
+ cfg = _load_config(path or config_path())
51
+ client = ArangoClient(hosts=f"http://{cfg['host']}:{cfg['port']}")
52
+ return client.db(
53
+ cfg["database"],
54
+ username=cfg["user_name"],
55
+ password=cfg["user_password"],
56
+ )
@@ -0,0 +1,103 @@
1
+ """What the store holds, said in one sentence (khipumaq D5).
2
+
3
+ `describe(db)` is the read-only census: counts by label and host plus the
4
+ date range. `instructions(db, ...)` turns that into the sentence the MCP
5
+ server says about itself at start, in the register of qhaway's MEMORY.md
6
+ line: what is here, how fresh it is, and when to reach for it. The sentence
7
+ is honest about staleness on purpose — a store that implies freshness it does
8
+ not have teaches the instance to stop searching.
9
+ """
10
+
11
+ import os
12
+ from datetime import UTC, datetime
13
+
14
+ from khipumaq.index import EPISODES
15
+ from khipumaq.ingest import label_from_path
16
+
17
+ SERVER_NAME = "khipumaq"
18
+ STALE_AFTER_HOURS = 48
19
+
20
+ _STATS_AQL = """
21
+ LET total = LENGTH(@@col)
22
+ LET newest = MAX(FOR d IN @@col RETURN d.ts)
23
+ LET oldest = MIN(FOR d IN @@col RETURN d.ts)
24
+ LET labels = (FOR d IN @@col COLLECT l = d.experiment_label WITH COUNT INTO n
25
+ SORT n DESC RETURN {label: l, count: n})
26
+ LET hosts = (FOR d IN @@col COLLECT h = d.host WITH COUNT INTO n
27
+ SORT n DESC RETURN {host: h, count: n})
28
+ RETURN {episodes: total, newest: newest, oldest: oldest,
29
+ labels: labels, hosts: hosts}
30
+ """
31
+
32
+
33
+ def describe(db):
34
+ """Counts by label and host, total, and the oldest/newest episode
35
+ timestamps. Episodes ingested before host capture have host null."""
36
+ return next(iter(db.aql.execute(_STATS_AQL, bind_vars={"@col": EPISODES})))
37
+
38
+
39
+ def project_label(project_dir=None):
40
+ """Label for the project the *consuming* session runs in. Claude Code
41
+ launches the server with cwd pinned to this repo but exports
42
+ CLAUDE_PROJECT_DIR; map that path to the same label ingest derives from
43
+ the `~/.claude/projects/<name>` directory. None when not under Claude."""
44
+ project_dir = project_dir or os.environ.get("CLAUDE_PROJECT_DIR")
45
+ return label_from_path(project_dir) if project_dir else None
46
+
47
+
48
+ def _parse_ts(ts):
49
+ return datetime.fromisoformat(ts.replace("Z", "+00:00"))
50
+
51
+
52
+ def _plural(n, unit):
53
+ return f"{n} {unit}{'' if n == 1 else 's'} ago"
54
+
55
+
56
+ def _age(newest, now):
57
+ delta = now - _parse_ts(newest)
58
+ hours = delta.total_seconds() / 3600
59
+ if hours < 1:
60
+ return _plural(max(int(delta.total_seconds() // 60), 1), "minute")
61
+ if hours < 48:
62
+ return _plural(int(hours), "hour")
63
+ return _plural(int(hours // 24), "day")
64
+
65
+
66
+ def sentence(stats, label=None, now=None, person="the user"):
67
+ """The server's one sentence about itself, from a `describe()` result.
68
+ `person` is who the sessions are with; the trigger is said in their name
69
+ because a person saying "I don't recall" is audible to the instance, where
70
+ its own ignorance is not (amendment A2)."""
71
+ now = now or datetime.now(UTC)
72
+ total = stats["episodes"]
73
+ if not total:
74
+ return (
75
+ f"{SERVER_NAME} holds no episodes yet; ingestion has not run. "
76
+ "search() will find nothing until it does."
77
+ )
78
+ hosts = [h["host"] for h in stats["hosts"] if h["host"]]
79
+ newest = stats["newest"]
80
+ hours_old = (now - _parse_ts(newest)).total_seconds() / 3600
81
+ freshness = f"newest {_age(newest, now)}"
82
+ if hours_old > STALE_AFTER_HOURS:
83
+ freshness += " — ingestion may be broken"
84
+ text = (
85
+ f"{SERVER_NAME} holds {total:,} episodes from every prior session "
86
+ f"across {len(stats['labels'])} projects on {len(hosts)} machines, "
87
+ f"{freshness}"
88
+ )
89
+ if label:
90
+ count = next(
91
+ (l["count"] for l in stats["labels"] if l["label"] == label), 0
92
+ )
93
+ text += f"; this project is `{label}` ({count:,} episodes)"
94
+ text += (
95
+ f". It holds {person}'s words and prior assistant responses, not "
96
+ f"summaries. Before asking {person} what happened or what was decided, "
97
+ f"search() first; when {person} says \"I don't recall\", search()."
98
+ )
99
+ return text
100
+
101
+
102
+ def instructions(db, project_dir=None, now=None, person="the user"):
103
+ return sentence(describe(db), project_label(project_dir), now, person)
@@ -0,0 +1,4 @@
1
+ def hit_at_k(result_cycles, expected_cycles, k=3):
2
+ """True if any expected cycle appears within the top-k result cycles."""
3
+ expected = set(expected_cycles)
4
+ return any(cycle in expected for cycle in result_cycles[:k])