@seanhogg/builderforce-memory-mcp 2026.6.30 → 2026.6.34

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.
@@ -1,8 +1,22 @@
1
1
  /**
2
2
  * HTTP transport — the multi-tenant / networked path (builderforce.ai hosting,
3
- * remote claws). Stateless Streamable HTTP: one short-lived McpServer +
3
+ * remote hosts). Stateless Streamable HTTP: one short-lived McpServer +
4
4
  * transport per request, so it scales horizontally with no sticky sessions.
5
- * Bearer-token auth gates every request.
5
+ *
6
+ * Auth model (pick one, in precedence order):
7
+ * • `tenants` — a `{ token: backend }` map. The bearer token selects the
8
+ * tenant's OWN backend (namespace isolation); an unknown token is 401. This
9
+ * is the production multi-tenant mode — one token can never read another
10
+ * tenant's facts.
11
+ * • `resolveBackend` — a function `(token) => backend` for dynamic tenant
12
+ * resolution (e.g. a gateway lookup).
13
+ * • `authToken` — a single shared secret guarding the one positional backend
14
+ * (single-tenant / reference hosting).
15
+ * • none — open, only valid behind a trusted gateway that already authed.
16
+ *
17
+ * Token comparison is constant-time (hash + timingSafeEqual / hash-keyed lookup),
18
+ * and an optional fixed-window rate limit (per tenant, or per client IP when
19
+ * unauthenticated) caps abuse.
6
20
  *
7
21
  * Consumed from the Claude Agent SDK as:
8
22
  * mcpServers: {
@@ -15,16 +29,36 @@ import type { MemoryBackend } from "../backend.js";
15
29
  import { type McpServerOptions } from "./mcp-server.js";
16
30
  export interface HttpHandlerOptions extends McpServerOptions {
17
31
  /**
18
- * Shared secret required in `Authorization: Bearer <token>`. When set, every
19
- * request without a matching token is rejected 401. Omit only behind a trusted
20
- * gateway that has already authenticated the caller.
32
+ * Shared secret required in `Authorization: Bearer <token>` for the single
33
+ * positional backend. Every request without a matching token is rejected 401.
34
+ * Omit only behind a trusted gateway that has already authenticated the caller.
21
35
  */
22
36
  authToken?: string;
37
+ /**
38
+ * Multi-tenant map: bearer token → that tenant's backend. When set, the token
39
+ * selects the backend (namespace isolation) and the positional `backend` is
40
+ * only used as a fallback when no token-auth modes match. Lookups are keyed by
41
+ * token hash, never the raw token.
42
+ */
43
+ tenants?: Record<string, MemoryBackend>;
44
+ /**
45
+ * Dynamic tenant resolver: `(token) => backend | undefined`. Used when tenants
46
+ * live in an external store. Returning undefined → 401.
47
+ */
48
+ resolveBackend?: (token: string) => MemoryBackend | undefined | Promise<MemoryBackend | undefined>;
49
+ /** Fixed-window rate limit applied per tenant (or per client IP if open). */
50
+ rateLimit?: {
51
+ windowMs: number;
52
+ max: number;
53
+ };
54
+ /** Injectable clock (ms) for deterministic rate-limit tests. */
55
+ now?: () => number;
23
56
  }
24
57
  /**
25
58
  * Returns a `(req, res) => Promise<void>` handler you mount on any Node HTTP
26
- * server (or Express). Per request it spins up a stateless MCP server bound to
27
- * `backend`, handles the MCP exchange, and tears down on response close.
59
+ * server (or Express). Per request it authenticates, resolves the tenant
60
+ * backend, rate-limits, spins up a stateless MCP server bound to that backend,
61
+ * handles the MCP exchange, and tears down on response close.
28
62
  */
29
63
  export declare function createMemoryHttpHandler(backend: MemoryBackend, opts?: HttpHandlerOptions): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
30
64
  //# sourceMappingURL=http.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/transports/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExE,MAAM,WAAW,kBAAmB,SAAQ,gBAAgB;IACxD;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAOD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACnC,OAAO,EAAE,aAAa,EACtB,IAAI,GAAE,kBAAuB,GAC9B,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAuB9D"}
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/transports/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAGxE,MAAM,WAAW,kBAAmB,SAAQ,gBAAgB;IACxD;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxC;;;OAGG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,aAAa,GAAG,SAAS,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;IACnG,6EAA6E;IAC7E,SAAS,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9C,gEAAgE;IAChE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AAcD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACnC,OAAO,EAAE,aAAa,EACtB,IAAI,GAAE,kBAAuB,GAC9B,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAyD9D"}
@@ -1,8 +1,22 @@
1
1
  /**
2
2
  * HTTP transport — the multi-tenant / networked path (builderforce.ai hosting,
3
- * remote claws). Stateless Streamable HTTP: one short-lived McpServer +
3
+ * remote hosts). Stateless Streamable HTTP: one short-lived McpServer +
4
4
  * transport per request, so it scales horizontally with no sticky sessions.
5
- * Bearer-token auth gates every request.
5
+ *
6
+ * Auth model (pick one, in precedence order):
7
+ * • `tenants` — a `{ token: backend }` map. The bearer token selects the
8
+ * tenant's OWN backend (namespace isolation); an unknown token is 401. This
9
+ * is the production multi-tenant mode — one token can never read another
10
+ * tenant's facts.
11
+ * • `resolveBackend` — a function `(token) => backend` for dynamic tenant
12
+ * resolution (e.g. a gateway lookup).
13
+ * • `authToken` — a single shared secret guarding the one positional backend
14
+ * (single-tenant / reference hosting).
15
+ * • none — open, only valid behind a trusted gateway that already authed.
16
+ *
17
+ * Token comparison is constant-time (hash + timingSafeEqual / hash-keyed lookup),
18
+ * and an optional fixed-window rate limit (per tenant, or per client IP when
19
+ * unauthenticated) caps abuse.
6
20
  *
7
21
  * Consumed from the Claude Agent SDK as:
8
22
  * mcpServers: {
@@ -12,25 +26,78 @@
12
26
  */
13
27
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
14
28
  import { buildMcpServer } from "./mcp-server.js";
15
- function unauthorized(res) {
16
- res.writeHead(401, { "content-type": "application/json" });
17
- res.end(JSON.stringify({ error: "unauthorized" }));
29
+ import { RateLimiter, bearerToken, buildTenantIndex, hashToken, timingSafeEqualStr } from "./auth.js";
30
+ function send(res, status, body) {
31
+ res.writeHead(status, { "content-type": "application/json" });
32
+ res.end(JSON.stringify(body));
33
+ }
34
+ /** First-hop client IP, for rate-limiting unauthenticated callers. */
35
+ function clientIp(req) {
36
+ const fwd = req.headers["x-forwarded-for"];
37
+ const first = Array.isArray(fwd) ? fwd[0] : fwd?.split(",")[0];
38
+ return (first?.trim() || req.socket?.remoteAddress || "unknown");
18
39
  }
19
40
  /**
20
41
  * Returns a `(req, res) => Promise<void>` handler you mount on any Node HTTP
21
- * server (or Express). Per request it spins up a stateless MCP server bound to
22
- * `backend`, handles the MCP exchange, and tears down on response close.
42
+ * server (or Express). Per request it authenticates, resolves the tenant
43
+ * backend, rate-limits, spins up a stateless MCP server bound to that backend,
44
+ * handles the MCP exchange, and tears down on response close.
23
45
  */
24
46
  export function createMemoryHttpHandler(backend, opts = {}) {
47
+ const tenantIndex = opts.tenants ? buildTenantIndex(opts.tenants) : undefined;
48
+ const limiter = opts.rateLimit
49
+ ? new RateLimiter(opts.rateLimit.windowMs, opts.rateLimit.max, opts.now ?? (() => Date.now()))
50
+ : undefined;
25
51
  return async (req, res) => {
26
- if (opts.authToken) {
27
- const header = req.headers["authorization"];
28
- if (header !== `Bearer ${opts.authToken}`) {
29
- unauthorized(res);
52
+ const token = bearerToken(req.headers["authorization"]);
53
+ // ── Resolve the per-request backend + a rate-limit key ────────────────
54
+ let resolved;
55
+ let rateKey;
56
+ if (tenantIndex) {
57
+ // Multi-tenant: token → that tenant's backend (hash-keyed lookup).
58
+ if (!token) {
59
+ send(res, 401, { error: "unauthorized" });
60
+ return;
61
+ }
62
+ resolved = tenantIndex.get(hashToken(token));
63
+ if (!resolved) {
64
+ send(res, 401, { error: "unauthorized" });
65
+ return;
66
+ }
67
+ rateKey = `t:${hashToken(token)}`;
68
+ }
69
+ else if (opts.resolveBackend) {
70
+ if (!token) {
71
+ send(res, 401, { error: "unauthorized" });
30
72
  return;
31
73
  }
74
+ resolved = await opts.resolveBackend(token);
75
+ if (!resolved) {
76
+ send(res, 401, { error: "unauthorized" });
77
+ return;
78
+ }
79
+ rateKey = `t:${hashToken(token)}`;
80
+ }
81
+ else if (opts.authToken) {
82
+ // Single shared secret, constant-time compare.
83
+ if (!token || !timingSafeEqualStr(token, opts.authToken)) {
84
+ send(res, 401, { error: "unauthorized" });
85
+ return;
86
+ }
87
+ resolved = backend;
88
+ rateKey = `t:${hashToken(token)}`;
89
+ }
90
+ else {
91
+ // Open (trusted gateway): rate-limit by client IP.
92
+ resolved = backend;
93
+ rateKey = `ip:${clientIp(req)}`;
94
+ }
95
+ // ── Rate limit ────────────────────────────────────────────────────────
96
+ if (limiter && !limiter.check(rateKey)) {
97
+ send(res, 429, { error: "rate_limited" });
98
+ return;
32
99
  }
33
- const server = buildMcpServer(backend, opts);
100
+ const server = buildMcpServer(resolved, opts);
34
101
  // Stateless: no session id generator → a fresh transport per request.
35
102
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
36
103
  res.on("close", () => {
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/transports/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AAEnG,OAAO,EAAE,cAAc,EAAyB,MAAM,iBAAiB,CAAC;AAWxE,SAAS,YAAY,CAAC,GAAmB;IACrC,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAC3D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;AACvD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACnC,OAAsB,EACtB,OAA2B,EAAE;IAE7B,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QACtB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YAC5C,IAAI,MAAM,KAAK,UAAU,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;gBACxC,YAAY,CAAC,GAAG,CAAC,CAAC;gBAClB,OAAO;YACX,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,cAAc,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC7C,sEAAsE;QACtE,MAAM,SAAS,GAAG,IAAI,6BAA6B,CAAC,EAAE,kBAAkB,EAAE,SAAS,EAAE,CAAC,CAAC;QAEvF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACjB,KAAK,SAAS,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EAAE,kBAAkB,EAAE,SAAS,EAAE,CAAC,CAAC;QAEvF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACjB,KAAK,SAAS,CAAC,KAAK,EAAE,CAAC;YACvB,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,CAAC,CAAC,CAAC;QAEH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAChC,8EAA8E;QAC9E,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAC5C,CAAC,CAAC;AACN,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanhogg/builderforce-memory-mcp",
3
- "version": "2026.6.30",
3
+ "version": "2026.6.34",
4
4
  "description": "BuilderForce Agent Memory — MCP transport. Exposes @seanhogg/builderforce-memory to any MCP client (Claude Agent SDK in-process, stdio, or HTTP) over a pluggable MemoryBackend, with token-saving fetch-on-demand recall.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -73,7 +73,7 @@
73
73
  "fake-indexeddb": "^6.0.0",
74
74
  "typescript": "^6.0.3",
75
75
  "@typescript/native-preview": "7.0.0-dev.20260627.2",
76
- "@seanhogg/builderforce-memory": "2026.6.30"
76
+ "@seanhogg/builderforce-memory": "2026.6.34"
77
77
  },
78
78
  "engines": {
79
79
  "node": ">=18.0.0"
@@ -83,7 +83,7 @@
83
83
  },
84
84
  "scripts": {
85
85
  "build": "tsc",
86
- "test": "tsc && node --test tests/install.test.mjs tests/tools.test.mjs",
86
+ "test": "tsc && node --test tests/install.test.mjs tests/tools.test.mjs tests/http.test.mjs",
87
87
  "lint": "eslint src/",
88
88
  "typecheck:native": "tsgo --noEmit"
89
89
  }
@@ -81,7 +81,7 @@ export interface LocalBackendOptions {
81
81
  /**
82
82
  * Optional SSMRuntime for embedding-based recall. Omit for lexical (Jaccard)
83
83
  * recall. In the agent-runtime, pass `ssmMemoryService.runtime` here to reuse
84
- * the already-loaded hippocampus instead of standing up a second model.
84
+ * the already-loaded Evermind runtime instead of standing up a second model.
85
85
  */
86
86
  runtime?: unknown;
87
87
  /**
@@ -18,8 +18,10 @@
18
18
 
19
19
  import os from "node:os";
20
20
  import path from "node:path";
21
+ import nodeFs from "node:fs";
21
22
  import { HOSTS } from "../install/hosts.js";
22
23
  import { installMemoryServer, type HostSelector } from "../install/install.js";
24
+ import { installClaudeCombo } from "../install/claude-hooks.js";
23
25
 
24
26
  function argValue(name: string): string | undefined {
25
27
  const hit = process.argv.find((a) => a.startsWith(`--${name}=`));
@@ -83,6 +85,26 @@ for (const r of results) {
83
85
  if (r.status === "installed" || r.status === "updated") wrote += 1;
84
86
  }
85
87
 
88
+ // ── Claude Code memory combo (hooks + companion skill) ───────────────────────
89
+ // Registering the server above gives Claude Code the TOOLS; this adds the
90
+ // self-driving behaviour (SessionStart digest, contextual recall, autonomous Stop
91
+ // capture). Only for Claude Code, only when present, and skippable via --no-hooks.
92
+ const claudeResult = results.find((r) => r.host === "claude-code");
93
+ const claudePresent = claudeResult && claudeResult.status !== "unsupported" && claudeResult.status !== "error";
94
+ if (claudePresent && !hasFlag("no-hooks")) {
95
+ try {
96
+ const combo = installClaudeCombo({
97
+ fs: nodeFs,
98
+ claudeDir: path.join(os.homedir(), ".claude"),
99
+ memoryFile,
100
+ });
101
+ const what = combo.addedHooks.length ? `added ${combo.addedHooks.join(", ")}` : "already current";
102
+ process.stdout.write(`✓ Claude Code memory combo: hooks ${what}; recall + autonomous capture wired\n`);
103
+ } catch (err) {
104
+ process.stderr.write(`✗ Claude Code hooks: ${String((err as Error).message ?? err)}\n`);
105
+ }
106
+ }
107
+
86
108
  if (results.length === 0) {
87
109
  process.stdout.write(
88
110
  "No MCP hosts detected. Pass --host=all to write configs anyway, or --host=cursor (etc.).\n",
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ export { runStdio } from "./transports/stdio.js";
29
29
 
30
30
  export { createMemoryHttpHandler } from "./transports/http.js";
31
31
  export type { HttpHandlerOptions } from "./transports/http.js";
32
+ export { hashToken, timingSafeEqualStr, buildTenantIndex, bearerToken, RateLimiter } from "./transports/auth.js";
32
33
 
33
34
  // ── Multi-host installer (wire the stdio server into any MCP-capable agent) ───
34
35
  export { buildServerSpec, MCP_PACKAGE, MCP_BIN, RUNTIME_PEERS } from "./install/server-spec.js";
@@ -37,3 +38,7 @@ export { installMemoryServer } from "./install/install.js";
37
38
  export type { InstallOptions, InstallResult, InstallStatus, HostSelector, FsLike } from "./install/install.js";
38
39
  export { HOSTS, SERVER_KEY, findHost } from "./install/hosts.js";
39
40
  export type { HostAdapter, HostEnv, ConfigFormat } from "./install/hosts.js";
41
+ // Claude Code "memory combo" — hooks (SessionStart/PreCompact/UserPromptSubmit/Stop)
42
+ // + companion skill that make memory self-driving (contextual recall + autonomous capture).
43
+ export { installClaudeCombo, bfmemHookSource, companionSkillMd, claudeComboPaths } from "./install/claude-hooks.js";
44
+ export type { ClaudeComboPaths } from "./install/claude-hooks.js";
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Claude Code "memory combo" — the hooks + companion skill half of the install.
3
+ *
4
+ * Registering the MCP server (install.ts) gives Claude Code the memory TOOLS.
5
+ * This module adds the behaviour that makes memory SELF-DRIVING rather than
6
+ * advisory, so the agent doesn't have to be reminded to use it:
7
+ *
8
+ * SessionStart → inject a digest of the top durable memories.
9
+ * PreCompact → flush durable learnings before the window is summarised.
10
+ * UserPromptSubmit → CONTEXTUAL recall: score memories against the prompt and
11
+ * inject the relevant ones (so a stored fact is retrieved at
12
+ * the decision point, not just at session start).
13
+ * Stop → AUTONOMOUS capture: detect a durable instruction/correction
14
+ * in the user's last message and, if it wasn't consolidated
15
+ * this turn, BLOCK the stop with a directive to memory_remember
16
+ * (capture flows through the MCP write path — never racing the
17
+ * server's snapshot).
18
+ *
19
+ * All four point at one generated, dependency-free hook script (DRY). The combo
20
+ * is idempotent and backup-safe, matching install.ts.
21
+ */
22
+
23
+ import nodePath from "node:path";
24
+ import type { FsLike } from "./install.js";
25
+
26
+ /** The single hook script, four modes. `memoryFile` is the JSON snapshot path. */
27
+ export function bfmemHookSource(memoryFile: string): string {
28
+ return `#!/usr/bin/env node
29
+ /**
30
+ * builderforce-memory hook — generated by builderforce-memory-install. Dependency-free:
31
+ * reads only the JSON snapshot, never stands up the MCP server.
32
+ * --session SessionStart: inject a small digest of durable memories.
33
+ * --precompact PreCompact: remind to flush learnings before summarisation.
34
+ * --recall UserPromptSubmit: contextual recall — inject memories relevant to the prompt.
35
+ * --capture Stop: autonomous consolidation — block the stop until a detected
36
+ * durable correction is persisted via memory_remember.
37
+ */
38
+ import fs from "node:fs";
39
+
40
+ const FILE = ${JSON.stringify(memoryFile)};
41
+ const mode = process.argv[2] || "--session";
42
+
43
+ function readStdin() {
44
+ try { return fs.readFileSync(0, "utf8"); } catch { return ""; }
45
+ }
46
+ function loadEntries() {
47
+ try { const p = JSON.parse(fs.readFileSync(FILE, "utf8")); return Array.isArray(p) ? p : []; }
48
+ catch { return []; }
49
+ }
50
+ function tokens(s) {
51
+ return String(s || "").toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length >= 3);
52
+ }
53
+
54
+ if (mode === "--precompact") {
55
+ process.stdout.write(
56
+ "[builderforce-memory] Context is about to be compacted. Persist any durable learnings from this session — decisions, fixes, project facts, user preferences — by calling memory_remember with concise one-line facts. Recall them later with memory_recall instead of re-reading files.",
57
+ );
58
+ process.exit(0);
59
+ }
60
+
61
+ if (mode === "--recall") {
62
+ let prompt = "";
63
+ try { const j = JSON.parse(readStdin() || "{}"); prompt = typeof j.prompt === "string" ? j.prompt : ""; } catch { /* no input */ }
64
+ if (!prompt) process.exit(0);
65
+ const entries = loadEntries();
66
+ if (entries.length === 0) process.exit(0);
67
+ const q = new Set(tokens(prompt));
68
+ if (q.size === 0) process.exit(0);
69
+ const scored = entries
70
+ .map((e) => {
71
+ const hay = new Set(tokens([e.key, e.content, (e.tags || []).join(" ")].join(" ")));
72
+ let score = 0;
73
+ for (const t of q) if (hay.has(t)) score++;
74
+ return { e, score };
75
+ })
76
+ .filter((x) => x.score >= 2)
77
+ .sort((a, b) => b.score - a.score)
78
+ .slice(0, 3);
79
+ if (scored.length === 0) process.exit(0);
80
+ const lines = scored.map((x) => "• " + x.e.key + ": " + String(x.e.content || "").slice(0, 240)).join("\\n");
81
+ process.stdout.write(
82
+ "[builderforce-memory] Relevant stored memories for this request — use these instead of re-deriving or re-reading:\\n" + lines,
83
+ );
84
+ process.exit(0);
85
+ }
86
+
87
+ if (mode === "--capture") {
88
+ let input = {};
89
+ try { input = JSON.parse(readStdin() || "{}"); } catch { /* no input */ }
90
+ if (input.stop_hook_active) process.exit(0);
91
+ const tpath = input.transcript_path;
92
+ if (!tpath || typeof tpath !== "string") process.exit(0);
93
+
94
+ let raw = "";
95
+ try {
96
+ const stat = fs.statSync(tpath);
97
+ const want = Math.min(stat.size, 400000);
98
+ const fd = fs.openSync(tpath, "r");
99
+ const buf = Buffer.alloc(want);
100
+ fs.readSync(fd, buf, 0, want, stat.size - want);
101
+ fs.closeSync(fd);
102
+ raw = buf.toString("utf8");
103
+ } catch { process.exit(0); }
104
+
105
+ const msgs = [];
106
+ for (const ln of raw.split("\\n")) { if (ln.trim()) { try { msgs.push(JSON.parse(ln)); } catch { /* partial */ } } }
107
+
108
+ let lastUserText = "";
109
+ let rememberedThisTurn = false;
110
+ for (let i = msgs.length - 1; i >= 0; i--) {
111
+ const m = msgs[i] || {};
112
+ const inner = m.message || m;
113
+ const role = inner.role;
114
+ const content = inner.content;
115
+ if (role === "assistant" && !lastUserText) {
116
+ if (Array.isArray(content)) for (const c of content) {
117
+ if (c && c.type === "tool_use" && typeof c.name === "string" && c.name.includes("memory_remember")) rememberedThisTurn = true;
118
+ }
119
+ }
120
+ if (role === "user" && !lastUserText) {
121
+ let txt = "";
122
+ if (typeof content === "string") txt = content;
123
+ else if (Array.isArray(content)) for (const c of content) {
124
+ if (typeof c === "string") txt += c + " ";
125
+ else if (c && c.type === "text" && typeof c.text === "string") txt += c.text + " ";
126
+ }
127
+ if (txt.trim()) lastUserText = txt;
128
+ }
129
+ }
130
+ if (!lastUserText || rememberedThisTurn) process.exit(0);
131
+
132
+ const lower = lastUserText.toLowerCase();
133
+ const SIGNALS = [
134
+ "you have to", "you should", "you need to", "you must", "from now on", "going forward",
135
+ "always ", "never ", "make sure", "remember to", "don't forget", "do not forget",
136
+ "i keep telling", "i already told", "shouldn't have to", "keep having to remind",
137
+ "you forgot", "you keep", "that's wrong", "you're wrong", "this is wrong", "stop ",
138
+ ];
139
+ const hit = SIGNALS.find((s) => lower.includes(s));
140
+ if (!hit) process.exit(0);
141
+
142
+ const snippet = lastUserText.trim().slice(0, 240);
143
+ const reason =
144
+ "[builderforce-memory] A durable instruction/correction was detected in the user's last message and you did NOT consolidate it this turn. " +
145
+ "Before stopping, call memory_remember with a concise, stable-keyed fact capturing it (reuse the same key to replace a superseded one, or memory_forget it). " +
146
+ "User said: '" + snippet + "'. If it is genuinely not durable (a one-off, or already stored), briefly say why and then stop.";
147
+ process.stdout.write(JSON.stringify({ decision: "block", reason }));
148
+ process.exit(0);
149
+ }
150
+
151
+ const entries = loadEntries();
152
+ if (entries.length === 0) {
153
+ process.stdout.write(
154
+ "[builderforce-memory] Active (memory empty). Store durable facts with memory_remember and retrieve them with memory_recall instead of re-reading files or chat history — that is how token usage stays low.",
155
+ );
156
+ process.exit(0);
157
+ }
158
+ const top = entries
159
+ .map((e) => ({ key: e.key, content: String(e.content ?? ""), importance: typeof e.importance === "number" ? e.importance : 0.5 }))
160
+ .sort((a, b) => b.importance - a.importance)
161
+ .slice(0, 8)
162
+ .map((e) => "• " + e.key + ": " + e.content.slice(0, 200))
163
+ .join("\\n");
164
+ process.stdout.write(
165
+ "[builderforce-memory] Active — token-saving memory loaded. Before re-reading files or history, call memory_recall. Store durable facts with memory_remember.\\nTop memories:\\n" + top,
166
+ );
167
+ `;
168
+ }
169
+
170
+ /** The companion skill doc that teaches the recall/remember discipline. */
171
+ export function companionSkillMd(): string {
172
+ return `---
173
+ name: builderforce-memory
174
+ description: Token-saving persistent memory. Recall durable facts (decisions, fixes, project context, user preferences) instead of re-reading files or chat history, and remember new durable facts as you learn them.
175
+ ---
176
+
177
+ # builderforce-memory — the conductor
178
+
179
+ Persistent memory backed by the \`builderforce-memory\` MCP server. The point is
180
+ **token reduction**: pull a small relevant slice from memory instead of re-reading
181
+ the full file/history. The install also wires hooks so this is largely automatic:
182
+ the SessionStart digest, contextual recall on each prompt, and an autonomous Stop
183
+ capture that won't let a durable correction go unrecorded.
184
+
185
+ ## Tools
186
+ - \`memory_recall(query, [k])\` — top-K relevant memories. First move on a task.
187
+ - \`memory_get(key)\` — exact lookup by key.
188
+ - \`memory_recall_by_tag(tag)\` — everything under a tag.
189
+ - \`memory_remember(key, content, [tags], [importance])\` — store ONE durable fact.
190
+ - \`memory_forget(key)\` — drop a superseded fact.
191
+
192
+ ## Discipline
193
+ Reuse a stable key to REPLACE a fact (write-through), don't append duplicates.
194
+ Store decisions, non-obvious fixes, project constraints, user preferences — one
195
+ tight line each. Not things git already records or one-off turn details.
196
+ `;
197
+ }
198
+
199
+ /** Files/paths the combo manages, derived from the Claude config dir (~/.claude). */
200
+ export interface ClaudeComboPaths {
201
+ claudeDir: string;
202
+ settingsFile: string;
203
+ hookScript: string;
204
+ companionSkill: string;
205
+ }
206
+
207
+ export function claudeComboPaths(claudeDir: string): ClaudeComboPaths {
208
+ return {
209
+ claudeDir,
210
+ settingsFile: nodePath.join(claudeDir, "settings.json"),
211
+ hookScript: nodePath.join(claudeDir, "builderforce-memory", "bfmem-hook.mjs"),
212
+ companionSkill: nodePath.join(claudeDir, "skills", "builderforce-memory", "SKILL.md"),
213
+ };
214
+ }
215
+
216
+ const HOOK_EVENTS = [
217
+ { event: "SessionStart", mode: "--session" },
218
+ { event: "PreCompact", mode: "--precompact" },
219
+ { event: "UserPromptSubmit", mode: "--recall" },
220
+ { event: "Stop", mode: "--capture" },
221
+ ] as const;
222
+
223
+ /**
224
+ * Write the hook script + companion skill and register all four hooks in
225
+ * settings.json. Idempotent (skips a hook command already present) and
226
+ * backup-safe (.bak before overwriting settings). Returns the events it added.
227
+ */
228
+ export function installClaudeCombo(opts: {
229
+ fs: FsLike;
230
+ claudeDir: string;
231
+ memoryFile: string;
232
+ }): { hookScript: string; addedHooks: string[]; settingsFile: string } {
233
+ const { fs, memoryFile } = opts;
234
+ const paths = claudeComboPaths(opts.claudeDir);
235
+
236
+ // 1) Hook script.
237
+ const hookDir = nodePath.dirname(paths.hookScript);
238
+ if (!fs.existsSync(hookDir)) fs.mkdirSync(hookDir, { recursive: true });
239
+ fs.writeFileSync(paths.hookScript, bfmemHookSource(memoryFile));
240
+
241
+ // 2) Companion skill.
242
+ const skillDir = nodePath.dirname(paths.companionSkill);
243
+ if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
244
+ fs.writeFileSync(paths.companionSkill, companionSkillMd());
245
+
246
+ // 3) Merge hooks into settings.json.
247
+ let settings: Record<string, unknown> = {};
248
+ if (fs.existsSync(paths.settingsFile)) {
249
+ try { settings = JSON.parse(fs.readFileSync(paths.settingsFile, "utf8")) as Record<string, unknown>; }
250
+ catch { throw new Error("existing settings.json is not valid JSON"); }
251
+ fs.copyFileSync(paths.settingsFile, `${paths.settingsFile}.bak`);
252
+ }
253
+ const hooks = (settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {}) as Record<string, unknown>;
254
+ const added: string[] = [];
255
+ for (const { event, mode } of HOOK_EVENTS) {
256
+ const command = `node "${paths.hookScript}" ${mode}`;
257
+ const arr = (Array.isArray(hooks[event]) ? hooks[event] : (hooks[event] = [])) as Array<{ hooks?: Array<{ type?: string; command?: string }> }>;
258
+ const exists = arr.some((g) => (g.hooks || []).some((h) => h.command === command));
259
+ if (!exists) { arr.push({ hooks: [{ type: "command", command }] }); added.push(event); }
260
+ }
261
+ settings.hooks = hooks;
262
+ const settingsDir = nodePath.dirname(paths.settingsFile);
263
+ if (!fs.existsSync(settingsDir)) fs.mkdirSync(settingsDir, { recursive: true });
264
+ fs.writeFileSync(paths.settingsFile, `${JSON.stringify(settings, null, 2)}\n`);
265
+
266
+ return { hookScript: paths.hookScript, addedHooks: added, settingsFile: paths.settingsFile };
267
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * transports/auth.ts — auth + rate-limiting primitives for the HTTP transport.
3
+ *
4
+ * The networked MCP surface is multi-tenant: one bearer token must map to ONE
5
+ * tenant's memory namespace, the comparison must not leak the secret through a
6
+ * timing side channel, and a noisy or hostile caller must not be able to hammer
7
+ * the server. These helpers provide exactly those three pieces, dependency-free
8
+ * (node:crypto only).
9
+ */
10
+
11
+ import { createHash, timingSafeEqual } from "node:crypto";
12
+
13
+ /** SHA-256 hex digest of a token — the stable, non-reversible lookup key. */
14
+ export function hashToken(token: string): string {
15
+ return createHash("sha256").update(token, "utf8").digest("hex");
16
+ }
17
+
18
+ /**
19
+ * Constant-time string equality. Hashes both sides to fixed-length digests
20
+ * first, so neither the comparison nor the input length leaks the secret.
21
+ */
22
+ export function timingSafeEqualStr(a: string, b: string): boolean {
23
+ const ha = createHash("sha256").update(a, "utf8").digest();
24
+ const hb = createHash("sha256").update(b, "utf8").digest();
25
+ return timingSafeEqual(ha, hb);
26
+ }
27
+
28
+ /**
29
+ * Build a tenant lookup keyed by token HASH (never the raw token). Resolving a
30
+ * presented token is a hash + map lookup — no per-character secret comparison,
31
+ * so there is no early-return timing channel on the token value.
32
+ */
33
+ export function buildTenantIndex<B>(tenants: Record<string, B>): Map<string, B> {
34
+ const index = new Map<string, B>();
35
+ for (const [token, backend] of Object.entries(tenants)) {
36
+ if (token) index.set(hashToken(token), backend);
37
+ }
38
+ return index;
39
+ }
40
+
41
+ /** Fixed-window rate limiter. Memory-bounded by pruning expired windows. */
42
+ export class RateLimiter {
43
+ private readonly _hits = new Map<string, { count: number; resetAt: number }>();
44
+
45
+ constructor(
46
+ private readonly windowMs: number,
47
+ private readonly max: number,
48
+ private readonly now: () => number = () => Date.now(),
49
+ ) {}
50
+
51
+ /** Returns true when the call is allowed; false when the window is exhausted. */
52
+ check(key: string): boolean {
53
+ const t = this.now();
54
+ const entry = this._hits.get(key);
55
+ if (!entry || t >= entry.resetAt) {
56
+ if (this._hits.size > 10_000) this._prune(t);
57
+ this._hits.set(key, { count: 1, resetAt: t + this.windowMs });
58
+ return true;
59
+ }
60
+ if (entry.count >= this.max) return false;
61
+ entry.count++;
62
+ return true;
63
+ }
64
+
65
+ private _prune(t: number): void {
66
+ for (const [k, v] of this._hits) {
67
+ if (t >= v.resetAt) this._hits.delete(k);
68
+ }
69
+ }
70
+ }
71
+
72
+ /** Extract the bearer token from an Authorization header value, or undefined. */
73
+ export function bearerToken(header: string | string[] | undefined): string | undefined {
74
+ const value = Array.isArray(header) ? header[0] : header;
75
+ if (!value) return undefined;
76
+ const m = /^Bearer\s+(.+)$/i.exec(value.trim());
77
+ return m ? m[1]!.trim() : undefined;
78
+ }