agent-mem-vault 1.0.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.
- agent_mem_vault/__init__.py +0 -0
- agent_mem_vault/cli.py +116 -0
- agent_mem_vault/companion.py +39 -0
- agent_mem_vault/config.py +97 -0
- agent_mem_vault/doctor.py +105 -0
- agent_mem_vault/format.py +51 -0
- agent_mem_vault/generated.py +66 -0
- agent_mem_vault/git.py +75 -0
- agent_mem_vault/hooks.py +113 -0
- agent_mem_vault/links.py +148 -0
- agent_mem_vault/records.py +261 -0
- agent_mem_vault/runtime.py +19 -0
- agent_mem_vault/sanitize.py +130 -0
- agent_mem_vault/search.py +39 -0
- agent_mem_vault/server.py +304 -0
- agent_mem_vault/store.py +623 -0
- agent_mem_vault/vault.py +224 -0
- agent_mem_vault-1.0.0.dist-info/METADATA +287 -0
- agent_mem_vault-1.0.0.dist-info/RECORD +22 -0
- agent_mem_vault-1.0.0.dist-info/WHEEL +4 -0
- agent_mem_vault-1.0.0.dist-info/entry_points.txt +2 -0
- agent_mem_vault-1.0.0.dist-info/licenses/LICENSE +21 -0
|
File without changes
|
agent_mem_vault/cli.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from agent_mem_vault.config import Config, ConfigError, load_config
|
|
6
|
+
from agent_mem_vault.doctor import run_doctor
|
|
7
|
+
from agent_mem_vault.format import format_records
|
|
8
|
+
from agent_mem_vault.hooks import CLIENTS, run_hook
|
|
9
|
+
from agent_mem_vault.runtime import open_store
|
|
10
|
+
from agent_mem_vault.vault import VaultError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
14
|
+
parser = argparse.ArgumentParser(
|
|
15
|
+
prog="agent-mem-vault",
|
|
16
|
+
description=(
|
|
17
|
+
"MCP server giving coding agents durable shared memory stored in an Obsidian vault. "
|
|
18
|
+
"Without a subcommand it runs the MCP server over stdio."
|
|
19
|
+
),
|
|
20
|
+
)
|
|
21
|
+
parser.add_argument("--version", action="version", version=version("agent-mem-vault"))
|
|
22
|
+
commands = parser.add_subparsers(dest="command")
|
|
23
|
+
|
|
24
|
+
commands.add_parser("doctor", help="check configuration, vault and record counts")
|
|
25
|
+
|
|
26
|
+
listing = commands.add_parser("list", help="list recent records")
|
|
27
|
+
_add_filters(listing)
|
|
28
|
+
listing.add_argument("--type", choices=["context", "handoff"])
|
|
29
|
+
listing.add_argument("--kind")
|
|
30
|
+
listing.add_argument("--tag", action="append", dest="tags")
|
|
31
|
+
listing.add_argument("--include-private", action="store_true")
|
|
32
|
+
|
|
33
|
+
search = commands.add_parser("search", help="search records by text")
|
|
34
|
+
search.add_argument("query")
|
|
35
|
+
_add_filters(search)
|
|
36
|
+
search.add_argument("--type", choices=["context", "handoff"])
|
|
37
|
+
search.add_argument("--kind")
|
|
38
|
+
search.add_argument("--tag", action="append", dest="tags")
|
|
39
|
+
search.add_argument("--include-private", action="store_true")
|
|
40
|
+
|
|
41
|
+
handoffs = commands.add_parser("handoffs", help="list handoffs")
|
|
42
|
+
_add_filters(handoffs)
|
|
43
|
+
handoffs.add_argument("--status", choices=["all", "pending", "read"], default="all")
|
|
44
|
+
|
|
45
|
+
hook = commands.add_parser("hook", help="client hook entry points; they need features.hooks")
|
|
46
|
+
events = hook.add_subparsers(dest="action", required=True)
|
|
47
|
+
for action, text in (
|
|
48
|
+
("session-start", "print the project brief for a SessionStart hook"),
|
|
49
|
+
("stop", "print a nudge to record decisions for a Stop hook"),
|
|
50
|
+
("print-config", "print the client settings snippet that installs both hooks"),
|
|
51
|
+
):
|
|
52
|
+
events.add_parser(action, help=text).add_argument("--client", choices=CLIENTS, required=True)
|
|
53
|
+
return parser
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _add_filters(parser: argparse.ArgumentParser) -> None:
|
|
57
|
+
parser.add_argument("--namespace")
|
|
58
|
+
parser.add_argument("--agent")
|
|
59
|
+
parser.add_argument("--limit", type=float)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run_server(config: Config) -> int:
|
|
63
|
+
from agent_mem_vault.server import create_server
|
|
64
|
+
|
|
65
|
+
store = open_store(config)
|
|
66
|
+
store.vault.clean_tmp_leftovers()
|
|
67
|
+
create_server(store).run()
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _print_records(records: list, empty: str, mark_rejected: bool = False) -> int:
|
|
72
|
+
print(format_records(records, mark_rejected) if records else empty)
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _dispatch(args: argparse.Namespace, config: Config) -> int:
|
|
77
|
+
if args.command is None:
|
|
78
|
+
return _run_server(config)
|
|
79
|
+
if args.command == "doctor":
|
|
80
|
+
return run_doctor(config)
|
|
81
|
+
store = open_store(config)
|
|
82
|
+
if args.command == "list":
|
|
83
|
+
records = store.list_contexts(
|
|
84
|
+
args.namespace, args.agent, args.tags, args.type, args.kind, args.limit, args.include_private
|
|
85
|
+
)
|
|
86
|
+
return _print_records(records, "No saved context yet.", store.visibility_filter)
|
|
87
|
+
if args.command == "search":
|
|
88
|
+
records = store.search_memory(
|
|
89
|
+
args.namespace,
|
|
90
|
+
args.query,
|
|
91
|
+
args.agent,
|
|
92
|
+
args.tags,
|
|
93
|
+
args.type,
|
|
94
|
+
args.kind,
|
|
95
|
+
limit=args.limit,
|
|
96
|
+
include_private=args.include_private,
|
|
97
|
+
)
|
|
98
|
+
return _print_records(records, "No matching memory found.", store.visibility_filter)
|
|
99
|
+
return _print_records(
|
|
100
|
+
store.list_handoffs(args.namespace, args.agent, args.status, args.limit), "No handoffs found."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def main(argv: list[str] | None = None) -> int:
|
|
105
|
+
args = build_parser().parse_args(argv)
|
|
106
|
+
if args.command == "hook":
|
|
107
|
+
return run_hook(args.action, args.client)
|
|
108
|
+
try:
|
|
109
|
+
return _dispatch(args, load_config())
|
|
110
|
+
except (ConfigError, VaultError, ValueError, TypeError) as error:
|
|
111
|
+
print(f"agent-mem-vault: {error}", file=sys.stderr)
|
|
112
|
+
return 2
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def run() -> None:
|
|
116
|
+
sys.exit(main())
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
from agent_mem_vault.records import namespace_slug, read_note, render_record
|
|
4
|
+
from agent_mem_vault.vault import Vault
|
|
5
|
+
|
|
6
|
+
COMPANION_DIR = "_companion"
|
|
7
|
+
CARD_FILES = {"last_session": "last-session.md", "threads": "threads.md"}
|
|
8
|
+
OWNER_MARKER = ("kind", "companion")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Companion:
|
|
13
|
+
last_session: str | None
|
|
14
|
+
threads: str | None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def card_relpath(namespace: str, card: str) -> str:
|
|
18
|
+
return f"{namespace_slug(namespace)}/{COMPANION_DIR}/{CARD_FILES[card]}"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render_card(namespace: str, text: str, updated: str) -> str:
|
|
22
|
+
meta = {"kind": "companion", "namespace": namespace, "updated": updated, "agent-written": True}
|
|
23
|
+
return render_record(meta, text + "\n")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_card(vault: Vault, namespace: str, card: str) -> str | None:
|
|
27
|
+
path = vault.root / card_relpath(namespace, card)
|
|
28
|
+
if not path.is_file():
|
|
29
|
+
return None
|
|
30
|
+
return read_note(path.read_text(encoding="utf-8"))[1].strip() or None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def format_companion(companion: Companion) -> str:
|
|
34
|
+
sections = [
|
|
35
|
+
f"## {heading}\n{text}"
|
|
36
|
+
for heading, text in (("Last session", companion.last_session), ("Threads", companion.threads))
|
|
37
|
+
if text
|
|
38
|
+
]
|
|
39
|
+
return "\n\n".join(sections) if sections else "No companion cards yet."
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from collections.abc import Mapping
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
ENV_VAULT = "AGENT_MEM_VAULT_VAULT"
|
|
9
|
+
ENV_CONFIG = "AGENT_MEM_VAULT_CONFIG"
|
|
10
|
+
ENV_NAMESPACE = "AGENT_MEM_VAULT_DEFAULT_NAMESPACE"
|
|
11
|
+
ENV_REDACT = "AGENT_MEM_VAULT_REDACT_SECRETS"
|
|
12
|
+
DEFAULT_CONFIG_FILE = Path("~/.config/agent-mem-vault/config.yaml")
|
|
13
|
+
DEFAULT_COMPANION_MAX_CHARS = 3000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigError(Exception):
|
|
17
|
+
"""The configuration is missing or invalid; the message tells the user what to fix."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Config:
|
|
22
|
+
vault: Path
|
|
23
|
+
default_namespace: str = "default"
|
|
24
|
+
redact_secrets: bool = True
|
|
25
|
+
receipts: bool = False
|
|
26
|
+
companion: bool = False
|
|
27
|
+
visibility: bool = True
|
|
28
|
+
hooks: bool = False
|
|
29
|
+
git_autocommit: bool = False
|
|
30
|
+
companion_max_chars: int = DEFAULT_COMPANION_MAX_CHARS
|
|
31
|
+
config_file: Path | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _read_config_file(env: Mapping[str, str]) -> tuple[dict, Path | None]:
|
|
35
|
+
explicit = env.get(ENV_CONFIG)
|
|
36
|
+
path = Path(explicit).expanduser() if explicit else DEFAULT_CONFIG_FILE.expanduser()
|
|
37
|
+
if not path.is_file():
|
|
38
|
+
if explicit:
|
|
39
|
+
raise ConfigError(f"config file not found: {path}")
|
|
40
|
+
return {}, None
|
|
41
|
+
try:
|
|
42
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
43
|
+
except (OSError, yaml.YAMLError) as error:
|
|
44
|
+
raise ConfigError(f"cannot read config file {path}: {error}") from error
|
|
45
|
+
if not isinstance(data, dict):
|
|
46
|
+
raise ConfigError(f"config file {path} must contain a mapping")
|
|
47
|
+
return data, path
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _parse_bool(value: object, source: str) -> bool:
|
|
51
|
+
if isinstance(value, bool):
|
|
52
|
+
return value
|
|
53
|
+
if isinstance(value, str) and value.strip().lower() in ("true", "false"):
|
|
54
|
+
return value.strip().lower() == "true"
|
|
55
|
+
raise ConfigError(f"{source} must be true or false")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _mapping(data: dict, key: str) -> dict:
|
|
59
|
+
section = data.get(key) or {}
|
|
60
|
+
if not isinstance(section, dict):
|
|
61
|
+
raise ConfigError(f"{key} must be a mapping")
|
|
62
|
+
return section
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _parse_max_chars(value: object) -> int:
|
|
66
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
67
|
+
raise ConfigError("companion.max_chars must be a positive integer")
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_config(env: Mapping[str, str] | None = None) -> Config:
|
|
72
|
+
"""Built-in defaults, then the config file, then environment variables."""
|
|
73
|
+
env = os.environ if env is None else env
|
|
74
|
+
data, config_file = _read_config_file(env)
|
|
75
|
+
|
|
76
|
+
vault = env.get(ENV_VAULT) or data.get("vault")
|
|
77
|
+
if not vault:
|
|
78
|
+
raise ConfigError(f"vault is not configured: set {ENV_VAULT} or `vault` in the config file")
|
|
79
|
+
namespace = env.get(ENV_NAMESPACE) or data.get("default_namespace", "default")
|
|
80
|
+
redact = env[ENV_REDACT] if ENV_REDACT in env else data.get("redact_secrets", True)
|
|
81
|
+
|
|
82
|
+
if not isinstance(vault, str) or not isinstance(namespace, str):
|
|
83
|
+
raise ConfigError("vault and default_namespace must be strings")
|
|
84
|
+
features = _mapping(data, "features")
|
|
85
|
+
companion = _mapping(data, "companion")
|
|
86
|
+
return Config(
|
|
87
|
+
vault=Path(vault).expanduser(),
|
|
88
|
+
default_namespace=namespace,
|
|
89
|
+
redact_secrets=_parse_bool(redact, ENV_REDACT if ENV_REDACT in env else "redact_secrets"),
|
|
90
|
+
receipts=_parse_bool(features.get("receipts", False), "features.receipts"),
|
|
91
|
+
companion=_parse_bool(features.get("companion", False), "features.companion"),
|
|
92
|
+
visibility=_parse_bool(features.get("visibility", True), "features.visibility"),
|
|
93
|
+
hooks=_parse_bool(features.get("hooks", False), "features.hooks"),
|
|
94
|
+
git_autocommit=_parse_bool(features.get("git_autocommit", False), "features.git_autocommit"),
|
|
95
|
+
companion_max_chars=_parse_max_chars(companion.get("max_chars", DEFAULT_COMPANION_MAX_CHARS)),
|
|
96
|
+
config_file=config_file,
|
|
97
|
+
)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import subprocess
|
|
3
|
+
from collections import Counter
|
|
4
|
+
|
|
5
|
+
from agent_mem_vault import git
|
|
6
|
+
from agent_mem_vault.config import Config
|
|
7
|
+
from agent_mem_vault.links import normalized_target, unresolved_targets
|
|
8
|
+
from agent_mem_vault.runtime import open_vault
|
|
9
|
+
from agent_mem_vault.vault import Vault
|
|
10
|
+
|
|
11
|
+
OBSIDIAN_TIMEOUT_SECONDS = 30
|
|
12
|
+
NOT_RUNNING = "Obsidian not running: parity check skipped"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run_doctor(config: Config) -> int:
|
|
16
|
+
vault = open_vault(config)
|
|
17
|
+
scan = vault.scan()
|
|
18
|
+
counts = Counter(record.kind for record in scan.records)
|
|
19
|
+
leftovers = vault.tmp_leftovers()
|
|
20
|
+
unresolved = unresolved_targets(vault, scan.records)
|
|
21
|
+
print(f"config file: {config.config_file or 'none (defaults and environment)'}")
|
|
22
|
+
print(f"vault: {vault.root}")
|
|
23
|
+
print(f".obsidian: {'present' if (vault.root / '.obsidian').is_dir() else 'missing'}")
|
|
24
|
+
print(f"default namespace: {config.default_namespace}")
|
|
25
|
+
print(f"redact secrets: {str(config.redact_secrets).lower()}")
|
|
26
|
+
print(f"git autocommit: {str(config.git_autocommit).lower()}")
|
|
27
|
+
flags = (("receipts", config.receipts), ("companion", config.companion))
|
|
28
|
+
flags += (("visibility", config.visibility), ("hooks", config.hooks))
|
|
29
|
+
print("features: " + ", ".join(f"{name} {'on' if enabled else 'off'}" for name, enabled in flags))
|
|
30
|
+
breakdown = ", ".join(f"{kind} {count}" for kind, count in sorted(counts.items()))
|
|
31
|
+
print(f"records: {len(scan.records)}" + (f" ({breakdown})" if breakdown else ""))
|
|
32
|
+
print(f"issues: {len(scan.issues)}")
|
|
33
|
+
for issue in scan.issues:
|
|
34
|
+
print(f" {issue.path}: {issue.reason}")
|
|
35
|
+
print(f"tmp leftovers: {len(leftovers)}")
|
|
36
|
+
for path in leftovers:
|
|
37
|
+
print(f" {path.name}")
|
|
38
|
+
print(f"unresolved links in records: {sum(len(targets) for targets in unresolved.values())}")
|
|
39
|
+
print(_git_line(vault))
|
|
40
|
+
for line in _obsidian_parity(vault, unresolved):
|
|
41
|
+
print(line)
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _git_line(vault: Vault) -> str:
|
|
46
|
+
status = git.status(vault.root)
|
|
47
|
+
if status is None:
|
|
48
|
+
return "git: not a git work tree"
|
|
49
|
+
changes = f"dirty ({status.changed} changed)" if status.changed else "clean"
|
|
50
|
+
distance = (
|
|
51
|
+
f"ahead {status.ahead}, behind {status.behind} of {status.upstream}" if status.upstream else "no upstream"
|
|
52
|
+
)
|
|
53
|
+
return f"git: branch {status.branch}, {changes}, {distance}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _obsidian_running() -> bool:
|
|
57
|
+
try:
|
|
58
|
+
return subprocess.run(["pgrep", "-x", "Obsidian"], capture_output=True, check=False).returncode == 0
|
|
59
|
+
except OSError:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _reported_unresolved(output: str) -> set[tuple[str, str]]:
|
|
64
|
+
"""Pairs of (source file, link) from `obsidian unresolved verbose format=json`."""
|
|
65
|
+
pairs: set[tuple[str, str]] = set()
|
|
66
|
+
for entry in json.loads(output):
|
|
67
|
+
link = entry.get("link") or entry.get("name") or entry.get("target")
|
|
68
|
+
sources = entry.get("files") or entry.get("sources") or entry.get("source") or entry.get("file")
|
|
69
|
+
if not link or not sources:
|
|
70
|
+
raise ValueError("entry without a link and its source files")
|
|
71
|
+
for source in [sources] if isinstance(sources, str) else sources:
|
|
72
|
+
pairs.add((source, normalized_target(link)))
|
|
73
|
+
return pairs
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _obsidian_parity(vault: Vault, ours: dict[str, set[str]]) -> list[str]:
|
|
77
|
+
if not _obsidian_running():
|
|
78
|
+
return [NOT_RUNNING]
|
|
79
|
+
try:
|
|
80
|
+
result = subprocess.run(
|
|
81
|
+
["obsidian", "unresolved", "verbose", "format=json"],
|
|
82
|
+
cwd=vault.root,
|
|
83
|
+
capture_output=True,
|
|
84
|
+
text=True,
|
|
85
|
+
timeout=OBSIDIAN_TIMEOUT_SECONDS,
|
|
86
|
+
check=False,
|
|
87
|
+
)
|
|
88
|
+
except FileNotFoundError:
|
|
89
|
+
return ["obsidian CLI not found: parity check skipped"]
|
|
90
|
+
except (OSError, subprocess.TimeoutExpired) as error:
|
|
91
|
+
return [f"obsidian CLI failed: parity check skipped ({error})"]
|
|
92
|
+
if result.returncode != 0:
|
|
93
|
+
return [f"obsidian CLI failed: parity check skipped ({result.stderr.strip() or result.returncode})"]
|
|
94
|
+
try:
|
|
95
|
+
reported = {pair for pair in _reported_unresolved(result.stdout) if pair[0] in ours}
|
|
96
|
+
except (ValueError, AttributeError, TypeError):
|
|
97
|
+
return ["obsidian CLI output not understood: parity check skipped"]
|
|
98
|
+
mine = {(path, target) for path, targets in ours.items() for target in targets}
|
|
99
|
+
if mine == reported:
|
|
100
|
+
return [f"obsidian parity: ok ({len(mine)} unresolved links match)"]
|
|
101
|
+
return [
|
|
102
|
+
"obsidian parity: differences",
|
|
103
|
+
*(f" only avm: {path} -> {target}" for path, target in sorted(mine - reported)),
|
|
104
|
+
*(f" only obsidian: {path} -> {target}" for path, target in sorted(reported - mine)),
|
|
105
|
+
]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from datetime import UTC, datetime
|
|
2
|
+
|
|
3
|
+
from agent_mem_vault.links import Links
|
|
4
|
+
from agent_mem_vault.records import Record
|
|
5
|
+
from agent_mem_vault.store import Brief
|
|
6
|
+
from agent_mem_vault.vault import Issue
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def format_timestamp(timestamp: str) -> str:
|
|
10
|
+
"""Render an ISO timestamp in the en-US style, in UTC."""
|
|
11
|
+
try:
|
|
12
|
+
moment = datetime.fromisoformat(timestamp).astimezone(UTC)
|
|
13
|
+
except ValueError:
|
|
14
|
+
return timestamp
|
|
15
|
+
hour = moment.hour % 12 or 12
|
|
16
|
+
meridiem = "AM" if moment.hour < 12 else "PM"
|
|
17
|
+
return f"{moment.month}/{moment.day}/{moment.year}, {hour}:{moment.minute:02d}:{moment.second:02d} {meridiem}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def format_record(record: Record, index: int, mark_rejected: bool = False) -> str:
|
|
21
|
+
destination = f" -> {record.to}" if record.to else ""
|
|
22
|
+
pending = " [PENDING]" if record.pending else ""
|
|
23
|
+
rejected = " [rejected]" if mark_rejected and record.meta.get("validity") == "rejected" else ""
|
|
24
|
+
return (
|
|
25
|
+
f"{index + 1}. [{record.type}/{record.kind}{destination}{pending}{rejected}] ({record.namespace}) "
|
|
26
|
+
f"{record.title} - {record.agent} - {format_timestamp(record.created)}"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_records(records: list[Record], mark_rejected: bool = False) -> str:
|
|
31
|
+
return "\n".join(format_record(record, index, mark_rejected) for index, record in enumerate(records))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def format_brief(brief: Brief) -> str:
|
|
35
|
+
return f"**{brief.title}** - {brief.namespace} - {format_timestamp(brief.created)}\n\n{brief.content}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def format_links(record: Record, links: Links) -> str:
|
|
39
|
+
sections = [f"**{record.title}** - {record.namespace}"]
|
|
40
|
+
for heading, items in (
|
|
41
|
+
("Outgoing links", links.outgoing),
|
|
42
|
+
("Unresolved links", links.unresolved),
|
|
43
|
+
("Backlinks", links.backlinks),
|
|
44
|
+
):
|
|
45
|
+
sections.append(f"{heading} ({len(items)}):" + "".join(f"\n- {item}" for item in items))
|
|
46
|
+
return "\n\n".join(sections)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def format_issues(issues: list[Issue]) -> str:
|
|
50
|
+
noun = "issue" if len(issues) == 1 else "issues"
|
|
51
|
+
return f"{len(issues)} {noun}:" + "".join(f"\n- {issue.path}: {issue.reason}" for issue in issues)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from agent_mem_vault.records import KINDS, RECEIPT_KIND, Record, namespace_slug, render_record, wikilink
|
|
2
|
+
|
|
3
|
+
HUB_BANNER = "> Generated by agent-mem-vault. Do not edit: changes are overwritten on the next write."
|
|
4
|
+
DASHBOARD_RELPATH = "_dashboards/memory.base"
|
|
5
|
+
|
|
6
|
+
DASHBOARD = """\
|
|
7
|
+
filters:
|
|
8
|
+
and:
|
|
9
|
+
- 'note["agent-written"] == true'
|
|
10
|
+
views:
|
|
11
|
+
- type: table
|
|
12
|
+
name: "Pending handoffs"
|
|
13
|
+
filters:
|
|
14
|
+
and:
|
|
15
|
+
- 'note.kind == "handoff"'
|
|
16
|
+
- 'note.read == false'
|
|
17
|
+
order:
|
|
18
|
+
- file.name
|
|
19
|
+
- note.to
|
|
20
|
+
- note.namespace
|
|
21
|
+
- note.created
|
|
22
|
+
- type: table
|
|
23
|
+
name: "Decisions and risks"
|
|
24
|
+
filters:
|
|
25
|
+
and:
|
|
26
|
+
- or:
|
|
27
|
+
- 'note.kind == "decision"'
|
|
28
|
+
- 'note.kind == "risk"'
|
|
29
|
+
- 'note.validity == "valid"'
|
|
30
|
+
groupBy:
|
|
31
|
+
property: note.namespace
|
|
32
|
+
direction: ASC
|
|
33
|
+
order:
|
|
34
|
+
- file.name
|
|
35
|
+
- note.kind
|
|
36
|
+
- note.status
|
|
37
|
+
- note.created
|
|
38
|
+
- type: table
|
|
39
|
+
name: "All records"
|
|
40
|
+
filters:
|
|
41
|
+
and:
|
|
42
|
+
- 'note.generated != true'
|
|
43
|
+
order:
|
|
44
|
+
- note.title
|
|
45
|
+
- note.kind
|
|
46
|
+
- note.namespace
|
|
47
|
+
- note.created
|
|
48
|
+
- note.status
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def hub_relpath(namespace: str) -> str:
|
|
53
|
+
slug = namespace_slug(namespace)
|
|
54
|
+
return f"{slug}/{slug}.md"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def render_hub(namespace: str, records: list[Record]) -> str:
|
|
58
|
+
"""Deterministic hub note: records grouped by kind, newest first, so an unchanged namespace renders identically."""
|
|
59
|
+
meta = {"title": f"Memory index: {namespace}", "namespace": namespace, "generated": True, "agent-written": True}
|
|
60
|
+
lines = [HUB_BANNER, "", f"# {namespace}"]
|
|
61
|
+
for kind in (*KINDS, RECEIPT_KIND):
|
|
62
|
+
group = sorted((record for record in records if record.kind == kind), key=lambda r: r.sort_key, reverse=True)
|
|
63
|
+
if group:
|
|
64
|
+
lines += ["", f"## {kind}", ""]
|
|
65
|
+
lines += [f"- {wikilink(record.path, record.title)} ({record.created[:10]})" for record in group]
|
|
66
|
+
return render_record(meta, "\n".join(lines) + "\n")
|
agent_mem_vault/git.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from agent_mem_vault.vault import log
|
|
7
|
+
|
|
8
|
+
GIT_TIMEOUT_SECONDS = 30
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GitError(Exception):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class GitStatus:
|
|
17
|
+
branch: str
|
|
18
|
+
changed: int
|
|
19
|
+
upstream: str | None
|
|
20
|
+
ahead: int
|
|
21
|
+
behind: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run_git(cwd: Path, *args: str) -> str:
|
|
25
|
+
try:
|
|
26
|
+
result = subprocess.run(
|
|
27
|
+
["git", *args],
|
|
28
|
+
cwd=cwd,
|
|
29
|
+
capture_output=True,
|
|
30
|
+
text=True,
|
|
31
|
+
timeout=GIT_TIMEOUT_SECONDS,
|
|
32
|
+
check=False,
|
|
33
|
+
env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"},
|
|
34
|
+
)
|
|
35
|
+
except (OSError, subprocess.TimeoutExpired) as error:
|
|
36
|
+
raise GitError(f"git {args[0]} failed: {error}") from error
|
|
37
|
+
if result.returncode != 0:
|
|
38
|
+
raise GitError(f"git {args[0]} failed: {(result.stderr or result.stdout).strip()}")
|
|
39
|
+
return result.stdout.rstrip("\n")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def inside_work_tree(root: Path) -> bool:
|
|
43
|
+
try:
|
|
44
|
+
return run_git(root, "rev-parse", "--is-inside-work-tree") == "true"
|
|
45
|
+
except GitError:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def autocommit(root: Path, relpaths: list[str], message: str) -> None:
|
|
50
|
+
"""Commit exactly these paths with the user's own git identity. Never pushes; failures are only logged."""
|
|
51
|
+
try:
|
|
52
|
+
if not inside_work_tree(root):
|
|
53
|
+
return
|
|
54
|
+
run_git(root, "add", "--", *relpaths)
|
|
55
|
+
run_git(root, "commit", "-m", message, "--", *relpaths)
|
|
56
|
+
except GitError as error:
|
|
57
|
+
log(f"git autocommit skipped: {error}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def status(root: Path) -> GitStatus | None:
|
|
61
|
+
"""Branch, uncommitted changes under the vault and distance from the upstream; None outside a work tree."""
|
|
62
|
+
if not inside_work_tree(root):
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
branch = run_git(root, "branch", "--show-current") or "detached HEAD"
|
|
66
|
+
changed = len(run_git(root, "status", "--porcelain", "--", ".").splitlines())
|
|
67
|
+
except GitError:
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
upstream = run_git(root, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
|
|
71
|
+
distance = run_git(root, "rev-list", "--left-right", "--count", "HEAD...@{upstream}")
|
|
72
|
+
ahead, behind = (int(count) for count in distance.split())
|
|
73
|
+
except GitError:
|
|
74
|
+
return GitStatus(branch, changed, None, 0, 0)
|
|
75
|
+
return GitStatus(branch, changed, upstream, ahead, behind)
|
agent_mem_vault/hooks.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from agent_mem_vault import git
|
|
7
|
+
from agent_mem_vault.config import load_config
|
|
8
|
+
from agent_mem_vault.format import format_brief
|
|
9
|
+
from agent_mem_vault.records import namespace_slug
|
|
10
|
+
from agent_mem_vault.runtime import open_store
|
|
11
|
+
from agent_mem_vault.vault import Vault, log
|
|
12
|
+
|
|
13
|
+
CLIENTS = ("claude", "codex")
|
|
14
|
+
SESSION_START_LIMIT = 9000
|
|
15
|
+
TRUNCATION_NOTE = "\n[brief truncated]"
|
|
16
|
+
HOOK_TIMEOUT_SECONDS = 5
|
|
17
|
+
STOP_NUDGE = (
|
|
18
|
+
"[agent-mem-vault] Work state changed since the last check. Before finishing, record durable decisions, "
|
|
19
|
+
"risks and next steps with the agent-mem-vault tools (save_memory with kind decision or risk, "
|
|
20
|
+
"create_handoff for a hand-over). If there is nothing durable to record, say so in one line and stop."
|
|
21
|
+
)
|
|
22
|
+
CLIENT_SETTINGS_FILE = {"claude": "~/.claude/settings.json", "codex": "the hooks.json of your Codex setup"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_hook(action: str, client: str) -> int:
|
|
26
|
+
"""Run one hook entry point. It always exits 0: a failing hook must never break the client session."""
|
|
27
|
+
try:
|
|
28
|
+
output = print_config(client) if action == "print-config" else _run_event(action, client)
|
|
29
|
+
except Exception as error:
|
|
30
|
+
log(f"hook {action} skipped: {error}")
|
|
31
|
+
return 0
|
|
32
|
+
if output:
|
|
33
|
+
print(output)
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def namespace_for(cwd: Path) -> str:
|
|
38
|
+
try:
|
|
39
|
+
root = Path(git.run_git(cwd, "rev-parse", "--show-toplevel"))
|
|
40
|
+
except git.GitError:
|
|
41
|
+
root = cwd
|
|
42
|
+
return f"project/{root.name}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def print_config(client: str) -> str:
|
|
46
|
+
"""The settings snippet for a client. The CLI never edits client settings itself."""
|
|
47
|
+
command = f"agent-mem-vault hook %s --client {client}"
|
|
48
|
+
snippet = {
|
|
49
|
+
"hooks": {
|
|
50
|
+
event: [{"hooks": [{"type": "command", "command": command % action, "timeout": HOOK_TIMEOUT_SECONDS}]}]
|
|
51
|
+
for event, action in (("SessionStart", "session-start"), ("Stop", "stop"))
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
print(
|
|
55
|
+
f"Merge this into {CLIENT_SETTINGS_FILE[client]} and set features.hooks: true in the config.", file=sys.stderr
|
|
56
|
+
)
|
|
57
|
+
return json.dumps(snippet, indent=2)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _run_event(action: str, client: str) -> str:
|
|
61
|
+
config = load_config()
|
|
62
|
+
if not config.hooks:
|
|
63
|
+
return ""
|
|
64
|
+
payload = _read_payload()
|
|
65
|
+
cwd = Path(payload["cwd"]) if isinstance(payload.get("cwd"), str) and payload["cwd"] else Path.cwd()
|
|
66
|
+
namespace = namespace_for(cwd)
|
|
67
|
+
store = open_store(config)
|
|
68
|
+
if action == "session-start":
|
|
69
|
+
return _session_start(client, _capped(format_brief(store.get_project_brief(namespace))))
|
|
70
|
+
if payload.get("stop_hook_active") is True or not _git_state_changed(store.vault, cwd, namespace):
|
|
71
|
+
return ""
|
|
72
|
+
return json.dumps({"decision": "block", "reason": STOP_NUDGE}) if client == "claude" else STOP_NUDGE
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _read_payload() -> dict:
|
|
76
|
+
if sys.stdin is None or sys.stdin.isatty():
|
|
77
|
+
return {}
|
|
78
|
+
try:
|
|
79
|
+
payload = json.loads(sys.stdin.read())
|
|
80
|
+
except ValueError:
|
|
81
|
+
return {}
|
|
82
|
+
return payload if isinstance(payload, dict) else {}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _capped(text: str) -> str:
|
|
86
|
+
if len(text) <= SESSION_START_LIMIT:
|
|
87
|
+
return text
|
|
88
|
+
return text[: SESSION_START_LIMIT - len(TRUNCATION_NOTE)] + TRUNCATION_NOTE
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _session_start(client: str, context: str) -> str:
|
|
92
|
+
if client == "claude":
|
|
93
|
+
return json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}})
|
|
94
|
+
return context
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _git_state_changed(vault: Vault, cwd: Path, namespace: str) -> bool:
|
|
98
|
+
"""True once per change of (HEAD, working tree status); outside a git work tree there is no state to compare."""
|
|
99
|
+
if not git.inside_work_tree(cwd):
|
|
100
|
+
return False
|
|
101
|
+
try:
|
|
102
|
+
head = git.run_git(cwd, "rev-parse", "HEAD")
|
|
103
|
+
except git.GitError:
|
|
104
|
+
head = "no-commits"
|
|
105
|
+
status = "\n".join(sorted(git.run_git(cwd, "status", "--porcelain").splitlines()))
|
|
106
|
+
signature = f"{head}:{hashlib.sha1(status.encode()).hexdigest()}"
|
|
107
|
+
marker = vault.state_dir / "state" / f"stop-{namespace_slug(namespace)}"
|
|
108
|
+
if marker.is_file() and marker.read_text(encoding="utf-8") == signature:
|
|
109
|
+
return False
|
|
110
|
+
vault.ensure_state()
|
|
111
|
+
marker.parent.mkdir(exist_ok=True)
|
|
112
|
+
marker.write_text(signature, encoding="utf-8")
|
|
113
|
+
return True
|