Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into garrytan/v0.6-mcp-server
Garry Tan37f512297a57
diff --cc CHANGELOG.mdindex aaeac89610,373d19145d..d4748ccc60--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -2,37 -2,14 +2,45 @@@All notable changes to GBrain will be documented in this file.+## [0.6.0] - 2026-04-10++### Added++- **Access your brain from any AI client.** Deploy GBrain as a serverless remote MCP endpoint on your existing Supabase instance. Works with Claude Desktop, Claude Code, Cowork, and Perplexity Computer. One URL, bearer token auth, zero new infrastructure. Clone the repo, fill in 3 env vars, run `scripts/deploy-remote.sh`, done.+- **Per-client setup guides** in `docs/mcp/` for Claude Code, Claude Desktop, Cowork, Perplexity, and ChatGPT (coming soon, requires OAuth 2.1). Also documents Tailscale Funnel and ngrok as self-hosted alternatives.+- **Token management** via standalone `src/commands/auth.ts`. Create, list, revoke per-client bearer tokens. Includes smoke test: `auth.ts test <url> --token <token>` verifies the full pipeline (initialize + tools/list + get_stats) in 3 seconds.+- **Usage logging** via `mcp_request_log` table. Every remote tool call logs token name, operation, latency, and status for debugging and security auditing.+- **Hardened health endpoint** at `/health`. Unauthenticated: 200/503 only (no info disclosure). Authenticated: checks postgres, pgvector, and OpenAI API key status.++### Fixed++- **MCP server actually connects now.** Handler registration used string literals (`'tools/list' as any`) instead of SDK typed schemas. Replaced with `ListToolsRequestSchema` and `CallToolRequestSchema`. Without this fix, `gbrain serve` silently failed to register handlers. (Issue #9)+- **Search results no longer flooded by one large page.** Keyword search returned ALL chunks from matching pages. Now returns one best chunk per page via `DISTINCT ON`. (Issue #22)+- **Search dedup no longer collapses to one chunk per page.** Layer 1 kept only the single highest-scoring chunk per slug. Now keeps top 3, letting later dedup layers (text similarity, cap per page) do their job. (Issue #22)+- **Transactions no longer corrupt shared state.** Both `PostgresEngine.transaction()` and `db.withTransaction()` swapped the shared connection reference, breaking under concurrent use. Now uses scoped engine via `Object.create` with no shared state mutation. (Issue #22)+- **embed --stale no longer wipes valid embeddings.** `upsertChunks()` deleted all chunks then re-inserted, writing NULL for chunks without new embeddings. Now uses UPSERT (INSERT ON CONFLICT UPDATE) with COALESCE to preserve existing embeddings. (Issue #22)+- **Slug normalization is consistent.** `pathToSlug()` preserved case while `inferSlug()` lowercased. Now `validateSlug()` enforces lowercase at the validation layer, covering all entry points. (Issue #22)+- **initSchema no longer reads from disk at runtime.** Both schema loaders used `readFileSync` with `import.meta.url`, which broke in compiled binaries and Deno Edge Functions. Schema is now embedded at build time via `scripts/build-schema.sh`. (Issue #22)+- **file_upload actually uploads content.** The operation wrote DB metadata but never called the storage backend. Fixed in all 3 paths (operation, CLI upload, CLI sync) with rollback semantics. (Issue #22)+- **S3 storage backend authenticates requests.** `signedFetch()` was just unsigned `fetch()`. Replaced with `@aws-sdk/client-s3` for proper SigV4 signing. Supports R2/MinIO via `forcePathStyle`. (Issue #22)+- **Parallel import uses thread-safe queue.** `queue.shift()` had race conditions under parallel workers. Now uses an atomic index counter. Checkpoint preserved on errors for safe resume. (Issue #22)+- **redirect verifies remote existence before deleting local files.** Previously deleted local files unconditionally. Now checks storage backend before removing. (Issue #22)+- **`gbrain call` respects dry_run.** `handleToolCall()` hardcoded `dryRun: false`. Now reads from params. (Issue #22)++### Changed++- Added `@aws-sdk/client-s3` as a dependency for authenticated S3 operations.+- Schema migration v2: unique index on `content_chunks(page_id, chunk_index)` for UPSERT support.+- Schema migration v3: `access_tokens` and `mcp_request_log` tables for remote MCP auth.++ ## [0.5.1] - 2026-04-10++ ### Fixed++ - **Apple Notes and files with spaces just work.** Paths like `Apple Notes/2017-05-03 ohmygreen.md` now auto-slugify to clean slugs (`apple-notes/2017-05-03-ohmygreen`). Spaces become hyphens, parens and special characters are stripped, accented characters normalize to ASCII. All 5,861+ Apple Notes files import cleanly without manual renaming.+ - **Existing brains auto-migrate.** On first run after upgrade, a one-time migration renames all existing slugs with spaces or special characters to their clean form. Links are rewritten automatically. No manual cleanup needed.+ - **Import and sync produce identical slugs.** Both pipelines now use the same `slugifyPath()` function, eliminating the mismatch where sync preserved case but import lowercased.+## [0.5.0] - 2026-04-10### Addeddiff --cc src/core/migrate.tsindex 3f233ad5f0,b82905856b..d8194a7446--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@@ -22,38 -27,27 +27,61 @@@ const MIGRATIONS: Migration[] =// Version 1 is the baseline (schema.sql creates everything with IF NOT EXISTS).{version: 2,+ name: 'slugify_existing_pages',+ sql: '',+ handler: async (engine) => {+ const pages = await engine.listPages();+ let renamed = 0;+ for (const page of pages) {+ const newSlug = slugifyPath(page.slug);+ if (newSlug !== page.slug) {+ try {+ await engine.updateSlug(page.slug, newSlug);+ await engine.rewriteLinks(page.slug, newSlug);+ renamed++;+ } catch (e: unknown) {+ const msg = e instanceof Error ? e.message : String(e);+ console.error(` Warning: could not rename "${page.slug}" → "${newSlug}": ${msg}`);+ }+ }+ }+ if (renamed > 0) console.log(` Renamed ${renamed} slugs`);+ },+ },++ {++ version: 3,+ name: 'unique_chunk_index',+ sql: `+ -- Deduplicate any existing duplicate (page_id, chunk_index) rows before adding constraint+ DELETE FROM content_chunks a USING content_chunks b+ WHERE a.page_id = b.page_id AND a.chunk_index = b.chunk_index AND a.id > b.id;+ CREATE UNIQUE INDEX IF NOT EXISTS idx_chunks_page_index ON content_chunks(page_id, chunk_index);+ `,+ },+ {- version: 3,++ version: 4,+ name: 'access_tokens_and_mcp_log',+ sql: `+ CREATE TABLE IF NOT EXISTS access_tokens (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ name TEXT NOT NULL,+ token_hash TEXT NOT NULL UNIQUE,+ scopes TEXT[],+ created_at TIMESTAMPTZ DEFAULT now(),+ last_used_at TIMESTAMPTZ,+ revoked_at TIMESTAMPTZ+ );+ CREATE INDEX IF NOT EXISTS idx_access_tokens_hash ON access_tokens (token_hash) WHERE revoked_at IS NULL;+ CREATE TABLE IF NOT EXISTS mcp_request_log (+ id SERIAL PRIMARY KEY,+ token_name TEXT,+ operation TEXT NOT NULL,+ latency_ms INTEGER,+ status TEXT NOT NULL DEFAULT 'success',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --cc src/core/sync.tsindex 6a8e7f8408,c37b3dbfd0..c71dc8664a--- a/src/core/sync.ts+++ b/src/core/sync.ts@@@ -97,21 -97,39 +97,39 @@@ export function isSyncable(path: string}/**- * Convert a repo-relative file path to a GBrain page slug.+ * Slugify a single path segment: lowercase, strip special chars, spaces → hyphens.+ */+ export function slugifySegment(segment: string): string {+ return segment+ .normalize('NFD') // Decompose accented chars+ .replace(/[\u0300-\u036f]/g, '') // Strip accent marks+ .toLowerCase()+ .replace(/[^a-z0-9.\s_-]/g, '') // Keep alphanumeric, dots, spaces, underscores, hyphens+ .replace(/[\s]+/g, '-') // Spaces → hyphens+ .replace(/-+/g, '-') // Collapse multiple hyphens+ .replace(/^-|-$/g, ''); // Strip leading/trailing hyphens+ }++ /**+ * Slugify a file path: strip .md, normalize separators, slugify each segment.** Examples:- * people/pedro-franceschi.md → people/pedro-franceschi- * daily/2026-04-05.md → daily/2026-04-05- * notes.md → notes+ * Apple Notes/2017-05-03 ohmygreen.md → apple-notes/2017-05-03-ohmygreen+ * people/alice-smith.md → people/alice-smith+ * notes/v1.0.0.md → notes/v1.0.0+ */+ export function slugifyPath(filePath: string): string {+ let path = filePath.replace(/\.md$/i, '');+ path = path.replace(/\\/g, '/');+ path = path.replace(/^\.?\//, '');+ return path.split('/').map(slugifySegment).filter(Boolean).join('/');+ }++ /**+ * Convert a repo-relative file path to a GBrain page slug.*/export function pathToSlug(filePath: string, repoPrefix?: string): string {- // Strip .md extension- let slug = filePath.replace(/\.md$/, '');- // Normalize separators- slug = slug.replace(/\\/g, '/');- // Strip leading slash- slug = slug.replace(/^\//, '');- // Add repo prefix for multi-repo setups+ let slug = slugifyPath(filePath);if (repoPrefix) slug = `${repoPrefix}/${slug}`;- return slug;+ return slug.toLowerCase();}