memhub-sdk 0.1.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.
- memhub/__init__.py +10 -0
- memhub/__main__.py +5 -0
- memhub/capture/__init__.py +9 -0
- memhub/capture/checkpoint.py +89 -0
- memhub/capture/cursor_plan.py +73 -0
- memhub/capture/transcript.py +121 -0
- memhub/cli/__init__.py +1 -0
- memhub/cli/hook_commands.py +138 -0
- memhub/cli/main.py +102 -0
- memhub/cli/setup_commands.py +127 -0
- memhub/cli/streams.py +28 -0
- memhub/cli/syncbot_commands.py +109 -0
- memhub/cli/workspace.py +43 -0
- memhub/client.py +164 -0
- memhub/config.py +145 -0
- memhub/errors.py +19 -0
- memhub/git_repo.py +146 -0
- memhub/hooks.py +110 -0
- memhub/local_store.py +178 -0
- memhub/models.py +86 -0
- memhub/outbound.py +101 -0
- memhub/push_range.py +106 -0
- memhub/py.typed +0 -0
- memhub/rekal/LICENSE +201 -0
- memhub/rekal/__init__.py +5 -0
- memhub/rekal/gitx.py +40 -0
- memhub/rekal/scrub/__init__.py +10 -0
- memhub/rekal/scrub/paths.py +84 -0
- memhub/rekal/scrub/scrub_payload.py +34 -0
- memhub/rekal/scrub/secrets.py +171 -0
- memhub/rekal/session/__init__.py +31 -0
- memhub/rekal/session/bench.py +48 -0
- memhub/rekal/session/claude.py +177 -0
- memhub/rekal/session/codex.py +158 -0
- memhub/rekal/session/codex_entries.py +139 -0
- memhub/rekal/session/compressed.py +38 -0
- memhub/rekal/session/content_blocks.py +126 -0
- memhub/rekal/session/decoding.py +128 -0
- memhub/rekal/session/identity.py +33 -0
- memhub/rekal/session/models.py +114 -0
- memhub/rekal/session/repo_paths.py +35 -0
- memhub/rekal/session/transcript.py +203 -0
- memhub/repo_name.py +46 -0
- memhub/syncbot/__init__.py +5 -0
- memhub/syncbot/event_queue.py +91 -0
- memhub/syncbot/push_events.py +149 -0
- memhub/syncbot/sender.py +152 -0
- memhub/transport.py +93 -0
- memhub/upload.py +46 -0
- memhub/version.py +3 -0
- memhub/wire.py +182 -0
- memhub_sdk-0.1.0.dist-info/METADATA +225 -0
- memhub_sdk-0.1.0.dist-info/RECORD +59 -0
- memhub_sdk-0.1.0.dist-info/WHEEL +5 -0
- memhub_sdk-0.1.0.dist-info/entry_points.txt +2 -0
- memhub_sdk-0.1.0.dist-info/licenses/LICENSE +201 -0
- memhub_sdk-0.1.0.dist-info/licenses/NOTICE +19 -0
- memhub_sdk-0.1.0.dist-info/licenses/src/memhub/rekal/LICENSE +201 -0
- memhub_sdk-0.1.0.dist-info/top_level.txt +1 -0
memhub/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Python SDK for MemHub: git-aware memory for AI coding agents."""
|
|
2
|
+
|
|
3
|
+
from memhub.client import Memhub
|
|
4
|
+
from memhub.errors import MemhubError
|
|
5
|
+
from memhub.models import RecalledMemory, RecallResult, WriteResult
|
|
6
|
+
from memhub.version import VERSION
|
|
7
|
+
|
|
8
|
+
__version__ = VERSION
|
|
9
|
+
|
|
10
|
+
__all__ = ["Memhub", "MemhubError", "RecallResult", "RecalledMemory", "WriteResult"]
|
memhub/__main__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Agent session capture.
|
|
2
|
+
|
|
3
|
+
Finds the agent sessions for a repository and queues the turns added since the last checkpoint
|
|
4
|
+
as one outbox record for the commit that just happened.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from memhub.capture.checkpoint import CheckpointResult, checkpoint
|
|
8
|
+
|
|
9
|
+
__all__ = ["CheckpointResult", "checkpoint"]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""The checkpoint run by the post-commit hook.
|
|
2
|
+
|
|
3
|
+
It never touches the network: uploading is the push command's job.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import secrets
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import TextIO
|
|
9
|
+
|
|
10
|
+
from memhub.capture.transcript import capture_transcript
|
|
11
|
+
from memhub.errors import MemhubError
|
|
12
|
+
from memhub.git_repo import GitRepo
|
|
13
|
+
from memhub.local_store import Cursor, LocalStore
|
|
14
|
+
from memhub.rekal import gitx
|
|
15
|
+
from memhub.rekal.session import ADAPTERS
|
|
16
|
+
from memhub.wire import CommitRecord, SessionSlice, utc_timestamp
|
|
17
|
+
|
|
18
|
+
RECORD_ID_BYTES = 16
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class CheckpointResult:
|
|
23
|
+
"""One checkpoint's summary for the command's output."""
|
|
24
|
+
|
|
25
|
+
commit_sha: str = ""
|
|
26
|
+
sessions: int = 0
|
|
27
|
+
turns: int = 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def checkpoint(repo: GitRepo, store: LocalStore, warnings: TextIO) -> CheckpointResult:
|
|
31
|
+
"""Captures new agent turns for repo and queues them under HEAD.
|
|
32
|
+
|
|
33
|
+
It does nothing during a rebase: git fires post-commit for every replayed commit, and those
|
|
34
|
+
carry old reasoning, so linking the live session to each would be wrong. The next real commit
|
|
35
|
+
sweeps up whatever was added meanwhile.
|
|
36
|
+
|
|
37
|
+
Raises:
|
|
38
|
+
MemhubError: Only for local database or git failures; a bad transcript is warned and
|
|
39
|
+
skipped.
|
|
40
|
+
"""
|
|
41
|
+
root = str(repo.root)
|
|
42
|
+
if gitx.rebase_in_progress(root):
|
|
43
|
+
return CheckpointResult()
|
|
44
|
+
slices, cursors = _collect_sessions(root, store, warnings)
|
|
45
|
+
if not slices:
|
|
46
|
+
store.save_checkpoint(None, cursors)
|
|
47
|
+
return CheckpointResult()
|
|
48
|
+
record = _new_commit_record(repo, slices)
|
|
49
|
+
store.save_checkpoint(record, cursors)
|
|
50
|
+
return CheckpointResult(
|
|
51
|
+
commit_sha=record.commit_sha,
|
|
52
|
+
sessions=len(slices),
|
|
53
|
+
turns=sum(len(item.turns) for item in slices),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _collect_sessions(
|
|
58
|
+
git_root: str, store: LocalStore, warnings: TextIO
|
|
59
|
+
) -> tuple[list[SessionSlice], list[Cursor]]:
|
|
60
|
+
slices: list[SessionSlice] = []
|
|
61
|
+
cursors: list[Cursor] = []
|
|
62
|
+
for adapter in ADAPTERS:
|
|
63
|
+
try:
|
|
64
|
+
refs = adapter.discover(git_root)
|
|
65
|
+
except (OSError, ValueError) as error:
|
|
66
|
+
warnings.write(f"memhub: could not list {adapter.name} sessions: {error}\n")
|
|
67
|
+
continue
|
|
68
|
+
for ref in refs:
|
|
69
|
+
captured = capture_transcript(store, adapter, ref, warnings)
|
|
70
|
+
if captured.cursor:
|
|
71
|
+
cursors.append(captured.cursor)
|
|
72
|
+
if captured.slice:
|
|
73
|
+
slices.append(captured.slice)
|
|
74
|
+
return slices, cursors
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _new_commit_record(repo: GitRepo, slices: list[SessionSlice]) -> CommitRecord:
|
|
78
|
+
sha = repo.head_sha()
|
|
79
|
+
if not sha:
|
|
80
|
+
raise MemhubError("repository has no commits yet")
|
|
81
|
+
return CommitRecord(
|
|
82
|
+
record_id=secrets.token_hex(RECORD_ID_BYTES),
|
|
83
|
+
commit_sha=sha,
|
|
84
|
+
parent_shas=repo.parents(sha),
|
|
85
|
+
branch=repo.current_branch() or "",
|
|
86
|
+
author=repo.author(sha),
|
|
87
|
+
captured_at=utc_timestamp(),
|
|
88
|
+
sessions=slices,
|
|
89
|
+
)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Turn dedup: decides which turns of a parsed transcript are new since the last checkpoint.
|
|
2
|
+
|
|
3
|
+
The logic follows rekal-cli's checkpoint (turnsExtend), but keeps a hash of the captured prefix
|
|
4
|
+
instead of a second copy of every turn.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
from memhub.local_store import Cursor
|
|
11
|
+
from memhub.rekal.session import SessionPayload, Turn
|
|
12
|
+
|
|
13
|
+
# Keeps a fallback session ID short while staying collision-free in practice for the few hundred
|
|
14
|
+
# transcripts one machine holds.
|
|
15
|
+
SHORT_HASH_LENGTH = 16
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class CapturePlan:
|
|
20
|
+
"""Where in a transcript this checkpoint starts taking turns and tool calls."""
|
|
21
|
+
|
|
22
|
+
start_turn: int = 0
|
|
23
|
+
start_tool_call: int = 0
|
|
24
|
+
generation: int = 0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def plan_capture(previous: Cursor | None, payload: SessionPayload) -> CapturePlan:
|
|
28
|
+
"""Compares a freshly parsed transcript with its stored cursor.
|
|
29
|
+
|
|
30
|
+
A live conversation only grows, so the usual answer is "start where the last checkpoint
|
|
31
|
+
stopped". If the captured turns no longer match (the transcript was truncated or replaced at
|
|
32
|
+
the same path), it is treated as a new conversation: capture restarts at turn 0 under the
|
|
33
|
+
next generation, which gives it a new session key, so the server never splices unrelated
|
|
34
|
+
turns onto the old session.
|
|
35
|
+
"""
|
|
36
|
+
if previous is None:
|
|
37
|
+
return CapturePlan()
|
|
38
|
+
captured = previous.turns_captured
|
|
39
|
+
if len(payload.turns) < captured or hash_turns(payload.turns[:captured]) != (
|
|
40
|
+
previous.prefix_hash
|
|
41
|
+
):
|
|
42
|
+
return CapturePlan(generation=previous.generation + 1)
|
|
43
|
+
return CapturePlan(
|
|
44
|
+
start_turn=captured,
|
|
45
|
+
start_tool_call=min(previous.tool_calls_captured, len(payload.tool_calls)),
|
|
46
|
+
generation=previous.generation,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def hash_turns(turns: list[Turn]) -> str:
|
|
51
|
+
"""Fingerprints a run of turns. Role is included, so a re-labelled turn counts as a rewrite."""
|
|
52
|
+
hasher = hashlib.sha256()
|
|
53
|
+
for turn in turns:
|
|
54
|
+
hasher.update(turn.role.encode("utf-8") + b"\0" + turn.content.encode("utf-8") + b"\0")
|
|
55
|
+
return hasher.hexdigest()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def session_key(agent: str, payload: SessionPayload, cache_key: str, generation: int) -> str:
|
|
59
|
+
"""Builds the ID the server and Memsy use for a conversation.
|
|
60
|
+
|
|
61
|
+
It must be stable across commits and must not contain local paths, which is why a transcript
|
|
62
|
+
without its own session ID falls back to a hash of its cache key rather than the key itself.
|
|
63
|
+
"""
|
|
64
|
+
session_id = (
|
|
65
|
+
payload.session_id
|
|
66
|
+
or hashlib.sha256(cache_key.encode("utf-8")).hexdigest()[:SHORT_HASH_LENGTH]
|
|
67
|
+
)
|
|
68
|
+
key = f"{agent}:{session_id}"
|
|
69
|
+
if payload.agent_id:
|
|
70
|
+
key += f"/{payload.agent_id}"
|
|
71
|
+
if generation > 0:
|
|
72
|
+
key += f"~{generation}"
|
|
73
|
+
return key
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Reads one agent transcript and cuts out the turns added since its cursor."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
from memhub.capture.cursor_plan import CapturePlan, hash_turns, plan_capture, session_key
|
|
8
|
+
from memhub.local_store import Cursor, LocalStore
|
|
9
|
+
from memhub.rekal import scrub
|
|
10
|
+
from memhub.rekal.session import Adapter, SessionPayload, SessionRef, content_hash, skip_capture
|
|
11
|
+
from memhub.wire import SessionSlice, ToolCall, Turn, utc_timestamp
|
|
12
|
+
|
|
13
|
+
# Codex compresses idle sessions to .jsonl.zst and decompresses them on resume, so both
|
|
14
|
+
# spellings must map to the same cursor.
|
|
15
|
+
CODEX_COMPRESSED_SUFFIX = ".zst"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class TranscriptCapture:
|
|
20
|
+
"""What one transcript contributes to a checkpoint.
|
|
21
|
+
|
|
22
|
+
Either field may be None: an unchanged transcript yields neither, and one that changed
|
|
23
|
+
without adding turns (for example a new tool result) yields only an updated cursor.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
slice: SessionSlice | None = None
|
|
27
|
+
cursor: Cursor | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def capture_transcript(
|
|
31
|
+
store: LocalStore, adapter: Adapter, ref: SessionRef, warnings: TextIO
|
|
32
|
+
) -> TranscriptCapture:
|
|
33
|
+
"""Captures the new part of one transcript. Problems with the file are warned and skipped."""
|
|
34
|
+
key = cache_key(adapter, ref)
|
|
35
|
+
previous = store.cursor(key)
|
|
36
|
+
try:
|
|
37
|
+
size, digest = _fingerprint(adapter, ref)
|
|
38
|
+
except OSError as error:
|
|
39
|
+
warnings.write(f"memhub: skipped {adapter.name} transcript: {error}\n")
|
|
40
|
+
return TranscriptCapture()
|
|
41
|
+
if previous and digest and (previous.file_size, previous.content_hash) == (size, digest):
|
|
42
|
+
return TranscriptCapture()
|
|
43
|
+
payload = _parse_scrubbed(adapter, ref, warnings)
|
|
44
|
+
if payload is None:
|
|
45
|
+
return TranscriptCapture()
|
|
46
|
+
plan = plan_capture(previous, payload)
|
|
47
|
+
cursor = Cursor(
|
|
48
|
+
cache_key=key,
|
|
49
|
+
session_key=session_key(adapter.name, payload, key, plan.generation),
|
|
50
|
+
file_size=size,
|
|
51
|
+
content_hash=digest,
|
|
52
|
+
turns_captured=len(payload.turns),
|
|
53
|
+
tool_calls_captured=len(payload.tool_calls),
|
|
54
|
+
prefix_hash=hash_turns(payload.turns),
|
|
55
|
+
generation=plan.generation,
|
|
56
|
+
)
|
|
57
|
+
return TranscriptCapture(_build_slice(adapter.name, cursor.session_key, payload, plan), cursor)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cache_key(adapter: Adapter, ref: SessionRef) -> str:
|
|
61
|
+
"""Returns the transcript's local identity: its path, or "agent:id" for database sessions."""
|
|
62
|
+
if not ref.path:
|
|
63
|
+
return f"{adapter.name}:{ref.db_id}"
|
|
64
|
+
if adapter.name == "codex":
|
|
65
|
+
return ref.path.removesuffix(CODEX_COMPRESSED_SUFFIX)
|
|
66
|
+
return ref.path
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _parse_scrubbed(adapter: Adapter, ref: SessionRef, warnings: TextIO) -> SessionPayload | None:
|
|
70
|
+
"""Parses a transcript and removes secrets and home-folder names before anything is stored.
|
|
71
|
+
|
|
72
|
+
Returns None for a transcript to skip: unparseable, empty, or a benchmark session.
|
|
73
|
+
"""
|
|
74
|
+
try:
|
|
75
|
+
payload = adapter.parse(ref)
|
|
76
|
+
except (OSError, ValueError) as error:
|
|
77
|
+
warnings.write(f"memhub: could not parse {adapter.name} transcript: {error}\n")
|
|
78
|
+
return None
|
|
79
|
+
if payload is None:
|
|
80
|
+
return None
|
|
81
|
+
scrub.scrub(payload)
|
|
82
|
+
return None if skip_capture(payload) else payload
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _fingerprint(adapter: Adapter, ref: SessionRef) -> tuple[int, str]:
|
|
86
|
+
"""Returns the transcript's size and content hash.
|
|
87
|
+
|
|
88
|
+
Database-backed sessions have no file to hash, so they return an empty hash and are always
|
|
89
|
+
re-parsed; the turn cursor still stops their turns being captured twice.
|
|
90
|
+
"""
|
|
91
|
+
if not ref.path:
|
|
92
|
+
return 0, ""
|
|
93
|
+
contents = Path(ref.path).read_bytes()
|
|
94
|
+
return len(contents), content_hash(adapter, ref, contents)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _build_slice(
|
|
98
|
+
agent: str, key: str, payload: SessionPayload, plan: CapturePlan
|
|
99
|
+
) -> SessionSlice | None:
|
|
100
|
+
new_turns = payload.turns[plan.start_turn :]
|
|
101
|
+
new_tool_calls = payload.tool_calls[plan.start_tool_call :]
|
|
102
|
+
if not new_turns and not new_tool_calls:
|
|
103
|
+
return None
|
|
104
|
+
return SessionSlice(
|
|
105
|
+
session_key=key,
|
|
106
|
+
agent=agent,
|
|
107
|
+
first_turn=plan.start_turn,
|
|
108
|
+
turns=[
|
|
109
|
+
Turn(
|
|
110
|
+
index=plan.start_turn + offset,
|
|
111
|
+
role=turn.role,
|
|
112
|
+
content=turn.content,
|
|
113
|
+
timestamp=utc_timestamp(turn.timestamp) if turn.timestamp else "",
|
|
114
|
+
)
|
|
115
|
+
for offset, turn in enumerate(new_turns)
|
|
116
|
+
],
|
|
117
|
+
tool_calls=[
|
|
118
|
+
ToolCall(tool=call.tool, path=call.path, cmd_prefix=call.cmd_prefix)
|
|
119
|
+
for call in new_tool_calls
|
|
120
|
+
],
|
|
121
|
+
)
|
memhub/cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The memhub command line."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""The commands that capture and upload memory.
|
|
2
|
+
|
|
3
|
+
`memhub checkpoint` runs from post-commit, `memhub push` from pre-push, and `memhub flush` by
|
|
4
|
+
hand or after `git push --no-verify`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
from memhub import capture, config, outbound, push_range, upload
|
|
11
|
+
from memhub.cli.streams import EXIT_OK, Streams
|
|
12
|
+
from memhub.cli.syncbot_commands import queue_push_for_syncbot
|
|
13
|
+
from memhub.cli.workspace import Workspace, open_workspace
|
|
14
|
+
from memhub.errors import MemhubError
|
|
15
|
+
from memhub.outbound import OutboundRequest
|
|
16
|
+
from memhub.repo_name import repo_from_remote_url
|
|
17
|
+
from memhub.transport import Transport
|
|
18
|
+
from memhub.version import VERSION
|
|
19
|
+
from memhub.wire import RefUpdate
|
|
20
|
+
|
|
21
|
+
# Enough of a SHA to recognise the commit in a one-line message.
|
|
22
|
+
SHORT_SHA_LENGTH = 7
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class UploadJob:
|
|
27
|
+
"""One upload attempt: the remote, the pre-push lines (none for flush) and a deadline."""
|
|
28
|
+
|
|
29
|
+
remote: str
|
|
30
|
+
timeout_seconds: float
|
|
31
|
+
updates: list[RefUpdate] = field(default_factory=list)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run_checkpoint(_args: argparse.Namespace, streams: Streams) -> int:
|
|
35
|
+
"""Queues agent turns added since the last checkpoint under HEAD. Offline; always exits 0."""
|
|
36
|
+
try:
|
|
37
|
+
workspace = open_workspace()
|
|
38
|
+
with workspace.store:
|
|
39
|
+
result = capture.checkpoint(workspace.repo, workspace.store, streams.stderr)
|
|
40
|
+
except MemhubError as error:
|
|
41
|
+
return streams.warn(error)
|
|
42
|
+
if result.turns:
|
|
43
|
+
streams.stderr.write(
|
|
44
|
+
f"memhub: queued {result.turns} turn(s) from {result.sessions} session(s) "
|
|
45
|
+
f"for {result.commit_sha[:SHORT_SHA_LENGTH]}\n"
|
|
46
|
+
)
|
|
47
|
+
return EXIT_OK
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def run_push(args: argparse.Namespace, streams: Streams) -> int:
|
|
51
|
+
"""Uploads queued memory for the commits being pushed, and queues the push for SyncBot.
|
|
52
|
+
|
|
53
|
+
Always exits 0: a MemHub problem must never block a git push. Records that fail to upload
|
|
54
|
+
stay in the outbox for the next push or `memhub flush`.
|
|
55
|
+
"""
|
|
56
|
+
if streams.stdin.isatty():
|
|
57
|
+
return streams.warn(
|
|
58
|
+
MemhubError(
|
|
59
|
+
"`memhub push` reads ref updates from git's pre-push hook; "
|
|
60
|
+
"run `memhub flush` to upload by hand"
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
try:
|
|
64
|
+
updates = push_range.parse_ref_updates(streams.stdin)
|
|
65
|
+
if not updates:
|
|
66
|
+
return EXIT_OK
|
|
67
|
+
job = UploadJob(args.remote, upload.HOOK_TIMEOUT_SECONDS, updates)
|
|
68
|
+
workspace = open_workspace()
|
|
69
|
+
with workspace.store:
|
|
70
|
+
# SyncBot first: queueing is local and instant, and must not wait on the upload.
|
|
71
|
+
_queue_for_syncbot(workspace, args, updates, streams)
|
|
72
|
+
sent = upload_pending(workspace, job)
|
|
73
|
+
except MemhubError as error:
|
|
74
|
+
return streams.warn(error)
|
|
75
|
+
if sent:
|
|
76
|
+
streams.stderr.write(f"memhub: uploaded memory for {sent} commit(s)\n")
|
|
77
|
+
return EXIT_OK
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _queue_for_syncbot(
|
|
81
|
+
workspace: Workspace, args: argparse.Namespace, updates: list[RefUpdate], streams: Streams
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Queues the push for SyncBot; a failure here only warns, so the upload still happens."""
|
|
84
|
+
try:
|
|
85
|
+
queue_push_for_syncbot(workspace, args.remote, updates, args.git_pid)
|
|
86
|
+
except (MemhubError, OSError) as error:
|
|
87
|
+
streams.warn(MemhubError(f"SyncBot: {error}"))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def run_flush(args: argparse.Namespace, streams: Streams) -> int:
|
|
91
|
+
"""Uploads queued records whose commits are already on the remote."""
|
|
92
|
+
try:
|
|
93
|
+
workspace = open_workspace()
|
|
94
|
+
with workspace.store:
|
|
95
|
+
sent = upload_pending(workspace, UploadJob(args.remote, upload.FLUSH_TIMEOUT_SECONDS))
|
|
96
|
+
except MemhubError as error:
|
|
97
|
+
return streams.fail(error)
|
|
98
|
+
streams.stdout.write(f"Uploaded memory for {sent} commit(s)\n")
|
|
99
|
+
return EXIT_OK
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def upload_pending(workspace: Workspace, job: UploadJob) -> int:
|
|
103
|
+
"""Sends the outbox records the job selects and marks them sent.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
How many records went out.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
MemhubError: If the upload fails; nothing is marked and the records stay queued.
|
|
110
|
+
"""
|
|
111
|
+
unsent = workspace.store.unsent()
|
|
112
|
+
if not unsent:
|
|
113
|
+
return 0
|
|
114
|
+
remote_url = workspace.repo.remote_url(job.remote)
|
|
115
|
+
request = OutboundRequest(workspace.repo, job.remote, remote_url is not None, job.updates)
|
|
116
|
+
selection = outbound.select(request, unsent)
|
|
117
|
+
if not selection.records:
|
|
118
|
+
return 0
|
|
119
|
+
pending = len(selection.records)
|
|
120
|
+
server_url = workspace.settings.server_url
|
|
121
|
+
token = config.load_token(server_url)
|
|
122
|
+
if not token:
|
|
123
|
+
raise MemhubError(
|
|
124
|
+
f"{pending} record(s) waiting: no token for {server_url}; run `memhub login`"
|
|
125
|
+
)
|
|
126
|
+
transport = Transport(server_url, token, job.timeout_seconds, f"memhub-cli/{VERSION}")
|
|
127
|
+
# `git push <url>` hands the hook the URL itself in place of a remote name.
|
|
128
|
+
repo = repo_from_remote_url(remote_url or job.remote)
|
|
129
|
+
try:
|
|
130
|
+
upload.push_records(
|
|
131
|
+
transport, repo, workspace.settings.share_mode, selection.refs, selection.records
|
|
132
|
+
)
|
|
133
|
+
except MemhubError as error:
|
|
134
|
+
raise MemhubError(
|
|
135
|
+
f"upload failed, {pending} record(s) kept for the next push or `memhub flush`: {error}"
|
|
136
|
+
) from error
|
|
137
|
+
workspace.store.mark_sent([record.record_id for record in selection.records])
|
|
138
|
+
return pending
|
memhub/cli/main.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Entry point of the memhub command: parses arguments and runs one command."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
|
|
6
|
+
from memhub.cli.hook_commands import run_checkpoint, run_flush, run_push
|
|
7
|
+
from memhub.cli.setup_commands import run_init, run_login, run_status
|
|
8
|
+
from memhub.cli.streams import EXIT_OK, EXIT_USAGE, Streams
|
|
9
|
+
from memhub.cli.syncbot_commands import run_syncbot_send
|
|
10
|
+
from memhub.config import DEFAULT_SERVER_URL
|
|
11
|
+
from memhub.version import VERSION
|
|
12
|
+
from memhub.wire import SHARE_MODES
|
|
13
|
+
|
|
14
|
+
DEFAULT_REMOTE = "origin"
|
|
15
|
+
# `memhub init --syncbot` with no folder: SyncBot's place in the Nexus repository.
|
|
16
|
+
DEFAULT_SYNCBOT_DIR = "syncBot"
|
|
17
|
+
|
|
18
|
+
Command = Callable[[argparse.Namespace, Streams], int]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main(argv: list[str] | None = None, streams: Streams | None = None) -> int:
|
|
22
|
+
"""Runs the command named in argv (default: the process arguments).
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
The process exit code.
|
|
26
|
+
"""
|
|
27
|
+
streams = streams or Streams()
|
|
28
|
+
parser = _build_parser()
|
|
29
|
+
try:
|
|
30
|
+
args = parser.parse_args(argv)
|
|
31
|
+
except SystemExit as exit_request:
|
|
32
|
+
# argparse exits on --help (code 0) and on bad arguments (code 2); hand that back.
|
|
33
|
+
return int(exit_request.code or EXIT_OK)
|
|
34
|
+
if not hasattr(args, "run"):
|
|
35
|
+
parser.print_usage(streams.stderr)
|
|
36
|
+
return EXIT_USAGE
|
|
37
|
+
return args.run(args, streams)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
41
|
+
parser = argparse.ArgumentParser(
|
|
42
|
+
prog="memhub", description="memhub keeps AI agent memory tied to the commits it produced."
|
|
43
|
+
)
|
|
44
|
+
parser.add_argument("--version", action="version", version=f"memhub {VERSION}")
|
|
45
|
+
commands = parser.add_subparsers(title="commands")
|
|
46
|
+
|
|
47
|
+
_add_init_command(commands)
|
|
48
|
+
_add_command(
|
|
49
|
+
commands, "checkpoint", "Queue new agent turns under HEAD (post-commit)", run_checkpoint
|
|
50
|
+
)
|
|
51
|
+
push = _add_command(
|
|
52
|
+
commands, "push", "Upload memory for commits being pushed (pre-push)", run_push
|
|
53
|
+
)
|
|
54
|
+
push.add_argument("--remote", default=DEFAULT_REMOTE, help="remote git is pushing to")
|
|
55
|
+
push.add_argument("--git-pid", type=int, default=0, help="the `git push` process (hook only)")
|
|
56
|
+
flush = _add_command(
|
|
57
|
+
commands, "flush", "Upload memory whose commits are on the remote", run_flush
|
|
58
|
+
)
|
|
59
|
+
flush.add_argument(
|
|
60
|
+
"--remote", default=DEFAULT_REMOTE, help="remote that decides what is published"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
login = _add_command(commands, "login", "Save the token memhub uploads with", run_login)
|
|
64
|
+
login.add_argument("--token-stdin", action="store_true", help="read the token from stdin")
|
|
65
|
+
login.add_argument("--token", help="token to save (prefer --token-stdin: shell history)")
|
|
66
|
+
login.add_argument("--server", help="server the token is for (default: this repo's server)")
|
|
67
|
+
_add_command(commands, "status", "Show setup, hooks and outbox", run_status)
|
|
68
|
+
send = _add_command(
|
|
69
|
+
commands, "syncbot-send", "Send queued push events to SyncBot", run_syncbot_send
|
|
70
|
+
)
|
|
71
|
+
send.add_argument(
|
|
72
|
+
"--wait-pid", type=int, default=0, help="wait for this process to exit first (hook only)"
|
|
73
|
+
)
|
|
74
|
+
return parser
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _add_init_command(commands: "argparse._SubParsersAction[argparse.ArgumentParser]") -> None:
|
|
78
|
+
init = _add_command(commands, "init", "Set up memhub here and install its git hooks", run_init)
|
|
79
|
+
init.add_argument("--server", help=f"MemHub server URL (default {DEFAULT_SERVER_URL})")
|
|
80
|
+
init.add_argument(
|
|
81
|
+
"--share",
|
|
82
|
+
choices=SHARE_MODES,
|
|
83
|
+
help='who sees memory from unmerged branches: "team" (default) or "private" (only you)',
|
|
84
|
+
)
|
|
85
|
+
init.add_argument(
|
|
86
|
+
"--syncbot",
|
|
87
|
+
nargs="?",
|
|
88
|
+
const=DEFAULT_SYNCBOT_DIR,
|
|
89
|
+
metavar="FOLDER",
|
|
90
|
+
help=f"also send pushes to the SyncBot worker in FOLDER (default {DEFAULT_SYNCBOT_DIR})",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _add_command(
|
|
95
|
+
commands: "argparse._SubParsersAction[argparse.ArgumentParser]",
|
|
96
|
+
name: str,
|
|
97
|
+
summary: str,
|
|
98
|
+
run: Command,
|
|
99
|
+
) -> argparse.ArgumentParser:
|
|
100
|
+
command = commands.add_parser(name, help=summary, description=summary)
|
|
101
|
+
command.set_defaults(run=run)
|
|
102
|
+
return command
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""`memhub init`, `memhub login` and `memhub status`: setting memhub up and checking on it."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from memhub import config, hooks
|
|
9
|
+
from memhub.cli.streams import EXIT_OK, Streams
|
|
10
|
+
from memhub.cli.workspace import locate_repo, open_workspace
|
|
11
|
+
from memhub.errors import MemhubError
|
|
12
|
+
from memhub.hooks import HookState, HookStatus
|
|
13
|
+
from memhub.local_store import LocalStore
|
|
14
|
+
from memhub.syncbot import event_queue
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_init(args: argparse.Namespace, streams: Streams) -> int:
|
|
18
|
+
"""Creates the local data folder and config, and installs the git hooks. Safe to re-run."""
|
|
19
|
+
try:
|
|
20
|
+
repo, data_dir = locate_repo()
|
|
21
|
+
settings = config.load_repo_settings(data_dir)
|
|
22
|
+
settings = replace(
|
|
23
|
+
settings,
|
|
24
|
+
server_url=args.server or settings.server_url,
|
|
25
|
+
share_mode=args.share or settings.share_mode,
|
|
26
|
+
syncbot_dir=_resolve_syncbot_dir(repo.root, args.syncbot) or settings.syncbot_dir,
|
|
27
|
+
)
|
|
28
|
+
config.save_repo_settings(data_dir, settings)
|
|
29
|
+
with LocalStore(data_dir):
|
|
30
|
+
pass
|
|
31
|
+
statuses = hooks.install(repo.hooks_dir(), sys.executable)
|
|
32
|
+
except MemhubError as error:
|
|
33
|
+
return streams.fail(error)
|
|
34
|
+
_report_hooks(streams, statuses)
|
|
35
|
+
streams.stdout.write(
|
|
36
|
+
f"memhub is set up: server {settings.server_url}, share mode {settings.share_mode}, "
|
|
37
|
+
f"data in {data_dir}\n"
|
|
38
|
+
)
|
|
39
|
+
if settings.syncbot_dir:
|
|
40
|
+
streams.stdout.write(f"Pushes are also sent to SyncBot in {settings.syncbot_dir}\n")
|
|
41
|
+
return EXIT_OK
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_login(args: argparse.Namespace, streams: Streams) -> int:
|
|
45
|
+
"""Saves the token uploads are made with, for this repository's server by default."""
|
|
46
|
+
token = streams.stdin.readline() if args.token_stdin else (args.token or "")
|
|
47
|
+
token = token.strip()
|
|
48
|
+
if not token:
|
|
49
|
+
return streams.fail(
|
|
50
|
+
MemhubError(
|
|
51
|
+
"pass the token on stdin with --token-stdin (for example "
|
|
52
|
+
"`gh auth token | memhub login --token-stdin`) or with --token"
|
|
53
|
+
)
|
|
54
|
+
)
|
|
55
|
+
try:
|
|
56
|
+
server_url = args.server or _current_server_url()
|
|
57
|
+
config.save_token(server_url, token)
|
|
58
|
+
except (MemhubError, OSError) as error:
|
|
59
|
+
return streams.fail(error)
|
|
60
|
+
streams.stdout.write(f"Saved token for {server_url}\n")
|
|
61
|
+
return EXIT_OK
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def run_status(_args: argparse.Namespace, streams: Streams) -> int:
|
|
65
|
+
"""Shows the server, share mode, token, hooks and outbox of this repository."""
|
|
66
|
+
try:
|
|
67
|
+
workspace = open_workspace()
|
|
68
|
+
with workspace.store:
|
|
69
|
+
counts = workspace.store.counts()
|
|
70
|
+
hook_statuses = hooks.inspect(workspace.repo.hooks_dir())
|
|
71
|
+
token = config.load_token(workspace.settings.server_url)
|
|
72
|
+
except MemhubError as error:
|
|
73
|
+
return streams.fail(error)
|
|
74
|
+
hook_summary = ", ".join(f"{status.name} {status.state.value}" for status in hook_statuses)
|
|
75
|
+
lines = [
|
|
76
|
+
f"Repository: {workspace.repo.root}",
|
|
77
|
+
f"Data: {workspace.data_dir}",
|
|
78
|
+
f"Server: {workspace.settings.server_url}",
|
|
79
|
+
f"Share mode: {workspace.settings.share_mode}",
|
|
80
|
+
f"Token: {'saved' if token else 'missing (run `memhub login`)'}",
|
|
81
|
+
f"Hooks: {hook_summary}",
|
|
82
|
+
f"Outbox: {counts.unsent} waiting, {counts.sent} uploaded",
|
|
83
|
+
f"SyncBot: {_describe_syncbot(workspace.settings.syncbot_dir, workspace.data_dir)}",
|
|
84
|
+
]
|
|
85
|
+
streams.stdout.write("\n".join(lines) + "\n")
|
|
86
|
+
return EXIT_OK
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _resolve_syncbot_dir(repo_root: Path, requested: str | None) -> str:
|
|
90
|
+
"""Returns the absolute SyncBot folder for --syncbot, relative paths taken from the repo root.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
MemhubError: If the folder does not exist.
|
|
94
|
+
"""
|
|
95
|
+
if not requested:
|
|
96
|
+
return ""
|
|
97
|
+
folder = (repo_root / requested).resolve()
|
|
98
|
+
if not folder.is_dir():
|
|
99
|
+
raise MemhubError(f"SyncBot folder {folder} does not exist")
|
|
100
|
+
return str(folder)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _describe_syncbot(syncbot_dir: str, data_dir: Path) -> str:
|
|
104
|
+
if not syncbot_dir:
|
|
105
|
+
return "off (enable with `memhub init --syncbot`)"
|
|
106
|
+
waiting = sum(len(event_queue.load(path).events) for path in event_queue.queued_files(data_dir))
|
|
107
|
+
return f"{syncbot_dir}, {waiting} push event(s) waiting"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _current_server_url() -> str:
|
|
111
|
+
"""Returns the server of the repository around the working folder, else the default."""
|
|
112
|
+
try:
|
|
113
|
+
_, data_dir = locate_repo()
|
|
114
|
+
except MemhubError:
|
|
115
|
+
return config.load_repo_settings(None).server_url
|
|
116
|
+
return config.load_repo_settings(data_dir).server_url
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _report_hooks(streams: Streams, statuses: list[HookStatus]) -> None:
|
|
120
|
+
for status in statuses:
|
|
121
|
+
if status.state == HookState.FOREIGN:
|
|
122
|
+
streams.stderr.write(
|
|
123
|
+
f"memhub: {status.path} belongs to another tool and was left alone; "
|
|
124
|
+
f"add `{hooks.command_line(status.name)}` to it to enable memhub\n"
|
|
125
|
+
)
|
|
126
|
+
else:
|
|
127
|
+
streams.stdout.write(f"Installed {status.name} hook\n")
|