agent-context-bridge 0.2.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.
@@ -0,0 +1,50 @@
1
+ """Agent Context Bridge (ACB)
2
+
3
+ Universal, zero-dependency context & memory bridge for multi-agent workflows.
4
+ Enables transparent context handoff between Hermes Agent, Claude Code, OpenCode, and Codex.
5
+ """
6
+
7
+ __version__ = "0.2.0"
8
+ __author__ = "shenn667"
9
+
10
+
11
+ def get_version() -> str:
12
+ """Single source of truth for the package version.
13
+
14
+ Prefers installed dist metadata (correct after ``pip install`` even if
15
+ the source tree was bumped), falls back to ``__version__`` for
16
+ source-tree / editable edge cases. Zero-dependency (stdlib only).
17
+ """
18
+ try:
19
+ from importlib.metadata import version, PackageNotFoundError
20
+
21
+ try:
22
+ return version("agent-context-bridge")
23
+ except PackageNotFoundError:
24
+ pass
25
+ except Exception:
26
+ pass
27
+ return __version__
28
+
29
+ from agent_context_bridge.core import (
30
+ ContextRecord,
31
+ MemoryStore,
32
+ BridgeSnapshot,
33
+ )
34
+ from agent_context_bridge.adapters import (
35
+ HermesAdapter,
36
+ ClaudeCodeAdapter,
37
+ OpenCodeAdapter,
38
+ CodexAdapter,
39
+ )
40
+
41
+ __all__ = [
42
+ "ContextRecord",
43
+ "MemoryStore",
44
+ "BridgeSnapshot",
45
+ "HermesAdapter",
46
+ "ClaudeCodeAdapter",
47
+ "OpenCodeAdapter",
48
+ "CodexAdapter",
49
+ "get_version",
50
+ ]
@@ -0,0 +1,105 @@
1
+ """Agent-specific adapters to consume and inject shared context."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import List, Dict, Any
5
+ from pathlib import Path
6
+
7
+ from agent_context_bridge.core import MemoryStore, ContextRecord, MAX_LIST_LIMIT
8
+
9
+
10
+ #: Cap applied to ``max_entries`` in all adapters (documented hardening rule).
11
+ MAX_ADAPTER_ENTRIES = MAX_LIST_LIMIT
12
+
13
+
14
+ def _normalize_max_entries(max_entries: int) -> int:
15
+ """Normalize ``max_entries`` for prompt injection.
16
+
17
+ Returns 0 when ``max_entries`` is non-positive (callers then render an
18
+ empty string), otherwise the value capped at ``MAX_ADAPTER_ENTRIES``.
19
+ ``None`` falls back to the default of 5.
20
+ """
21
+ if max_entries is None:
22
+ return 5
23
+ if max_entries <= 0:
24
+ return 0
25
+ return min(max_entries, MAX_ADAPTER_ENTRIES)
26
+
27
+
28
+ class BaseAgentAdapter(ABC):
29
+ """Abstract interface for agent context ingestion."""
30
+
31
+ @abstractmethod
32
+ def format_prompt_injection(self, store: MemoryStore, max_entries: int = 5) -> str:
33
+ """Render context snippet suitable for prompt or hook injection."""
34
+ pass
35
+
36
+
37
+ class HermesAdapter(BaseAgentAdapter):
38
+ """Adapter for Nous Research Hermes Agent."""
39
+
40
+ def format_prompt_injection(self, store: MemoryStore, max_entries: int = 5) -> str:
41
+ max_entries = _normalize_max_entries(max_entries)
42
+ if max_entries <= 0:
43
+ return ""
44
+ records = store.list_records(limit=max_entries)
45
+ if not records:
46
+ return ""
47
+ lines = [
48
+ "<!-- HERMES MULTI-AGENT SHARED MEMORY -->",
49
+ "Here is recent context and decisions from peer agents in this repository:",
50
+ ]
51
+ for r in records:
52
+ lines.append(f"- [{r.agent}] **{r.topic}**: {r.summary}")
53
+ lines.append("<!-- END SHARED MEMORY -->")
54
+ return "\n".join(lines)
55
+
56
+
57
+ class ClaudeCodeAdapter(BaseAgentAdapter):
58
+ """Adapter for Anthropic Claude Code SessionStart hooks."""
59
+
60
+ def format_prompt_injection(self, store: MemoryStore, max_entries: int = 5) -> str:
61
+ max_entries = _normalize_max_entries(max_entries)
62
+ if max_entries <= 0:
63
+ return ""
64
+ records = store.list_records(limit=max_entries)
65
+ if not records:
66
+ return ""
67
+ lines = [
68
+ "## Shared Repository Memory (Claude Code Integration)",
69
+ "The following context was captured from peer agents working on this workspace:",
70
+ ]
71
+ for r in records:
72
+ lines.append(f"* **{r.agent}** ({r.topic}): {r.summary}")
73
+ return "\n".join(lines)
74
+
75
+
76
+ class OpenCodeAdapter(BaseAgentAdapter):
77
+ """Adapter for OpenCode System Prompt Transformer."""
78
+
79
+ def format_prompt_injection(self, store: MemoryStore, max_entries: int = 5) -> str:
80
+ max_entries = _normalize_max_entries(max_entries)
81
+ if max_entries <= 0:
82
+ return ""
83
+ records = store.list_records(limit=max_entries)
84
+ if not records:
85
+ return ""
86
+ lines = ["[OpenCode Shared Context]"]
87
+ for r in records:
88
+ lines.append(f"• {r.agent}: {r.summary}")
89
+ return "\n".join(lines)
90
+
91
+
92
+ class CodexAdapter(BaseAgentAdapter):
93
+ """Adapter for Codex CLI environments."""
94
+
95
+ def format_prompt_injection(self, store: MemoryStore, max_entries: int = 5) -> str:
96
+ max_entries = _normalize_max_entries(max_entries)
97
+ if max_entries <= 0:
98
+ return ""
99
+ records = store.list_records(limit=max_entries)
100
+ if not records:
101
+ return ""
102
+ lines = ["# Codex Multi-Agent Shared State"]
103
+ for r in records:
104
+ lines.append(f"- [{r.agent}] {r.topic}: {r.summary}")
105
+ return "\n".join(lines)
@@ -0,0 +1,229 @@
1
+ """Command-line interface for agent-context-bridge."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from agent_context_bridge.core import MemoryStore, ContextRecord, MAX_LIST_LIMIT
9
+ from agent_context_bridge import get_version
10
+ from agent_context_bridge.hooks import (
11
+ HOOK_TARGETS,
12
+ DEFAULT_MAX_ENTRIES,
13
+ hook_command,
14
+ render_claude_settings_snippet,
15
+ hermes_wiring_snippet,
16
+ install_claude_hook,
17
+ run_hook_injection,
18
+ )
19
+ from agent_context_bridge.adapters import (
20
+ HermesAdapter,
21
+ ClaudeCodeAdapter,
22
+ OpenCodeAdapter,
23
+ CodexAdapter,
24
+ )
25
+
26
+
27
+ def _require_valid_limit(parser: argparse.ArgumentParser, limit) -> int:
28
+ """Validate --limit/-n: reject <= 0 with exit code 2, cap at MAX_LIST_LIMIT."""
29
+ if limit is None:
30
+ return 10
31
+ if limit <= 0:
32
+ parser.error(f"--limit/-n must be a positive integer (got {limit}).")
33
+ return min(limit, MAX_LIST_LIMIT)
34
+
35
+
36
+ def main():
37
+ parent_parser = argparse.ArgumentParser(add_help=False)
38
+ # NOTE: default=SUPPRESS so the subparser-level --dir does not shadow a
39
+ # top-level `--dir <path>` with its own default (classic argparse pitfall).
40
+ parent_parser.add_argument("--dir", default=argparse.SUPPRESS, help="Workspace root directory")
41
+
42
+ parser = argparse.ArgumentParser(
43
+ prog="agent-bridge",
44
+ description="Agent Context Bridge (ACB) — Universal memory & context handoff for coding agents.",
45
+ parents=[parent_parser],
46
+ )
47
+ parser.add_argument(
48
+ "--version",
49
+ action="version",
50
+ version=f"%(prog)s {get_version()}",
51
+ help="Show package version (coherent with git tag vX.Y.Z and pyproject).",
52
+ )
53
+ subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
54
+
55
+ # init
56
+ init_parser = subparsers.add_parser("init", help="Initialize ACB in current workspace", parents=[parent_parser])
57
+
58
+ # record
59
+ record_parser = subparsers.add_parser("record", help="Record a new context item", parents=[parent_parser])
60
+ record_parser.add_argument("--agent", required=True, help="Agent name (e.g. hermes, claude, opencode)")
61
+ record_parser.add_argument("--topic", required=True, help="Short topic/scope of the decision")
62
+ record_parser.add_argument("--summary", required=True, help="1-sentence executive summary")
63
+ record_parser.add_argument("--details", help="Optional detailed markdown explanation")
64
+ record_parser.add_argument("--tag", action="append", default=[], help="Categorization tag (repeatable)")
65
+
66
+ # list
67
+ list_parser = subparsers.add_parser("list", help="List recent shared context items", parents=[parent_parser])
68
+ list_parser.add_argument("-n", "--limit", type=int, default=10, help="Maximum items to show")
69
+
70
+ # inject
71
+ inject_parser = subparsers.add_parser("inject", help="Output formatted context for specific agent", parents=[parent_parser])
72
+ inject_parser.add_argument(
73
+ "--target",
74
+ choices=["hermes", "claude", "opencode", "codex"],
75
+ default="hermes",
76
+ help="Target agent prompt format",
77
+ )
78
+ inject_parser.add_argument("-n", "--limit", type=int, default=5, help="Maximum items to inject")
79
+
80
+ # export
81
+ export_parser = subparsers.add_parser("export", help="Export full snapshot to JSON", parents=[parent_parser])
82
+
83
+ # hooks
84
+ hooks_parser = subparsers.add_parser(
85
+ "hooks", help="Native agent hooks (Claude SessionStart, Hermes inject)", parents=[parent_parser]
86
+ )
87
+ hooks_sub = hooks_parser.add_subparsers(dest="hooks_action", help="Hook operations")
88
+
89
+ hooks_claude = hooks_sub.add_parser("claude", help="Claude Code SessionStart hook", parents=[parent_parser])
90
+ hooks_claude.add_argument("--print", dest="print_snippet", action="store_true",
91
+ help="Print .claude/settings.json snippet (default)")
92
+ hooks_claude.add_argument("--install", action="store_true",
93
+ help="Write/merge hook into <workspace>/.claude/settings.json")
94
+ hooks_claude.add_argument("-n", "--max-entries", type=int, default=DEFAULT_MAX_ENTRIES,
95
+ help="Maximum context entries injected per session")
96
+
97
+ hooks_hermes = hooks_sub.add_parser("hermes", help="Hermes Agent inject wiring", parents=[parent_parser])
98
+ hooks_hermes.add_argument("--print", dest="print_snippet", action="store_true", default=True,
99
+ help="Print one-command Hermes wiring snippet")
100
+
101
+ hooks_run = hooks_sub.add_parser("run", help="Execute hook injection (reads hook JSON on stdin, prints context on stdout)",
102
+ parents=[parent_parser])
103
+ hooks_run.add_argument("--target", choices=list(HOOK_TARGETS), default="hermes",
104
+ help="Target agent prompt format")
105
+ hooks_run.add_argument("-n", "--max-entries", type=int, default=DEFAULT_MAX_ENTRIES,
106
+ help="Maximum entries to inject")
107
+
108
+ args = parser.parse_args()
109
+
110
+ if not args.command:
111
+ parser.print_help()
112
+ sys.exit(0)
113
+
114
+ workspace = Path(getattr(args, "dir", ".")).resolve()
115
+ store = MemoryStore(workspace)
116
+
117
+ if args.command == "init":
118
+ try:
119
+ p = store.initialize()
120
+ except OSError as exc:
121
+ print(f"error: failed to initialize store at {store.bridge_dir}: {exc}", file=sys.stderr)
122
+ sys.exit(1)
123
+ print(f"✓ Initialized Agent Context Bridge at: {p}")
124
+ print(f"✓ Context document created: {store.summary_md}")
125
+
126
+ elif args.command == "record":
127
+ try:
128
+ record = ContextRecord(
129
+ agent=args.agent,
130
+ topic=args.topic,
131
+ summary=args.summary,
132
+ details=args.details,
133
+ tags=args.tag,
134
+ )
135
+ except ValueError as exc:
136
+ print(f"error: invalid record: {exc}", file=sys.stderr)
137
+ sys.exit(2)
138
+ try:
139
+ store.add_record(record)
140
+ except (OSError, ValueError) as exc:
141
+ print(f"error: failed to record context: {exc}", file=sys.stderr)
142
+ sys.exit(1)
143
+ print(f"✓ Recorded [{record.agent}] {record.topic} ({record.estimated_tokens} tokens)")
144
+
145
+ elif args.command == "list":
146
+ limit = _require_valid_limit(parser, args.limit)
147
+ try:
148
+ records = store.list_records(limit=limit)
149
+ except OSError as exc:
150
+ print(f"error: failed to list records: {exc}", file=sys.stderr)
151
+ sys.exit(1)
152
+ if not records:
153
+ print("No shared context records found. Run `agent-bridge record` first.")
154
+ return
155
+ print(f"\n--- Shared Context ({len(records)} recent records) ---")
156
+ for r in records:
157
+ print(f"[{r.timestamp[:19]}] [{r.agent}] {r.topic}: {r.summary}")
158
+ print(f"\nFull log: {store.summary_md}")
159
+
160
+ elif args.command == "inject":
161
+ limit = _require_valid_limit(parser, args.limit)
162
+ adapters = {
163
+ "hermes": HermesAdapter(),
164
+ "claude": ClaudeCodeAdapter(),
165
+ "opencode": OpenCodeAdapter(),
166
+ "codex": CodexAdapter(),
167
+ }
168
+ adapter = adapters[args.target]
169
+ try:
170
+ output = adapter.format_prompt_injection(store, max_entries=limit)
171
+ except OSError as exc:
172
+ print(f"error: failed to inject context: {exc}", file=sys.stderr)
173
+ sys.exit(1)
174
+ if not output.strip():
175
+ print("No shared context records found. Run `agent-bridge record` first.")
176
+ return
177
+ print(output)
178
+
179
+ elif args.command == "export":
180
+ try:
181
+ snap = store.snapshot()
182
+ except OSError as exc:
183
+ print(f"error: failed to export snapshot: {exc}", file=sys.stderr)
184
+ sys.exit(1)
185
+ print(json.dumps(snap.to_dict(), indent=2, ensure_ascii=False))
186
+
187
+ elif args.command == "hooks":
188
+ action = args.hooks_action
189
+ if action == "claude":
190
+ max_entries = args.max_entries if args.max_entries and args.max_entries > 0 else DEFAULT_MAX_ENTRIES
191
+ if args.install:
192
+ try:
193
+ settings_path = install_claude_hook(workspace, max_entries=max_entries)
194
+ except OSError as exc:
195
+ print(f"error: failed to install Claude hook: {exc}", file=sys.stderr)
196
+ sys.exit(1)
197
+ print(f"✓ Claude SessionStart hook installed: {settings_path}")
198
+ print(f" command: {hook_command('claude', max_entries)}")
199
+ else:
200
+ print(render_claude_settings_snippet(max_entries=max_entries))
201
+ elif action == "hermes":
202
+ print(hermes_wiring_snippet())
203
+ elif action == "run":
204
+ # Drain hook payload on stdin (Claude SessionStart JSON); ignore content.
205
+ try:
206
+ if not sys.stdin.isatty():
207
+ sys.stdin.read()
208
+ except (OSError, ValueError):
209
+ pass
210
+ limit = args.max_entries
211
+ if limit is not None and limit <= 0:
212
+ parser.error("--max-entries must be a positive integer.")
213
+ try:
214
+ output = run_hook_injection(workspace, target=args.target, max_entries=limit)
215
+ except ValueError as exc:
216
+ print(f"error: {exc}", file=sys.stderr)
217
+ sys.exit(2)
218
+ if not output.strip():
219
+ print("No shared context records found. Run `agent-bridge record` first.",
220
+ file=sys.stderr)
221
+ sys.exit(0)
222
+ print(output)
223
+ else:
224
+ hooks_parser.print_help()
225
+ sys.exit(0)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
@@ -0,0 +1,208 @@
1
+ """Core data structures and storage engine for Agent Context Bridge."""
2
+
3
+ import json
4
+ from dataclasses import dataclass, field, asdict
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import List, Optional, Dict, Any
8
+
9
+ from agent_context_bridge.utils import estimate_tokens, atomic_write, sanitize_agent_name
10
+
11
+
12
+ # Hardening limits (step 2): shared validation caps.
13
+ MAX_LIST_LIMIT = 1000
14
+ MAX_AGENT_LEN = 64
15
+ MAX_TOPIC_LEN = 200
16
+ MAX_SUMMARY_LEN = 2000
17
+ MAX_DETAILS_LEN = 20000
18
+ MAX_TAGS = 20
19
+ MAX_TAG_LEN = 50
20
+
21
+
22
+ def _validate_record_fields(agent, topic, summary, details, tags) -> None:
23
+ """Validate record fields; raise ValueError with a clear message on violation."""
24
+ if agent is None or not str(agent).strip():
25
+ raise ValueError("agent must not be empty.")
26
+ if len(str(agent).strip()) > MAX_AGENT_LEN:
27
+ raise ValueError(f"agent must be at most {MAX_AGENT_LEN} characters.")
28
+ if topic is None or not str(topic).strip():
29
+ raise ValueError("topic must not be empty.")
30
+ if len(str(topic).strip()) > MAX_TOPIC_LEN:
31
+ raise ValueError(f"topic must be at most {MAX_TOPIC_LEN} characters.")
32
+ if summary is None or not str(summary).strip():
33
+ raise ValueError("summary must not be empty.")
34
+ if len(str(summary).strip()) > MAX_SUMMARY_LEN:
35
+ raise ValueError(f"summary must be at most {MAX_SUMMARY_LEN} characters.")
36
+ if details is not None and len(str(details)) > MAX_DETAILS_LEN:
37
+ raise ValueError(f"details must be at most {MAX_DETAILS_LEN} characters.")
38
+ if tags is not None:
39
+ tag_list = list(tags)
40
+ if len(tag_list) > MAX_TAGS:
41
+ raise ValueError(f"at most {MAX_TAGS} tags allowed (got {len(tag_list)}).")
42
+ for t in tag_list:
43
+ if len(str(t)) > MAX_TAG_LEN:
44
+ raise ValueError(f"each tag must be at most {MAX_TAG_LEN} characters (got {t!r}).")
45
+
46
+
47
+ def _package_version() -> str:
48
+ """Resolve the package version without hardcoding (lazy: avoids import cycle).
49
+
50
+ Prefers installed dist metadata, falls back to ``__version__``.
51
+ """
52
+ try:
53
+ from importlib.metadata import version, PackageNotFoundError
54
+
55
+ try:
56
+ return version("agent-context-bridge")
57
+ except PackageNotFoundError:
58
+ pass
59
+ except Exception:
60
+ pass
61
+ from agent_context_bridge import __version__
62
+
63
+ return __version__
64
+
65
+
66
+ @dataclass
67
+ class ContextRecord:
68
+ """A discrete unit of shared context generated by an agent."""
69
+ agent: str
70
+ topic: str
71
+ summary: str
72
+ details: Optional[str] = None
73
+ tags: List[str] = field(default_factory=list)
74
+ timestamp: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
75
+ estimated_tokens: int = 0
76
+
77
+ def __post_init__(self):
78
+ _validate_record_fields(self.agent, self.topic, self.summary, self.details, self.tags)
79
+ self.agent = sanitize_agent_name(self.agent)
80
+ total_text = f"{self.summary}\n{self.details or ''}"
81
+ if not self.estimated_tokens:
82
+ self.estimated_tokens = estimate_tokens(total_text)
83
+
84
+ def to_markdown(self) -> str:
85
+ """Serialize record into clean, human-readable markdown format."""
86
+ header = f"### [{self.timestamp}] {self.agent.upper()}: {self.topic}"
87
+ body = [header, f"**Summary:** {self.summary}"]
88
+ if self.tags:
89
+ body.append(f"**Tags:** `{', '.join(self.tags)}`")
90
+ if self.details:
91
+ body.append(f"\n{self.details.strip()}")
92
+ return "\n".join(body)
93
+
94
+ @classmethod
95
+ def from_dict(cls, data: Dict[str, Any]) -> "ContextRecord":
96
+ return cls(
97
+ agent=data.get("agent", "unknown"),
98
+ topic=data.get("topic", "general"),
99
+ summary=data.get("summary", ""),
100
+ details=data.get("details"),
101
+ tags=data.get("tags", []),
102
+ timestamp=data.get("timestamp", datetime.now(timezone.utc).isoformat()),
103
+ estimated_tokens=data.get("estimated_tokens", 0),
104
+ )
105
+
106
+
107
+ @dataclass
108
+ class BridgeSnapshot:
109
+ """A full frozen snapshot of current multi-agent context."""
110
+ version: str
111
+ project_root: str
112
+ records: List[ContextRecord] = field(default_factory=list)
113
+ generated_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
114
+
115
+ @property
116
+ def total_tokens(self) -> int:
117
+ return sum(r.estimated_tokens for r in self.records)
118
+
119
+ def to_dict(self) -> Dict[str, Any]:
120
+ return {
121
+ "version": self.version,
122
+ "project_root": self.project_root,
123
+ "generated_at": self.generated_at,
124
+ "total_tokens": self.total_tokens,
125
+ "records": [asdict(r) for r in self.records],
126
+ }
127
+
128
+
129
+ class MemoryStore:
130
+ """Local, offline file-backed context store for agents."""
131
+
132
+ def __init__(self, workspace_path: Optional[Path] = None):
133
+ self.workspace = Path(workspace_path or Path.cwd()).resolve()
134
+ self.bridge_dir = self.workspace / ".agent_bridge"
135
+ self.records_file = self.bridge_dir / "records.jsonl"
136
+ self.summary_md = self.bridge_dir / "SHARED_CONTEXT.md"
137
+
138
+ def initialize(self) -> Path:
139
+ """Create directory structure and initialize files if missing."""
140
+ self.bridge_dir.mkdir(parents=True, exist_ok=True)
141
+ if not self.records_file.exists():
142
+ atomic_write(self.records_file, "")
143
+ if not self.summary_md.exists():
144
+ header = (
145
+ "# 🧠 Shared Agent Context\n"
146
+ "> Managed automatically by `agent-context-bridge`.\n"
147
+ "> Shared across Hermes, Claude Code, OpenCode, and Codex.\n\n"
148
+ )
149
+ atomic_write(self.summary_md, header)
150
+ return self.bridge_dir
151
+
152
+ def add_record(self, record: ContextRecord) -> None:
153
+ """Append a context record and regenerate markdown summary."""
154
+ self.initialize()
155
+ # Append to records JSONL
156
+ with open(self.records_file, "a", encoding="utf-8") as f:
157
+ f.write(json.dumps(asdict(record), ensure_ascii=False) + "\n")
158
+ self.sync_markdown()
159
+
160
+ def list_records(self, limit: Optional[int] = None) -> List[ContextRecord]:
161
+ """Read all stored records, newest first.
162
+
163
+ A limit of None means no limit. Non-positive limits return [].
164
+ Positive limits are capped at MAX_LIST_LIMIT (1000).
165
+ """
166
+ if not self.records_file.exists():
167
+ return []
168
+ records = []
169
+ with open(self.records_file, "r", encoding="utf-8") as f:
170
+ for line in f:
171
+ line = line.strip()
172
+ if line:
173
+ try:
174
+ records.append(ContextRecord.from_dict(json.loads(line)))
175
+ except (json.JSONDecodeError, ValueError):
176
+ continue
177
+ records.reverse()
178
+ if limit is None:
179
+ return records
180
+ if limit <= 0:
181
+ return []
182
+ return records[:min(limit, MAX_LIST_LIMIT)]
183
+
184
+ def sync_markdown(self) -> Path:
185
+ """Compile stored records into clean SHARED_CONTEXT.md."""
186
+ records = self.list_records()
187
+ parts = [
188
+ "# 🧠 Shared Agent Context",
189
+ "> Auto-generated by `agent-context-bridge` — Offline multi-agent memory.\n",
190
+ ]
191
+ if not records:
192
+ parts.append("_No shared records recorded yet._")
193
+ else:
194
+ for r in records:
195
+ parts.append(r.to_markdown())
196
+ parts.append("\n---\n")
197
+
198
+ atomic_write(self.summary_md, "\n".join(parts))
199
+ return self.summary_md
200
+
201
+ def snapshot(self) -> BridgeSnapshot:
202
+ """Create an exportable snapshot object."""
203
+ records = self.list_records()
204
+ return BridgeSnapshot(
205
+ version=_package_version(),
206
+ project_root=str(self.workspace),
207
+ records=records,
208
+ )
@@ -0,0 +1,156 @@
1
+ """Native agent hook helpers for agent-context-bridge (zero-dependency).
2
+
3
+ Claude Code invokes SessionStart hooks as shell commands receiving a JSON
4
+ payload on stdin. ``acb hooks run`` drains that payload (ignored) and prints
5
+ the prompt-ready shared context to stdout — which Claude Code appends to the
6
+ session context. Same entrypoint serves Hermes (``--target hermes``).
7
+
8
+ Single-command wiring:
9
+
10
+ acb hooks claude --install # write .claude/settings.json SessionStart hook
11
+ echo '{}' | acb hooks run --target claude # test the hook (exit 0)
12
+ acb inject --target hermes # Hermes one-command inject
13
+ """
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Dict, List, Optional
18
+
19
+ HOOK_TARGETS = ("hermes", "claude", "opencode", "codex")
20
+
21
+ DEFAULT_MAX_ENTRIES = 5
22
+
23
+
24
+ def hook_command(target: str = "claude", max_entries: int = DEFAULT_MAX_ENTRIES) -> str:
25
+ """Shell command string registered as the agent's session-start hook."""
26
+ if max_entries == DEFAULT_MAX_ENTRIES:
27
+ return f"acb inject --target {target}"
28
+ return f"acb inject --target {target} -n {max_entries}"
29
+
30
+
31
+ def claude_settings_fragment(
32
+ target: str = "claude", max_entries: int = DEFAULT_MAX_ENTRIES
33
+ ) -> Dict:
34
+ """Return the ``.claude/settings.json`` fragment wiring SessionStart."""
35
+ return {
36
+ "hooks": {
37
+ "SessionStart": [
38
+ {
39
+ "matcher": "",
40
+ "hooks": [
41
+ {
42
+ "type": "command",
43
+ "command": hook_command(target, max_entries),
44
+ }
45
+ ],
46
+ }
47
+ ]
48
+ }
49
+ }
50
+
51
+
52
+ def render_claude_settings_snippet(
53
+ target: str = "claude", max_entries: int = DEFAULT_MAX_ENTRIES
54
+ ) -> str:
55
+ """Pretty JSON snippet the user copies into ``.claude/settings.json``."""
56
+ return json.dumps(claude_settings_fragment(target, max_entries), indent=2)
57
+
58
+
59
+ def hermes_wiring_snippet(
60
+ target: str = "hermes", max_entries: int = DEFAULT_MAX_ENTRIES
61
+ ) -> str:
62
+ """One-command Hermes wiring snippet (system context / session preamble)."""
63
+ cmd = hook_command(target, max_entries)
64
+ return (
65
+ "# Hermes Agent — shared memory wiring (agent-context-bridge)\n"
66
+ "# Run once per session preamble, or export as HERMES_SESSION_PREAMBLE_CMD:\n"
67
+ f"{cmd}\n"
68
+ "# Output is prompt-ready context between "
69
+ "<!-- HERMES MULTI-AGENT SHARED MEMORY --> markers."
70
+ )
71
+
72
+
73
+ def install_claude_hook(
74
+ workspace: Path,
75
+ target: str = "claude",
76
+ max_entries: int = DEFAULT_MAX_ENTRIES,
77
+ ) -> Path:
78
+ """Install (idempotent merge) the SessionStart hook into settings.json.
79
+
80
+ Merges into ``<workspace>/.claude/settings.json`` preserving existing
81
+ keys; appends our hook entry only if the command is not already present.
82
+ Returns the settings file path.
83
+ """
84
+ from agent_context_bridge.utils import atomic_write
85
+
86
+ settings_path = Path(workspace).resolve() / ".claude" / "settings.json"
87
+ command = hook_command(target, max_entries)
88
+
89
+ existing: Dict = {}
90
+ if settings_path.exists():
91
+ try:
92
+ existing = json.loads(settings_path.read_text(encoding="utf-8"))
93
+ if not isinstance(existing, dict):
94
+ existing = {}
95
+ except (json.JSONDecodeError, OSError, ValueError):
96
+ existing = {}
97
+
98
+ hooks = existing.setdefault("hooks", {})
99
+ if not isinstance(hooks, dict):
100
+ hooks = existing["hooks"] = {}
101
+ starts: List = hooks.setdefault("SessionStart", [])
102
+ if not isinstance(starts, list):
103
+ starts = hooks["SessionStart"] = []
104
+
105
+ already = any(
106
+ isinstance(entry, dict)
107
+ and any(
108
+ isinstance(h, dict) and h.get("command") == command
109
+ for h in entry.get("hooks", [])
110
+ )
111
+ for entry in starts
112
+ )
113
+ if not already:
114
+ starts.append(
115
+ {
116
+ "matcher": "",
117
+ "hooks": [{"type": "command", "command": command}],
118
+ }
119
+ )
120
+
121
+ atomic_write(settings_path, json.dumps(existing, indent=2) + "\n")
122
+ return settings_path
123
+
124
+
125
+ def run_hook_injection(
126
+ workspace: Path,
127
+ target: str = "hermes",
128
+ max_entries: Optional[int] = DEFAULT_MAX_ENTRIES,
129
+ ) -> str:
130
+ """Render prompt-ready context for hook execution (pure, testable).
131
+
132
+ Returns "" when the store is empty so hook callers can exit 0 silently.
133
+ """
134
+ from agent_context_bridge.adapters import (
135
+ HermesAdapter,
136
+ ClaudeCodeAdapter,
137
+ OpenCodeAdapter,
138
+ CodexAdapter,
139
+ )
140
+ from agent_context_bridge.core import MemoryStore
141
+
142
+ adapters = {
143
+ "hermes": HermesAdapter(),
144
+ "claude": ClaudeCodeAdapter(),
145
+ "opencode": OpenCodeAdapter(),
146
+ "codex": CodexAdapter(),
147
+ }
148
+ if target not in adapters:
149
+ raise ValueError(f"unknown hook target {target!r} (expected one of {HOOK_TARGETS}).")
150
+ store = MemoryStore(Path(workspace).resolve())
151
+ try:
152
+ return adapters[target].format_prompt_injection(
153
+ store, max_entries=max_entries if max_entries is not None else DEFAULT_MAX_ENTRIES
154
+ )
155
+ except OSError:
156
+ return ""
@@ -0,0 +1,33 @@
1
+ """Utility helpers for file I/O, token estimation, and formatting."""
2
+
3
+ import os
4
+ import re
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Union
8
+
9
+
10
+ def estimate_tokens(text: str) -> int:
11
+ """Fast, deterministic heuristic token count (~4 chars per token)."""
12
+ if not text:
13
+ return 0
14
+ return max(1, len(text) // 4)
15
+
16
+
17
+ def sanitize_agent_name(name: str) -> str:
18
+ """Normalize agent name to lowercase alphanumeric with hyphens."""
19
+ cleaned = re.sub(r"[^a-zA-Z0-9_\-]", "-", name.strip().lower())
20
+ return re.sub(r"-+", "-", cleaned).strip("-") or "agent"
21
+
22
+
23
+ def atomic_write(target_path: Union[str, Path], content: str, encoding: str = "utf-8") -> None:
24
+ """Safely write content to target file atomically using a temporary file."""
25
+ path = Path(target_path).resolve()
26
+ path.parent.mkdir(parents=True, exist_ok=True)
27
+ temp_dir = path.parent
28
+
29
+ with tempfile.NamedTemporaryFile("w", dir=temp_dir, delete=False, encoding=encoding) as tf:
30
+ tf.write(content)
31
+ temp_name = tf.name
32
+
33
+ os.replace(temp_name, path)
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-context-bridge
3
+ Version: 0.2.0
4
+ Summary: A lightweight, zero-dependency universal context & memory bridge for autonomous coding agents (Hermes, Claude Code, OpenCode, Codex).
5
+ Project-URL: Homepage, https://github.com/shenn667/agent-context-bridge
6
+ Project-URL: Repository, https://github.com/shenn667/agent-context-bridge
7
+ Project-URL: Issues, https://github.com/shenn667/agent-context-bridge/issues
8
+ Project-URL: Changelog, https://github.com/shenn667/agent-context-bridge/blob/main/CHANGELOG.md
9
+ Author-email: shenn667 <lehdev@yandex.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,ai,claude-code,context,developer-tools,hermes,memory,multi-agent,opencode
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Software Development :: Build Tools
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
26
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # 🌉 Agent Context Bridge (ACB)
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/agent-context-bridge.svg)](https://pypi.org/project/agent-context-bridge/)
32
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
33
+ [![Python: 3.10+](https://img.shields.io/badge/python-3.10%2B-brightgreen.svg)](https://www.python.org/)
34
+ [![CI](https://github.com/shenn667/agent-context-bridge/actions/workflows/ci.yml/badge.svg)](https://github.com/shenn667/agent-context-bridge/actions/workflows/ci.yml)
35
+
36
+ > **Universal, zero-dependency context & memory bridge for autonomous coding agents.**
37
+ > Seamlessly share project decisions, architectural constraints, and task progress between **Hermes Agent**, **Claude Code**, **OpenCode**, and **Codex**.
38
+
39
+ > ⏱️ **The 10-second version:** every AI coding tool starts blind — decisions made in one agent are lost to the next. ACB records them once (`acb record`) and replays them in each agent's native format (`acb inject`).
40
+
41
+ ![ACB demo: init → record → inject](docs/demo.gif)
42
+
43
+ *50s, no audio: `init` → `record` → `list` → `inject` for Claude & Hermes. One store (`.agent_bridge/`) → every agent.*
44
+
45
+ ---
46
+
47
+ ## 💡 The Problem: Multi-Agent Context Fragmentation
48
+
49
+ When switching between modern AI developer tools (e.g., Claude Code in terminal, Hermes swarm running in background, OpenCode in IDE):
50
+ 1. **Each agent starts blind**: Context learned by one agent in a prior turn is lost to the next.
51
+ 2. **Token waste**: Agents re-read entire repository trees to rediscover decisions already made.
52
+ 3. **No persistent audit trail**: Critical architectural choices disappear with session resets.
53
+
54
+ **Agent Context Bridge** solves this with a lightweight, file-backed offline store (`.agent_bridge/`) and dedicated adapter templates for each agent's native prompt hook format.
55
+
56
+ ---
57
+
58
+ ## ✨ Features
59
+
60
+ - **Zero Runtime Dependencies**: Pure Python standard library (`argparse`, `json`, `dataclasses`, `datetime`). Fast and crash-resilient.
61
+ - **Offline & Local-First**: No background daemon, no external database, no network calls. Works 100% offline.
62
+ - **Multi-Agent Adapters**: Native formatters for **Hermes Agent**, **Claude Code**, **OpenCode**, and **Codex**.
63
+ - **Human-Readable & Machine-Parseable**: Automatically maintains both `records.jsonl` (structured) and `SHARED_CONTEXT.md` (markdown view).
64
+ - **Fast CLI**: Simple `agent-bridge` (`acb`) command for CI, shell hooks, or direct agent execution.
65
+
66
+ ---
67
+
68
+ ## 📦 Installation
69
+
70
+ ```bash
71
+ pip install agent-context-bridge
72
+ ```
73
+
74
+ Or install locally from source:
75
+
76
+ ```bash
77
+ git clone https://github.com/shenn667/agent-context-bridge.git
78
+ cd agent-context-bridge
79
+ pip install -e .
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 🚀 Quickstart
85
+
86
+ ### 1. Initialize a Workspace
87
+
88
+ ```bash
89
+ acb init
90
+ ```
91
+ Creates `.agent_bridge/records.jsonl` and `.agent_bridge/SHARED_CONTEXT.md`.
92
+
93
+ ### 2. Record a Context Decision
94
+
95
+ ```bash
96
+ acb record \
97
+ --agent hermes-dev \
98
+ --topic "Database Engine" \
99
+ --summary "Adopted SQLite WAL mode for local agent state storage" \
100
+ --details "PostgreSQL required Docker containers; SQLite provides zero-latency offline access." \
101
+ --tag db --tag architecture
102
+ ```
103
+
104
+ ### 3. List Shared Context
105
+
106
+ ```bash
107
+ acb list
108
+ ```
109
+
110
+ ### 4. Inject Context into an Agent Session
111
+
112
+ Output prompt-ready context tailored for your target agent:
113
+
114
+ ```bash
115
+ # For Claude Code SessionStart hook:
116
+ acb inject --target claude
117
+
118
+ # For Hermes Agent system context:
119
+ acb inject --target hermes
120
+
121
+ # For OpenCode:
122
+ acb inject --target opencode
123
+ ```
124
+
125
+ ---
126
+
127
+ ## ✅ Demo locale (3 commandes)
128
+
129
+ Reproductible depuis une clone fraîche — prouve install + record/inject + version cohérente :
130
+
131
+ ```bash
132
+ pip install -e .
133
+ acb init --dir /tmp/acb-demo && acb record --dir /tmp/acb-demo --agent hermes-dev --topic "Demo" --summary "Bridge OK" && acb inject --dir /tmp/acb-demo --target hermes
134
+ acb --version
135
+ ```
136
+
137
+ Attendu : `agent-bridge 0.2.0` (identique à `pyproject.toml`, `__init__.__version__` et au tag `v0.2.0` — le workflow `release.yml` refuse la publication si tag ≠ version).
138
+
139
+ ---
140
+
141
+ ## 🪝 Hooks natifs (1 commande chacun)
142
+
143
+ ### Claude Code — SessionStart
144
+
145
+ ```bash
146
+ acb hooks claude --print # affiche le snippet .claude/settings.json
147
+ acb hooks claude --install # écrit/fusionne <workspace>/.claude/settings.json (idempotent)
148
+ echo '{}' | acb hooks run --target claude # teste le hook : exit 0 + contexte sur stdout
149
+ ```
150
+
151
+ Le hook enregistré est `acb inject --target claude` : Claude Code l'exécute à chaque
152
+ SessionStart (payload JSON sur stdin, ignoré) et le stdout est injecté en contexte de session.
153
+
154
+ ### Hermes Agent — inject
155
+
156
+ ```bash
157
+ acb hooks hermes --print # snippet de câblage (préambule de session)
158
+ acb inject --target hermes # inject 1-commande, prêt pour le system context
159
+ ```
160
+
161
+ ---
162
+
163
+ ## 🏗️ Architecture
164
+
165
+ ```
166
+ ┌──────────────────────┐
167
+ │ Your Project Repo │
168
+ └──────────┬───────────┘
169
+ │
170
+ .agent_bridge/SHARED_CONTEXT.md
171
+ .agent_bridge/records.jsonl
172
+ │
173
+ ┌─────────────────────┼─────────────────────┐
174
+ ▼ ▼ ▼
175
+ ┌───────────┐ ┌───────────┐ ┌───────────┐
176
+ │ Hermes │ │Claude Code│ │ OpenCode │
177
+ │ Adapter │ │ Adapter │ │ Adapter │
178
+ └───────────┘ └───────────┘ └───────────┘
179
+ ```
180
+
181
+ ---
182
+
183
+ ## 🧪 Running Tests
184
+
185
+ ```bash
186
+ pytest -v
187
+ ```
188
+
189
+ ---
190
+
191
+ ## 📄 License
192
+
193
+ This project is open-source under the [MIT License](LICENSE).
194
+ Authored by **shenn667** ([lehdev@yandex.com](mailto:lehdev@yandex.com)).
@@ -0,0 +1,11 @@
1
+ agent_context_bridge/__init__.py,sha256=FBwR20HYyzNHXelmR14u_sEHZzdEoFQYCe1fz3N0uPE,1222
2
+ agent_context_bridge/adapters.py,sha256=cTKaUbSUVfJbTvsjJoFmDHZl4sSAfz2HFlQreOiBdIw,3697
3
+ agent_context_bridge/cli.py,sha256=UbQNTpdBBmb9NY0dxwQi9cukYj8Gtn4_X-QCfzkE4Jc,9706
4
+ agent_context_bridge/core.py,sha256=N_lnbrHniNIfGc_2_3uuY5jIE-5IP5fBjlnmrJbJZD0,7886
5
+ agent_context_bridge/hooks.py,sha256=5Wea4adHivrTX9eEEPecetabIn5rfmUpue89lvFdRDU,5202
6
+ agent_context_bridge/utils.py,sha256=xLcBBxMms679fJ90n_YuxG2f3O0SUeQuyWCKvFVX3g4,1065
7
+ agent_context_bridge-0.2.0.dist-info/METADATA,sha256=0_VmYQXITa0CgMEws1vgevgf5QuQjsn4fEsnZ3W5DV8,7482
8
+ agent_context_bridge-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ agent_context_bridge-0.2.0.dist-info/entry_points.txt,sha256=vwMsQ2zJ2gBH7ctBUj1sHCc1XgGowVZKLEQ9vpObC4A,99
10
+ agent_context_bridge-0.2.0.dist-info/licenses/LICENSE,sha256=IpL79nGUYIwh_R-xYjGMYvb0B0yvVDKILuw_Qx5g0V4,1085
11
+ agent_context_bridge-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ acb = agent_context_bridge.cli:main
3
+ agent-bridge = agent_context_bridge.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shenn667 <lehdev@yandex.com>
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.