Skip to content

Commit ed8158b

Browse files
authored
Merge pull request #60 from ActiveMemory/feat/shared-context-hub
feat: shared context hub for cross-project knowledge sharing
2 parents 6554515 + 9efe1a9 commit ed8158b

163 files changed

Lines changed: 7003 additions & 58 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.context/TASKS.md

Lines changed: 124 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,76 @@ TASK STATUS LABELS:
2727

2828
### Misc
2929

30+
- [ ] Improve hub failover client: distinguish auth errors (Unauthenticated/PermissionDenied) from connection errors. Fail fast on auth failures instead of cycling through all peers with the same invalid token. #priority:low #added:2026-04-08-194612
31+
32+
- [ ] Add file locking to ctx connect sync state to prevent concurrent sync races. Two sync processes (hook + manual) can both load the same LastSequence, process the same entries, and write duplicate content to .context/shared/. #priority:medium #added:2026-04-08-194557
33+
34+
- [ ] Fix fanout broadcast entry loss: non-blocking send drops entries to slow listeners silently. Log when entries are dropped. Consider per-listener backpressure or disconnect-on-lag. Buffer of 64 is too small for busy hubs. #priority:medium #added:2026-04-08-194542
35+
36+
- [ ] Prevent duplicate client registration in hub store: RegisterClient should reject if ProjectName already exists. Add token revocation support (delete client by ID/project). Currently tokens are valid forever with no way to disable compromised ones. #priority:medium #added:2026-04-08-194529
37+
38+
- [ ] Fix hub cluster: NewCluster result is discarded (not stored on Server), so Raft runs but leadership status is never queryable. Store cluster reference on Server, wire IsLeader/LeaderAddr into Status RPC and hub status command. #priority:medium #added:2026-04-08-194511
39+
40+
- [ ] Use crypto/subtle.ConstantTimeCompare for hub token validation instead of string equality. Current Store.ValidateToken uses == which is vulnerable to timing attacks. Also replace O(n) linear scan with a map[string]*ClientInfo for O(1) lookup. #priority:high #added:2026-04-08-194458
41+
42+
- [ ] Fix silent error suppression in hub: (1) ctx add --share silently ignores publish failures — warn user on failure, (2) hubsync hook swallows all errors — log to event system, (3) replication loop drops errors silently — add structured logging for debug. #priority:high #added:2026-04-08-194443
43+
44+
- [ ] Add input validation to hub Publish handler: reject empty ID, validate Type against allowed set (decision/learning/convention/task), enforce Content length limit (1MB), require non-empty Origin. Prevents garbage data and DoS via unbounded content. #priority:high #added:2026-04-08-194430
45+
46+
- [ ] Fix ctx connect listen: currently only does initial sync then blocks on ctx.Done() without ever calling the Listen RPC. Must stream entries in real-time via the server-streaming Listen RPC, writing to .context/shared/ as entries arrive. #priority:high #added:2026-04-08-194415
47+
48+
- [x] Remove any superpowers library references and implement all needed workflow mechanisms (brainstorm, plan, execute, review, subagent dispatch) natively in ctx. No external plugin libraries should be used — ctx must be self-contained. Clean up docs/superpowers/ directory and any remaining references. #priority:high #added:2026-04-06-121002 #done:2026-04-06
49+
50+
- [ ] SMB mount path support: add `CTX_BACKUP_MOUNT_PATH` env var so
51+
`ctx backup` can use fstab/systemd automounts instead of requiring GVFS.
52+
Spec: specs/smb-mount-path-support.md #priority:medium #added:2026-04-04-010000
53+
54+
### Architecture Docs
55+
56+
- [ ] Publish architecture docs to docs/: copy ARCHITECTURE.md,
57+
DETAILED_DESIGN domain files, and CHEAT-SHEETS.md to docs/reference/.
58+
Sanitize intervention points into docs/contributing/.
59+
Exclude DANGER-ZONES.md and ARCHITECTURE-PRINCIPAL.md (internal only).
60+
Spec: specs/publish-architecture-docs.md #priority:medium #added:2026-04-03-150000
61+
62+
- [ ] Update ctx-architecture skill to append discovered terms to GLOSSARY.md
63+
during Phase 3. Additive only, max 10 terms per run, project-specific only,
64+
alphabetical insertion, skip if GLOSSARY.md empty. Print added terms in
65+
convergence report. Spec: specs/publish-architecture-docs.md #priority:low #added:2026-04-03-153000
66+
67+
### Code Cleanup Findings
68+
69+
70+
- [x] Extend flagbind helpers (IntFlag, DurationFlag, DurationFlagP, StringP,
71+
BoolP) and migrate ~50 call sites to unblock TestNoFlagBindOutsideFlagbind
72+
#added:2026-04-01-233250
73+
74+
- [ ] Implement journal compaction: Elastic-style tiered storage with tar.gz
75+
backup. Spec: specs/journal-compact.md #added:2026-03-31-110005
76+
77+
- [x] Refactor 28 grandfathered cmd/ purity violations found by
78+
TestCmdDirPurity: move unexported helpers, exported non-Cmd/Run functions,
79+
and types from cmd/ directories to core/. See grandfathered map in
80+
compliance_test.go for the full list. #priority:medium #added:2026-03-31-005115
81+
82+
83+
- [x] PD.4.5: Update AGENT_PLAYBOOK.md — add generic "check available skills"
84+
instruction #priority:medium #added:2026-03-25-203340
85+
86+
**PD.5 — Validate:**
87+
88+
89+
### Phase -3: DevEx
90+
91+
- [x] Plugin enablement gap: Ref:
92+
`ideas/plugin-enablement-gap.md`. Local-installed plugins get
93+
registered in `installed_plugins.json` but not auto-added to
94+
`enabledPlugins`, so slash commands are invisible in non-ctx
95+
projects.
96+
97+
- [x] Add cobra Example fields to CLI commands via
98+
examples.yaml #added:2026-03-20-163413
99+
30100
- [x] Add CLI YAML drift detection test: verify flag names in
31101
examples.yaml match actual registered flags, and Use: patterns
32102
in commands.yaml match Use constants. Structural linkage is
@@ -165,13 +235,13 @@ Session-start checks, suppressibility, and registry for companion MCP tools.
165235

166236
### Phase CLI-FIX: CLI Infrastructure Fixes
167237

168-
- [ ] Bug: ctx add task appends to the last Phase section instead of a dedicated
238+
- [x] Bug: ctx add task appends to the last Phase section instead of a dedicated
169239
location. Tasks added via CLI land inside whatever Phase happens to be last in
170-
TASKS.md, breaking Phase structure. Fix: add mandatory --phase flag to ctx add
171-
task. If the named Phase section does not exist, create it. If --phase is
172-
omitted, error with available Phase names. No fallback section — mandatory
173-
placement forces intent at creation time.
174-
#priority:high #added:2026-03-25-234813
240+
TASKS.md, breaking Phase structure. Fix: add mandatory --section flag to ctx add
241+
task. If the named section does not exist, create it. If --section is
242+
omitted, error with message. Heading level fixed from ## to ### to match
243+
TASKS.md structure.
244+
#priority:high #added:2026-03-25-234813 #done:2026-04-06
175245

176246
### Phase BLOG: Blog Posts
177247

@@ -951,3 +1021,51 @@ Not a fit (keep in `ctx`):
9511021
template placeholder instead of literal tool names. Define minimum interface
9521022
contract (query, context, impact). Spec:
9531023
`ideas/spec-mcp-warm-up-ceremony.md` #added:2026-03-25-120000
1024+
1025+
- [x] HUB-1: Define hub.proto — gRPC service definition with Register, Publish, Sync, Listen, Status RPCs. Generate Go code. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113020 #done:2026-04-06
1026+
1027+
- [x] HUB-2: Implement internal/hub/store.go — JSONL append-only entry storage with sequence assignment, type filtering, and since-sequence queries. Spec: specs/hub_implementation.md #priority:high #added:2026-04-06-113021 #done:2026-04-06
1028+
1029+
- [x] HUB-3: Implement internal/hub/auth.go — admin token generation on first run, client token issuance via Register RPC, gRPC interceptor for Bearer token validation. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113022 #done:2026-04-06
1030+
1031+
- [x] HUB-4: Implement internal/hub/server.go — gRPC server with Register, Publish, Sync RPCs. Wire auth interceptor, JSONL store, TLS support. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113024 #done:2026-04-06
1032+
1033+
- [x] HUB-5: Implement ctx serve --shared CLI command — starts gRPC hub server on specified port, generates admin token on first run, supports --tls-cert/--tls-key flags. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113030 #done:2026-04-06
1034+
1035+
- [x] HUB-6: Implement internal/hub/client.go — gRPC client with Register, Sync, Publish, Listen methods. Connection config encrypted storage via internal/crypto (same pattern as notify). Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113032 #done:2026-04-06
1036+
1037+
- [x] HUB-7: Implement ctx connect register — one-time registration with hub, stores encrypted connection config in .context/.connect.enc. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-113033 #done:2026-04-06
1038+
1039+
- [x] HUB-8: Implement ctx connect subscribe — set entry type filters (decisions, learnings, conventions), persist in local connection config. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113035 #done:2026-04-07
1040+
1041+
- [x] HUB-9: Implement ctx connect sync — initial full pull of matching entries from hub, write to .context/shared/ as markdown files with origin tags, record last-seen sequence in .sync-state.json. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113041 #done:2026-04-07
1042+
1043+
- [x] HUB-10: Implement ctx connect publish and --share flag — push local entries to hub. Add --share flag to ctx add so entries go to local file AND hub simultaneously. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113043 #done:2026-04-07
1044+
1045+
- [x] HUB-11: Implement Listen RPC with fan-out — server-streaming RPC that pushes new entries to connected clients in real-time. ctx connect listen with auto-reconnect on disconnect. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113044 #done:2026-04-07
1046+
1047+
- [x] HUB-12: Implement ctx connect status — show server address, connection state, last sync time, subscription config, entry counts by type. Includes hub-side Status RPC. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113046 #done:2026-04-07
1048+
1049+
- [x] HUB-13: Implement ctx agent --include-shared — add Tier 8 budget for shared knowledge in agent packet assembly. Shared entries from .context/shared/ included when --include-shared flag is passed. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113053 #done:2026-04-07
1050+
1051+
- [x] HUB-14: Implement --daemon flag for ctx serve --shared — background process with PID file, --stop to kill, graceful shutdown. Required for federation. Spec: specs/shared-hub-federation.md #priority:medium #added:2026-04-06-113054
1052+
1053+
- [x] HUB-15: Integrate hashicorp/raft for leader election — Raft-lite: use Raft ONLY for master election, not data consensus. --peers flag for cluster membership. Single-node mode auto-elects. Spec: specs/shared-hub-federation.md #priority:medium #added:2026-04-06-113056
1054+
1055+
- [x] HUB-16: Implement master-to-follower replication — master pushes entries to followers via gRPC stream. Followers catch up via sequence-based sync on reconnect. Spec: specs/shared-hub-federation.md #priority:medium #added:2026-04-06-113058
1056+
1057+
- [x] HUB-17: Implement client failover — clients maintain ordered peer list, auto-reconnect to new master on connection failure. Follower redirects client to current master address. Spec: specs/shared-hub-federation.md #priority:medium #added:2026-04-06-113104
1058+
1059+
- [x] HUB-18: Implement ctx hub status/peer/stepdown — cluster status display (role, peers, sync state, entries, uptime), runtime peer add/remove, graceful leadership transfer. Spec: specs/shared-hub-federation.md #priority:low #added:2026-04-06-113106
1060+
1061+
- [x] HUB-19: Update compliance test — add internal/hub/ to allowed-net-import list alongside internal/notify/. Core packages remain network-free. Spec: specs/hub_implementation.md #priority:high #added:2026-04-06-113107
1062+
1063+
- [x] HUB-20: End-to-end integration test — spin up hub, register 2 clients, publish from one, verify sync on other. Test --share flag, Listen stream, and reconnect behavior. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-113109
1064+
1065+
- [x] HUB-2a: Implement hub client registry and meta persistence — clients.json for registered client tokens/project names, meta.json for sequence counter and hub metadata. Separate from entries.jsonl. Spec: specs/shared-context-hub.md #priority:high #added:2026-04-06-114131
1066+
1067+
- [x] HUB-9a: Implement shared file renderer — convert Entry objects to markdown with origin tags and date headers, create/append to .context/shared/*.md files. Reused by both ctx connect sync and ctx connect listen. Spec: specs/shared-context-hub.md #priority:medium #added:2026-04-06-114131
1068+
1069+
- [x] HUB-21: Unit tests for internal/hub/ — store (append, query, rotation), auth (token generation, validation, interceptor), client (connect, reconnect), renderer (markdown output). Each package tested independently. Spec: specs/hub_implementation.md #priority:medium #added:2026-04-06-114131
1070+
1071+
- [x] HUB-22: Documentation — create docs/cli/connect.md and docs/cli/serve.md for new commands, update docs/cli/agent.md for --include-shared flag and --shared-budget option. Spec: specs/shared-context-hub.md #priority:low #added:2026-04-06-114131

docs/cli/connect.md

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
---
2+
# / ctx: https://ctx.ist
3+
# ,'`./ do you remember?
4+
# `.,'\
5+
# \ Copyright 2026-present Context contributors.
6+
# SPDX-License-Identifier: Apache-2.0
7+
8+
title: Connect
9+
icon: lucide/link
10+
---
11+
12+
## `ctx connect`
13+
14+
Connect to a shared context hub for cross-project knowledge sharing.
15+
Projects publish decisions, learnings, and conventions to a centralized
16+
hub; other projects receive them alongside local context.
17+
18+
### `ctx connect register`
19+
20+
One-time registration with a shared hub. Requires the hub address and
21+
admin token (printed by `ctx serve --shared` on first run).
22+
23+
```bash
24+
ctx connect register localhost:9900 --token ctx_adm_7f3a...
25+
```
26+
27+
On success, stores an encrypted connection config in
28+
`.context/.connect.enc` for future RPCs.
29+
30+
### `ctx connect subscribe`
31+
32+
Set which entry types to receive from the hub. Only matching types
33+
are returned by sync and listen.
34+
35+
```bash
36+
ctx connect subscribe decision learning
37+
ctx connect subscribe decision learning convention
38+
```
39+
40+
### `ctx connect sync`
41+
42+
Pull matching entries from the hub and write them to
43+
`.context/shared/` as markdown files with origin tags and date
44+
headers. Tracks last-seen sequence for incremental sync.
45+
46+
```bash
47+
ctx connect sync
48+
```
49+
50+
### `ctx connect publish`
51+
52+
Push entries to the hub. Specify type and content as arguments.
53+
54+
```bash
55+
ctx connect publish decision "Use UTC timestamps everywhere"
56+
```
57+
58+
### `ctx connect listen`
59+
60+
Stream new entries from the hub in real-time. Writes to
61+
`.context/shared/` as entries arrive. Press Ctrl-C to stop.
62+
63+
```bash
64+
ctx connect listen
65+
```
66+
67+
### `ctx connect status`
68+
69+
Show hub connection state and entry statistics.
70+
71+
```bash
72+
ctx connect status
73+
```
74+
75+
## Automatic sharing
76+
77+
Use `--share` on `ctx add` to write locally AND publish to the hub:
78+
79+
```bash
80+
ctx add decision "Use UTC" --share \
81+
--context "Need consistency" \
82+
--rationale "Avoid timezone bugs" \
83+
--consequence "UI does conversion"
84+
```
85+
86+
If the hub is unreachable, the local write succeeds and a warning
87+
is printed. The `--share` flag is best-effort — it never blocks
88+
local context updates.
89+
90+
## Auto-sync
91+
92+
Once registered, the `check-hub-sync` hook automatically syncs
93+
new entries from the hub at the start of each session (daily
94+
throttled). No manual `ctx connect sync` needed.
95+
96+
## Shared files
97+
98+
Entries from the hub are stored in `.context/shared/`:
99+
100+
```
101+
.context/shared/
102+
decisions.md # Shared decisions with origin tags
103+
learnings.md # Shared learnings
104+
conventions.md # Shared conventions
105+
.sync-state.json # Last-seen sequence tracker
106+
```
107+
108+
These files are read-only (managed by sync/listen) and never
109+
mixed with local context files.
110+
111+
## Agent integration
112+
113+
Include shared knowledge in agent context packets:
114+
115+
```bash
116+
ctx agent --include-shared
117+
```
118+
119+
Shared entries are included as Tier 8 in the budget-aware
120+
assembly, scored by recency and type relevance.

docs/cli/hub.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
---
2+
# / ctx: https://ctx.ist
3+
# ,'`./ do you remember?
4+
# `.,'\
5+
# \ Copyright 2026-present Context contributors.
6+
# SPDX-License-Identifier: Apache-2.0
7+
8+
title: Hub
9+
icon: lucide/network
10+
---
11+
12+
## `ctx hub`
13+
14+
Manage a running shared context hub cluster.
15+
16+
### `ctx hub status`
17+
18+
Show cluster status: role, entry count, and connected projects.
19+
20+
```bash
21+
ctx hub status
22+
```
23+
24+
### `ctx hub peer`
25+
26+
Add or remove peers from the cluster at runtime.
27+
28+
```bash
29+
ctx hub peer add host2:9901
30+
ctx hub peer remove host2:9901
31+
```
32+
33+
### `ctx hub stepdown`
34+
35+
Transfer leadership to another node gracefully. Use before
36+
taking a node offline for maintenance.
37+
38+
```bash
39+
ctx hub stepdown
40+
```

docs/cli/index.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ own guards and no-op gracefully.
6060
| [`ctx learning`](context.md#ctx-learning) | Manage `LEARNINGS.md` (reindex) |
6161
| [`ctx journal`](recall.md#ctx-recall) | Browse and export AI session history |
6262
| [`ctx journal`](recall.md#ctx-journal) | Generate static site from journal entries |
63-
| [`ctx serve`](recall.md#ctx-serve) | Serve any zensical directory (default: journal site) |
63+
| [`ctx serve`](serve.md#ctx-serve) | Serve journal site or shared context hub |
6464
| [`ctx watch`](tools.md#ctx-watch) | Auto-apply context updates from AI output |
6565
| [`ctx setup`](tools.md#ctx-hook) | Generate AI tool integration configs |
6666
| [`ctx loop`](tools.md#ctx-loop) | Generate autonomous loop script |
@@ -81,6 +81,8 @@ own guards and no-op gracefully.
8181
| [`ctx hook`](tools.md#ctx-hook) | Manage lifecycle hooks (shell scripts for automation) |
8282
| [`ctx skill`](tools.md#ctx-skill) | Manage reusable instruction bundles |
8383
| [`ctx config`](config.md#ctx-config) | Manage runtime configuration profiles |
84+
| [`ctx connect`](connect.md#ctx-connect) | Connect to a shared context hub |
85+
| [`ctx hub`](hub.md#ctx-hub) | Manage hub cluster (status, peer, stepdown) |
8486
| [`ctx system`](system.md#ctx-system) | System diagnostics and hook commands |
8587

8688
---

docs/cli/init-status.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ ctx agent [flags]
101101
| `--format` | md | Output format: `md` or `json` |
102102
| `--cooldown` | 10m | Suppress repeated output within this duration (requires `--session`) |
103103
| `--session` | (none) | Session ID for cooldown isolation (e.g., `$PPID`) |
104+
| `--include-shared` | false | Include shared hub entries from `.context/shared/` |
104105

105106
**How budget works**:
106107

@@ -112,6 +113,9 @@ in priority tiers:
112113
3. **Conventions**: all conventions, up to 20% of budget
113114
4. **Decisions**: scored by recency and relevance to active tasks
114115
5. **Learnings**: scored by recency and relevance to active tasks
116+
6. **Steering**: applicable steering file bodies
117+
7. **Skill**: named skill content (from `--skill`)
118+
8. **Shared**: hub entries from `.context/shared/` (with `--include-shared`)
115119

116120
Decisions and learnings are ranked by a combined score (how recent + how
117121
relevant to your current tasks). High-scoring entries are included with

0 commit comments

Comments
 (0)