{"id":48456293,"url":"https://github.com/iampantherr/securecontext","last_synced_at":"2026-05-03T07:02:02.652Z","repository":{"id":344745684,"uuid":"1182898907","full_name":"iampantherr/SecureContext","owner":"iampantherr","description":"Secure memory \u0026 context optimization MCP plugin for Claude Code. Drop-in replacement for context-mode with credential isolation, SSRF protection, MemGPT-style persistent memory, and hybrid BM25+vector search. 84 security tests, zero cloud sync.","archived":false,"fork":false,"pushed_at":"2026-04-18T00:18:21.000Z","size":1063,"stargazers_count":5,"open_issues_count":0,"forks_count":4,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-18T00:33:03.216Z","etag":null,"topics":["ai-agent-memory","claude-code","claude-code-plugin","context-management","context-mode-alternative","context-window","hybrid-search","knowledge-base","llm-memory","mcp","mcp-server","memgpt","persistent-memory","secure-mcp","zeroclaw"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/iampantherr.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY_REPORT.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-16T04:15:09.000Z","updated_at":"2026-04-18T00:18:25.000Z","dependencies_parsed_at":null,"dependency_job_id":"d46afd8a-293a-43d6-b302-beb9748db459","html_url":"https://github.com/iampantherr/SecureContext","commit_stats":null,"previous_names":["iampantherr/securecontext"],"tags_count":14,"template":false,"template_full_name":null,"purl":"pkg:github/iampantherr/SecureContext","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iampantherr%2FSecureContext","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iampantherr%2FSecureContext/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iampantherr%2FSecureContext/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iampantherr%2FSecureContext/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/iampantherr","download_url":"https://codeload.github.com/iampantherr/SecureContext/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iampantherr%2FSecureContext/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31982755,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T17:30:12.329Z","status":"ssl_error","status_checked_at":"2026-04-18T17:29:59.069Z","response_time":103,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agent-memory","claude-code","claude-code-plugin","context-management","context-mode-alternative","context-window","hybrid-search","knowledge-base","llm-memory","mcp","mcp-server","memgpt","persistent-memory","secure-mcp","zeroclaw"],"created_at":"2026-04-06T23:05:05.500Z","updated_at":"2026-05-03T07:02:02.624Z","avatar_url":"https://github.com/iampantherr.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SecureContext — Secure Multi-Agent Harness for Claude Code\n\n\u003e **Persistent memory, verifiable telemetry, and work-stealing coordination for multi-agent Claude Code sessions.**\n\u003e Built on the principle: *cybersecurity into the architecture, not bolted on.* HMAC-chained audit trail, per-agent cryptographic identity, Postgres Row-Level Security, atomic work distribution, closed learning loop. Zero cloud sync. MIT license.\n\n[![Version](https://img.shields.io/badge/version-0.22.5-blue)](package.json)\n[![Tests](https://img.shields.io/badge/tests-786%20passed-brightgreen)](src)\n[![Security Tests](https://img.shields.io/badge/security%20red%20team-60%2B%20RT%20IDs-brightgreen)](security-tests)\n[![CI](https://github.com/iampantherr/SecureContext/actions/workflows/ci.yml/badge.svg)](https://github.com/iampantherr/SecureContext/actions)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![Node](https://img.shields.io/badge/node-%3E%3D22-green)](package.json)\n\n---\n\n## What SecureContext Is Today\n\nSecureContext started as a token-optimization memory plugin. Through 17 sprints of design + red-team verification it evolved into something larger:\n\n**A hardened harness for running multi-agent Claude Code sessions** where multiple agents (Opus orchestrator + Sonnet worker pool) coordinate through a verifiable audit trail, share memory across sessions, distribute work atomically through a Postgres queue, and feed failures back into a learning corpus — all while staying within the Claude Code TUI (so Claude Pro auth keeps working — no API-key upgrade required).\n\nFour pillars:\n\n| Pillar | What it means |\n|---|---|\n| **Persistent memory** | Working memory facts, session summaries, KB search — survives Claude Code restarts. MemGPT-style importance scoring; hybrid BM25 + vector retrieval. |\n| **Verifiable security** | HMAC hash chain over every tool call + outcome. Per-agent HKDF subkeys — agent A cryptographically cannot forge a row claiming to be agent B. Postgres RLS with per-query `SET LOCAL ROLE`. Credential-isolated sandbox for `zc_execute`. |\n| **Multi-agent coordination** | Broadcast channel for ASSIGN / STATUS / MERGE. Postgres work-stealing queue (`FOR UPDATE SKIP LOCKED`) for atomic task distribution across worker pools. Dynamic role spawn via LAUNCH_ROLE. Dispatcher nudge + Stop-hook enforcement to prevent worker drift. |\n| **Closed learning loop** | Per-tool-call telemetry with real cost accounting. Three outcome resolvers (git_commit, user_prompt sentiment, follow-up pattern). Outcomes auto-feed `learnings/failures.jsonl` + `learnings/experiments.jsonl` — no agent discipline required. |\n\n---\n\n## Headline Numbers\n\n| Metric | Result |\n|---|---|\n| Token overhead per session (vs. native Claude re-paste) | **~87% lower** |\n| Claude Opus cost per session (tool-call overhead only) | **~$0.16** vs. ~$2–5 native |\n| Recall cache hit saves | **~800 tokens per call** (~$0.06 on Opus) |\n| Unit + integration tests | **786 passing** |\n| Red-team attack IDs verified | **60+ (RT-S0 through RT-S4)** |\n| Hash-chain forgery resistance | Cryptographic (per-agent HKDF subkey) |\n| Agents per role (work-stealing pool) | **1 to 20** (tested 50 × 100 no double-claim) |\n\n---\n\n## Key Capabilities\n\n### 1. Persistent Memory That Survives Restarts\n\nClaude's context window is lossy. When it compacts, architecture decisions, file locations, and task state vanish. SecureContext persists them.\n\n- **Working memory**: `zc_remember(\"api_key_rotation_decided\", \"use KMS\", importance=5)`. Bounded to 100–250 facts (auto-scales with project complexity). Lowest-importance facts evict to archival KB rather than disappearing.\n- **Session summaries**: `zc_summarize_session()` archives a structured summary for 365 days. Retrievable via `zc_search([\"prior session\"])`.\n- **Shared broadcast channel**: multi-agent A2A coordination (ASSIGN, STATUS, MERGE, DEPENDENCY, PROPOSED, REJECT, REVISE, LAUNCH_ROLE, RETIRE_ROLE).\n- **Hybrid KB search**: FTS5 BM25 + Ollama vector reranking. Falls back cleanly to BM25-only if Ollama is unavailable.\n- **Cross-project search**: `zc_search_global` federates across all local project KBs.\n\n### 2. Security That Auditors Can Verify\n\n- **HMAC-chained rows** on `tool_calls_pg` + `outcomes_pg`. Tampering with any row breaks the chain; `verifyChain()` detects it deterministically.\n- **Per-agent HKDF subkeys**: each agent signs its rows with a key derived from the shared machine secret + agent_id. No other agent can produce a valid signature. **RT-S2-01 proves it with a live forgery attempt.**\n- **Postgres RLS (T3.2)**: 4 policies on `outcomes_pg` for the classification tiers public/internal/confidential/restricted. `restricted` rows visible only to the writing agent via `current_setting('zc.current_agent', true)`.\n- **Per-query `SET LOCAL ROLE` (T3.1)**: every write transaction switches to a per-agent Postgres role so a compromised agent can't escalate its database identity.\n- **Credential-isolated sandbox** for `zc_execute`: PATH-only environment, 30s timeout, 512 KB output cap, no ANTHROPIC_API_KEY / AWS / GitHub tokens leak through.\n- **Secret scanner** on 11 patterns + high-entropy detection, runs before any external send.\n- **Audit log** — append-only HMAC-chained — survives even catastrophic context compaction.\n\n### 3. Multi-Agent Coordination (Production-Grade)\n\nVia the companion [A2A_dispatcher](https://github.com/iampantherr/A2A_dispatcher):\n\n- **Worker pools with -WorkerCount N**: `start-agents.ps1 -Roles developer -WorkerCount 3` spawns `developer-1/2/3`, all sharing `role=\"developer\"` and one work-stealing queue.\n- **Atomic work distribution**: Postgres `FOR UPDATE SKIP LOCKED` guarantees each queued task is claimed exactly once. Unit-verified with 50 concurrent workers racing for 100 tasks (RT-S4-01 — zero double-claims).\n- **File-ownership overlap guard**: `/api/v1/broadcast` rejects ASSIGN with HTTP 409 Conflict if `file_ownership_exclusive` overlaps an in-flight task's set. Two workers can never be given the same file.\n- **Dynamic role spawn**: orchestrator broadcasts `LAUNCH_ROLE state=qa` → dispatcher spawns a QA agent mid-session. Matching `RETIRE_ROLE` cleans it up.\n- **Dispatcher wake-nudge**: polls the queue every 15s; if a role has queued tasks and alive workers aren't claiming, sends them a direct \"call zc_claim_task now\" message.\n- **Stop-hook enforcement**: blocks a worker from ending its session if the queue still has claimable tasks for its role (forces drain-before-summarize).\n- **Role-tagged registration**: `agents.json._agent_roles` sidecar maps agent_id → role so the dispatcher can route by pool.\n\n### 4. Honest Cost Accounting\n\nEvery MCP tool call produces a row with input_tokens, output_tokens, model, latency, status, and cost_usd. v0.17.2 corrections:\n\n- **Tier 1** — `computeToolCallCost` prices from the LLM's perspective: tool call args at output rate (LLM generated), tool response at input rate (LLM ingests next turn). Naive accounting over-reported Opus recall cost by 5×.\n- **Tier 2** — DB-assembly tools (`zc_recall_context`, `zc_file_summary`, `zc_project_card`, `zc_status`) show $0 cost so the orchestrator's delegate-vs-DIY decision isn't polluted by infra noise.\n- **Opus orchestrator makes real cost trade-offs**: \"should I read this file myself (Opus input rate) or delegate to a developer (Sonnet) via ASSIGN broadcast overhead?\" With honest numbers, the trade is decidable.\n\n### 5. Closed Learning Loop (v0.17.2 L4)\n\nWhen `recordOutcome({outcomeKind: \"rejected\" | \"failed\" | \"insufficient\" | \"errored\" | \"reverted\"})` lands, it also atomically appends a structured JSON line to `\u003cproject\u003e/learnings/failures.jsonl`. High-confidence `shipped` / `accepted` outcomes append to `experiments.jsonl`. No agent discipline required.\n\nFuture sessions surface those learnings via `zc_search([\"past failures for X\"])` — the loop is now structural, not behavioral.\n\n### 6. Self-Improving Skills (v0.18.0 Sprint 2)\n\nSkills are versioned, hash-protected markdown procedures that agents discover at session start and follow when doing work. They improve themselves over time:\n\n- **Two-scope hierarchy**: per-project skills override global. Per-project optimizations don't pollute other projects.\n- **Composite outcome scoring**: every skill execution records `accuracy + cost + speed` into `skill_runs`. Failure traces feed the mutator.\n- **Pluggable mutators**: `local-mock` (free, deterministic), `realtime-sonnet` (Anthropic API direct), `batch-sonnet` (50% discount via Batch API). Allowlist-enforced via `ZC_MUTATOR_MODEL` env var (RT-S2-05).\n- **Synthetic-fixture replay**: candidates are validated against hand-crafted fixtures before promotion. Pass/fail + accuracy gate prevents regressions.\n- **Atomic promotion**: when a candidate beats parent by ≥10% AND meets acceptance criteria, parent is archived and new version is inserted in one transaction.\n- **Cross-project promotion**: `findGlobalPromotionCandidates` walks `skill_runs_pg` to surface per-project versions consistently outperforming global. Operator approves before global publishes.\n- **Audit trail**: every candidate (promoted or not) lands in `skill_mutations`. `body_hmac` verified at every load (RT-S2-08); `candidate_hmac` verified at every replay (RT-S2-09).\n- **agentskills.io interop**: lossless export/import via the open standard.\n\n7 new MCP tools: `zc_skill_list`, `zc_skill_show`, `zc_skill_score`, `zc_skill_run_replay`, `zc_skill_propose_mutation`, `zc_skill_export`, `zc_skill_import`. See [docs/SKILLS_WALKTHROUGH.md](docs/SKILLS_WALKTHROUGH.md) for the full lifecycle + cron setup + mutator selection.\n\n### 7. Architectural Quality Gates\n\nThree automated checks prevent whole classes of regression:\n\n- **L1 — env-pinning linter** (`npm run check:env`): scans `src/` for `process.env.ZC_*` refs, asserts every CRITICAL var (like `ZC_AGENT_ID`) is explicitly pinned in the dispatcher's launcher templates. Would have caught the pre-v0.17.0 bug where every agent's MCP server inherited the last-written agent_id (breaking per-agent HKDF isolation). 14-case self-test.\n- **L3 — no-floating-promises ESLint** (`npm run lint`): `@typescript-eslint/no-floating-promises` caught 3 real violations on install. Equivalent bug silently dropped 9 months of outcome writes when `outcomes.ts` became async in v0.12.0. 5-case regression self-test.\n- **L4 — outcome auto-feedback** (see above): the learning loop itself is enforced in code, not by convention.\n\n---\n\n## Architecture at a Glance\n\n```\n                     ┌──────────────────┐\n                     │ Claude Code TUI  │\n                     │ (Opus + Sonnet)  │\n                     └────────┬─────────┘\n                              │ MCP (stdio)\n               ┌──────────────┴──────────────┐\n               │    SecureContext server     │\n               │    (src/server.ts)          │\n               └──┬──┬──┬──┬──────────────┬──┘\n                  │  │  │  │              │\n                  │  │  │  │              ▼\n                  │  │  │  │       zc_execute (sandbox)\n                  │  │  │  │       zc_fetch   (SSRF-guarded)\n                  │  │  │  ▼\n                  │  │  │  zc_enqueue_task / zc_claim_task (SKIP LOCKED)\n                  │  │  ▼\n                  │  │  zc_broadcast (HMAC-chained, ownership-guarded)\n                  │  ▼\n                  │  zc_recall_context (60s TTL cache; per-agent scoped)\n                  ▼\n                  zc_remember / zc_search (working memory + KB)\n\n         All persisted to one of:\n         • ~/.claude/zc-ctx/sessions/{projectHash}.db  (SQLite, local)\n         • sc-postgres                                 (Docker, PG + pgvector)\n```\n\nComplete architecture: [ARCHITECTURE.md](ARCHITECTURE.md). Threat model: [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). Harness usage rules: [AGENT_HARNESS.md](AGENT_HARNESS.md).\n\n---\n\n## MCP Tools (25)\n\n### Memory + Retrieval (7)\n| Tool | What it does |\n|---|---|\n| `zc_remember` | Store a fact with importance score (1–5) and optional agent namespace |\n| `zc_forget` | Remove a fact |\n| `zc_recall_context` | Restore working memory + broadcasts + session events (60s cache with change-detection) |\n| `zc_summarize_session` | Archive session summary to 365-day KB |\n| `zc_search` | Hybrid BM25 + vector search in current project |\n| `zc_search_global` | Federated search across all local project KBs |\n| `zc_status` | DB health + KB counts + working-memory fill + fetch budget |\n\n### Indexing + Knowledge (5)\n| Tool | What it does |\n|---|---|\n| `zc_index` | Manually index text into the KB |\n| `zc_fetch` | Fetch a URL (SSRF-checked) → Markdown → indexed as `[EXTERNAL]` |\n| `zc_index_project` | Bulk-index project tree with semantic L0/L1 via local Ollama |\n| `zc_file_summary` | L0/L1 summary accessor (replaces Read for check/review questions) |\n| `zc_project_card` | Per-project orientation card (stack, state, gotchas) — read or update |\n\n### Execution + Analysis (5)\n| Tool | What it does |\n|---|---|\n| `zc_execute` | Run Python/JS/Bash in credential-isolated sandbox |\n| `zc_execute_file` | Analyse a specific file in sandbox (stdin-passed TARGET_FILE) |\n| `zc_batch` | Run shell commands AND search KB in one parallel call |\n| `zc_check` | Memory-first answer with confidence scoring (high/medium/low/none) |\n| `zc_capture_output` | Archive long bash output to KB (auto-called by PostBash hook) |\n\n### Multi-Agent Coordination (2)\n| Tool | What it does |\n|---|---|\n| `zc_broadcast` | Post to A2A shared channel: ASSIGN/STATUS/MERGE/PROPOSED/DEPENDENCY/REJECT/REVISE/LAUNCH_ROLE/RETIRE_ROLE. File-ownership overlap guard at API layer. |\n| `zc_explain` | Trace how a specific broadcast was routed / acknowledged |\n\n### Work-Stealing Queue (6) — v0.17.0\n| Tool | What it does |\n|---|---|\n| `zc_enqueue_task` | Orchestrator enqueues into `task_queue_pg` keyed by (project, role) |\n| `zc_claim_task` | Worker atomically claims oldest queued task (FOR UPDATE SKIP LOCKED) |\n| `zc_heartbeat_task` | Refresh claim (workers must call every 30s) |\n| `zc_complete_task` | Mark claimed task done |\n| `zc_fail_task` | Mark failed + bump retries counter |\n| `zc_queue_stats` | Count by state {queued, claimed, done, failed} |\n\n### Graph Analysis (3) — v0.13.0\n| Tool | What it does |\n|---|---|\n| `zc_graph_query` / `zc_graph_path` / `zc_graph_neighbors` | Proxy to [graphify](https://github.com/safishamsi/graphify) subprocess |\n| `zc_kb_cluster` | Louvain community detection over KB graph |\n| `zc_kb_community_for` | Look up community of a specific KB source + community-mates |\n\n### Cost Routing + Replay (2)\n| Tool | What it does |\n|---|---|\n| `zc_choose_model` | Returns Haiku/Sonnet/Opus recommendation for a complexity (informational — orchestrator decides) |\n| `zc_replay` / `zc_ack` | Replay un-acknowledged broadcasts / mark one as seen |\n\n### RBAC (2)\n| Tool | What it does |\n|---|---|\n| `zc_issue_token` | Short-lived HMAC-signed session token bound to (agent_id, role) |\n| `zc_revoke_token` | Revoke all tokens for an agent |\n\n### Observability (1)\n| Tool | What it does |\n|---|---|\n| `zc_logs` | Query structured logs (per-component, agent-scoped, trace_id correlation) |\n\n---\n\n## Installation\n\n### Docker Stack (recommended)\n\n**Prerequisites**: Docker Desktop 4.x+, Node.js 22+.\n\n```bash\ngit clone https://github.com/iampantherr/SecureContext\ncd SecureContext\ncp docker/.env.example docker/.env\n# Edit docker/.env: set POSTGRES_PASSWORD + ZC_API_KEY (generate via crypto.randomBytes)\n```\n\nStart the stack:\n```powershell\n# Windows — auto-detects NVIDIA / AMD / CPU\n.\\docker\\start.ps1\n```\n```bash\n# Linux / macOS\n./docker/start.sh\n```\n\nThree containers come up: `securecontext-postgres` (PG + pgvector), `securecontext-api` (HTTP API), `securecontext-ollama` (embeddings). All set to `restart: unless-stopped` — they come back on every boot.\n\nVerify:\n```bash\ncurl http://localhost:3099/health\n# {\"status\":\"ok\",\"version\":\"0.22.5\",\"store\":\"postgres\",\"ollamaAvailable\":true,\"searchMode\":\"hybrid (BM25 + vector)\"}\n```\n\nRegister with Claude:\n```bash\nnode install.mjs --remote http://localhost:3099 \u003cyour-ZC_API_KEY\u003e\n```\nRestart Claude Code after running.\n\n### Local SQLite (single-developer, no Docker)\n\n**Prerequisites**: Node.js 22+ only. Clone repo, `npm install`, `npm run build`, then:\n\n```bash\nnode install.mjs --local\n```\n\nWrites `~/.claude/settings.json`'s MCP `zc-ctx` entry pointing at `dist/server.js`. Data lives in `~/.claude/zc-ctx/sessions/{projectHash}.db`. No vector search (falls back to BM25) unless Ollama is installed locally at `http://127.0.0.1:11434`.\n\n### Multi-Agent Harness\n\nTo run multi-agent sessions, also clone the companion dispatcher:\n```bash\ngit clone https://github.com/iampantherr/A2A_dispatcher\ncd A2A_dispatcher\n# Launch 1 orchestrator (Opus) + 3 developers (Sonnet) sharing one queue:\npowershell -File start-agents.ps1 -Project C:\\path\\to\\your\\project -Roles developer -WorkerCount 3\n```\n\nSee A2A_dispatcher's README for LAUNCH_ROLE / RETIRE_ROLE / file ownership details.\n\n---\n\n## Quick Start\n\nIn a new Claude Code session on your project:\n\n```\nYou: please restore context and tell me what we were working on\n\nClaude:  (calls zc_recall_context)\n         [restores ~50 working memory facts, recent session events, shared\n          broadcast channel, and health banner — all in ~1500 tokens]\n         \n         Last session we were refactoring auth: decided to use HMAC signing\n         via KDF-derived per-agent subkeys. The prototype is in src/security/\n         hmac_chain.ts and 28/28 unit tests pass. Next step was wiring the\n         per-query SET LOCAL ROLE for RLS...\n```\n\nTell Claude to remember things as they happen:\n```\nYou: we settled on using pgvector over pinecone because we need local-first\n\nClaude: (calls zc_remember with importance=5)\n```\n\nEnd the session:\n```\nYou: wrap up please\n\nClaude: (calls zc_summarize_session)  \n        [persists structured summary; next session's zc_recall_context will surface it]\n```\n\n---\n\n## How It Compares\n\n### vs. `claude-mem` (21k+ stars)\n\n| Feature | claude-mem | SecureContext |\n|---|---|---|\n| Memory | AI-compressed summaries (lossy) | MemGPT importance-scored facts (structured, bounded) |\n| Security | None documented | HMAC chain + per-agent HKDF + RLS + sandbox |\n| Multi-agent | None | Work-stealing queue + dispatcher + broadcast channel |\n| Telemetry | None | Per-call cost/latency/token rows |\n| Learning loop | None | Outcome → failures.jsonl auto-feedback |\n| Audit trail | None | HMAC-chained, tamper-detectable |\n\n### vs. `context-mode` (the one SecureContext originally replaced)\n\n| Concern | context-mode | SecureContext |\n|---|---|---|\n| Env leaks to sandbox | ❌ Full env inherited | ✅ PATH-only env |\n| SSRF protection | ❌ | ✅ Multi-layer (protocol/DNS/redirect) |\n| Prompt injection via KB | ❌ | ✅ Pre-filter + trust labels on external content |\n| Self-modifiable hooks | ❌ | ✅ Hook paths + manifests verified |\n| Multi-agent | ❌ | ✅ Full harness |\n\n### vs. Claude's Native Context Management\n\n| Concern | Native | SecureContext |\n|---|---|---|\n| Survives session restart | ❌ starts fresh | ✅ `zc_recall_context` restores |\n| Handles 150k+ token context | Auto-compacts (lossy) | Bounded working memory + archival KB |\n| Cost per session (overhead) | ~$2–5 | ~$0.16 (with recall cache) |\n| Cross-session continuity | ❌ | ✅ summaries + facts persist |\n| Pool parallelism | ❌ single-session | ✅ N workers via `-WorkerCount` |\n\n---\n\n## Cost Model\n\n**Claude Sonnet 4.6 pricing**: $3/Mtok input, $15/Mtok output.  \n**Claude Opus 4.7 pricing**: $15/Mtok input, $75/Mtok output.\n\nTypical SecureContext-harness session with Opus orchestrator + Sonnet developers:\n\n| Operation | Count | Cost |\n|---|---:|---:|\n| `zc_recall_context` on Opus (first call) | 1 | ~$0.012 |\n| `zc_recall_context` on Opus (cache hit, 2nd+) | 2 | $0.00 |\n| `zc_choose_model` on Opus | 1 | $0.004 |\n| `zc_enqueue_task` × 4 on Opus | 4 | $0.024 |\n| `zc_broadcast` ASSIGN × 4 on Opus | 4 | $0.016 |\n| Developer work (Sonnet) | 6 | $0.014 |\n| `zc_summarize_session` on Opus | 1 | $0.003 |\n| **Total per user-task-cycle** | | **~$0.16** |\n\nSame flow without the harness (native re-paste + cold retries): **$2–5 per cycle**. That's where the 87% token-savings claim comes from.\n\n---\n\n## Testing \u0026 Verification\n\n```bash\nnpm test              # 645 unit + integration tests\nnpm run lint          # ESLint @typescript-eslint/no-floating-promises\nnpm run check:env     # L1 env-pinning linter — catches un-pinned critical vars\nnpm run check:env:test  # self-test of the env linter (14 cases)\nnpm run lint:test     # self-test of the floating-promises rule (5 cases)\n\nnode security-tests/run-all.mjs  # 60+ red-team attack IDs (RT-S0-* through RT-S4-*)\n```\n\nRed-team categories:\n- Sandbox escape + credential isolation (RT-S0-*)\n- SSRF + fetcher (RT-S1-*)\n- SQLite / KB injection (RT-S1-12 symlink escape)\n- Hook + prompt-injection-via-KB\n- Chain tamper-detection (RT-S1-15/16)\n- Per-agent HKDF forgery (RT-S2-01)\n- Reference Monitor + token binding (RT-S2-02/03/04/05/06)\n- Cross-agent RLS (RT-S3-05)\n- Work-stealing queue correctness (RT-S4-01 — 50 workers × 100 tasks no double-claim)\n- File-ownership overlap guard (RT-S4-05/06/07)\n\n---\n\n## Recent Changes\n\nSee [CHANGELOG.md](CHANGELOG.md) for the full history. Highlights from the last quarter:\n\n- **[v0.22.5](CHANGELOG.md#0225)** (2026-05-02) — **PreRead intercepts now visible in the dashboard.** Migration 17 adds `read_redirects_pg` (with a GENERATED `saved_tokens` column); the PreRead hook fires fire-and-forget telemetry on every L0/L1 redirect; the savings card surfaces a new \"📄 PreRead summary intercepts\" panel rolling those rows into the headline totals. Fixes the silent-savings problem where the system was saving ~95% on every Read and the dashboard couldn't see any of it.\n- **[v0.22.4](CHANGELOG.md#0224)** (2026-05-02) — Fix: `ZC_SUMMARY_REDIRECT` defaults to `1` in `start-agents.ps1` (orchestrator + worker launcher blocks). v0.22.2 had landed the redirect but the env var was conditional on operator's shell having it set, which it usually wasn't, so the redirect silently no-op'd in real-project sessions.\n- **[v0.22.3](CHANGELOG.md#0223)** (2026-05-02) — Hook fixes from first real-project use of v0.22.2: PreRead dedup now bypasses for `offset/limit` partial reads (was looping on chunked Reads of large files); PostBash hook stops emitting `decision:\"modify\"` (rejected by current PostToolUse hook schema) and archives silently instead.\n- **[v0.22.2](CHANGELOG.md#0222)** (2026-05-02) — **Agent Notebook Model enforced.** PreRead hook redirects Read of indexed files to the L0/L1 summary (~95% Read-token reduction); `zc_file_summary` auto-indexes on miss; per-agent namespacing (`zc_remember`/`zc_recall_context` default to `agent_id = ZC_AGENT_ID`, recall UNIONs private + shared \"default\" pool); skill-block dedup per `MCP_SESSION_ID`. Closes the gap between having semantic summaries and agents actually using them.\n- **[v0.22.1](CHANGELOG.md#0221)** (2026-05-01) — 3 bug fixes from v0.22.0 live E2E: `mutation_results_pg` mirror (dashboard couldn't see candidates in sqlite mode), `zc_mutation_approve` resolves to active skill version (was bumping from archived parent → reverting progress), `zc_record_skill_outcome` reports actual L1 outcome (was hardcoded based on env-var detection).\n- **[v0.22.0](CHANGELOG.md#0220)** (2026-05-01) — **Full skill attribution + operator audit log.** PG migration 16 adds `skill_runs_pg.agent_id`; new `skill_run_tool_calls_pg` correlation table; new `mutation_reviews_pg` operator audit log; `tool_calls_pg.skill_id` finally populated end-to-end. API container runs PG migrations on startup. Verified live with 5 distinct roles + Playwright-driven dashboard approval.\n- **[v0.21.0](CHANGELOG.md#0210)** (2026-05-01) — **Skill enforcement levers (#1, #2, #4).** Inject \"## YOUR SKILLS\" block at agent spawn (`generate-role-skill-block.mjs`); `zc_recall_context` auto-injects applicable skills via new `?role=` query param; MERGE-time skill-record mandate appended to every role prompt. Lever #5 (hard PreTool block) deliberately designed-but-unshipped — see `docs/SKILL_ENFORCEMENT.md`.\n- **[v0.20.1](CHANGELOG.md#0201)** (2026-05-01) — **First fully verified self-improvement cycle live.** 4 bugs found and fixed: L1 hook PG fallback for skill lookup, `ZC_L1_MUTATION_ENABLED` propagation to per-agent launchers, dispatcher PG-creds propagation, skill auto-importer using HMAC-keyed hash (was plain SHA256). Live evidence: REJECT → outcome → mutator pool → 5 candidates → operator approve → `developer-debugging-methodology@1.1@global` promoted.\n- **[v0.20.0](CHANGELOG.md#0200)** (2026-04-30) — **Sprint 4 + closes every 🔴 high item from v0.19.0.** Auto-import `skills/*.skill.md` into `skills_pg` (25 skills imported on first run); LLM \"Generate skill body from rejection cluster\" (Sonnet default, Ollama fallback); context-budget tracking + `zc_context_status`; rolling compaction (`zc_compact_window`); reranker + HyDE + multi-hop retrieval modes for `zc_search`; vitest test isolation via dedicated `securecontext_test` DB. 803 unit tests passing; 14/14 live agent E2E.\n- **[v0.19.0](CHANGELOG.md#0190)** (2026-04-30) — **Sprint 2.10: closes the agent self-improvement loop.** Role-to-skill extractor (`scripts/extract-skills-from-roles.mjs`); orchestrator-REJECT outcome resolver (writes `outcomes_pg` + `learnings/failures.jsonl` + flags the failed `skill_run` for the mutator); skill-candidate detector + `skill_candidates_pg` (PG migration 15) — clusters repeated rejections into queued skill candidates the operator can author against.\n- **[v0.18.0](CHANGELOG.md#0180)** (2026-04-29) — **Sprint 2 baseline**: skill mutation engine. Versioned hash-protected skills, synthetic-fixture replay harness, pluggable mutators (`local-mock`, `realtime-sonnet`, `batch-sonnet`), composite outcome scoring, atomic promotion, cross-project promotion candidates. 7 new MCP tools, 132 new tests, 786/786 passing. Postgres mirror for multi-machine consistency. agentskills.io interop.\n- **[v0.17.2](CHANGELOG.md#0172)** (2026-04-20) — L1 env-pinning linter + L3 no-floating-promises ESLint + L4 outcome → failures.jsonl auto-feedback. Closes 3 architectural-bug classes pre-Sprint-2.\n- **[v0.17.1](CHANGELOG.md#0171)** — Agent-idle fixes (claim-drain, Stop-hook queue-drain, dispatcher wake-nudge) + 60s recall cache + Tier 1+2 pricing correctness.\n- **[v0.17.0](CHANGELOG.md#0170)** — Postgres work-stealing queue (`FOR UPDATE SKIP LOCKED`) + complexity-based model router + file-ownership overlap guard + `-WorkerCount N` multi-worker pools.\n- **[v0.16.0](CHANGELOG.md#0160)** — Postgres backend for telemetry + outcomes + learnings; Tier 3 security (per-query `SET LOCAL ROLE` + Row-Level Security).\n- **[v0.15.0](CHANGELOG.md#0150)** — Structured ASSIGN schema (`file_ownership_exclusive`, `complexity_estimate`, `acceptance_criteria`, etc.) + MAC classification on outcomes.\n- **[v0.14.0](CHANGELOG.md#0140)** — Provenance tagging (EXTRACTED / INFERRED / AMBIGUOUS / UNKNOWN) + AST code extractor + Louvain community detection.\n- **[v0.13.0](CHANGELOG.md#0130)** — graphify integration (zc_graph_query / path / neighbors) + auto-indexed graph reports.\n- **[v0.12.0](CHANGELOG.md#0120)** — ChainedTable abstraction + per-agent HKDF subkey (Tier 1 security fix).\n- **[v0.11.0](CHANGELOG.md#0110)** — Telemetry foundation (tool_calls hash chain + outcomes pipeline + learnings mirror).\n\nFor v0.6–v0.10 history see [CHANGELOG.md](CHANGELOG.md).\n\n---\n\n## Contributing\n\nIssues and PRs welcome. Before opening a PR:\n\n```bash\nnpm run build\nnpm test                  # must be 786/786 (or updated)\nnpm run lint              # 0 errors\nnpm run check:env         # 0 unclassified\nnode security-tests/run-all.mjs  # all red-team IDs pass\n```\n\nArchitectural decisions are recorded in `C:\\Users\\Amit\\AI_projects\\.harness-planning\\ARCHITECTURAL_LESSONS.md` (local-only — not in the repo to keep internal strategy out of public history). Consult before proposing changes that touch the security foundation, telemetry pipeline, or work-stealing queue.\n\n---\n\n## License\n\nMIT — see [LICENSE](LICENSE). Built for self-hostable, auditable agent infrastructure. No telemetry-back-to-vendor. No cloud dependencies beyond what you configure yourself.\n\n---\n\n**Companion project**: [A2A_dispatcher](https://github.com/iampantherr/A2A_dispatcher) — multi-agent orchestration layer that spawns / routes / retires worker pools against this harness.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiampantherr%2Fsecurecontext","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fiampantherr%2Fsecurecontext","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiampantherr%2Fsecurecontext/lists"}