@corgelabs/corge 1.0.1 → 1.0.3

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.
Files changed (2) hide show
  1. package/README.md +274 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,274 @@
1
+ <div align="center">
2
+
3
+ # ⚡ Corge (`@corgelabs/corge`)
4
+
5
+ **The Zero-Boilerplate AI & Durable Workflow Backend-in-a-Box for GCP Cloud Functions v2.**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@corgelabs/corge?color=0ea5e9&label=%40corgelabs%2Fcorge)](https://www.npmjs.com/package/@corgelabs/corge)
8
+ [![Node.js >= 24](https://img.shields.io/badge/node-%3E%3D24-339933?logo=nodedotjs&logoColor=white)](https://nodejs.org)
9
+ [![TypeScript Strict](https://img.shields.io/badge/TypeScript-Strict-3178c6?logo=typescript&logoColor=white)](https://www.typescriptlang.org)
10
+ [![GCP Cloud Functions v2](https://img.shields.io/badge/GCP-Cloud_Functions_v2-4285F4?logo=googlecloud&logoColor=white)](https://cloud.google.com/functions)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-f59e0b.svg)](https://opensource.org/licenses/MIT)
12
+
13
+ [Why Corge?](#-why-corge-stop-writing-glue-code) · [30-Second Quickstart](#-30-second-quickstart) · [4 Architectural Pillars](#-the-4-architectural-pillars) · [Built for AI Coding Agents](#-built-for-ai-coding-agents) · [CLI Reference](#-built-in-corge-cli) · [Full SDK Spec](./docs/SDK_SPEC.md)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## 🔥 Why Corge? Stop Writing Glue Code.
20
+
21
+ Modern AI SaaS backends drown in **10,000+ lines of infrastructure plumbing** before shipping a single product feature: stitching together Hono/Express routers, Vercel AI / LangChain streams, BullMQ / Temporal durable workers, Stripe / Dodo webhook verifiers, SendGrid / Resend email templates, Firebase Auth sessions, and GCS signed URLs.
22
+
23
+ **Corge collapses the entire stack into a single `core` singleton.**
24
+
25
+ Your repository contains **100% pure domain business logic**—declarative Zod schemas, routes, agents, and services—while `@corgelabs/corge` handles distributed durability, multi-tenant zero-trust security, multimodal AI orchestration, billing, and one-command Cloud Functions v2 deployment.
26
+
27
+ | Layer | Traditional DIY Stack (10+ Packages & Glue) | With `@corgelabs/corge` |
28
+ | :--- | :--- | :--- |
29
+ | **HTTP, SSE & Guardrails** | Hono + custom CORS, rate limiters, body limits, auth middleware | `core.createApp()` + `core.define.routes()` |
30
+ | **Durable Workflows** | Temporal / Inngest / BullMQ + Redis + custom retry & rollback code | `mode: 'workflow'` + `useCore().step()` with Saga rollback |
31
+ | **Multimodal AI & RAG** | Vercel AI SDK + custom OCR + vector DB + custom MCP server | `core.ai`, `core.chat`, `core.attachments` + opt-in `/api/mcp` |
32
+ | **Database & Tenant RBAC** | Raw `firebase-admin/firestore` + manual converters & ownership checks | `core.db` + `core.define.collections()` (Zod strict + RBAC) |
33
+ | **Object Storage** | Raw `@google-cloud/storage` + manual MIME & tenant validation | `core.files` (`{userId}_{sha256}` content-addressed $O(1)$ ACLs) |
34
+ | **Auth & Sessions** | Custom JWTs, OAuth state, password reset tokens, revocation lists | `core.auth` (Cookies, Google/Apple OIDC, 3s revocation watermark) |
35
+ | **Subscriptions & Metering** | Stripe / Dodo SDKs + webhook HMAC + custom token quota counters | `core.payments` (Plans, Products, Webhooks, AI Token Quotas) |
36
+ | **Transactional Emails** | SendGrid / Resend SDKs + bounce webhooks + suppression tables | `core.emails` (Zod templates, FileRef attachments, auto-suppression) |
37
+ | **Build, Dev & Deploy** | Custom `esbuild` scripts, Secret Manager loaders, `firebase.json` hacks | `npx corge dev` · `corge build` · `corge deploy` · `corge test` |
38
+
39
+ ```mermaid
40
+ flowchart TB
41
+ subgraph Consumer["Your Repository (100% Domain Logic)"]
42
+ Entry["src/index.ts — core.createApp(...)"]
43
+ Config["src/config/ — collections, routes, agents, plans, emails"]
44
+ Services["src/services/ & src/routes/ — Domain Workflows & REST"]
45
+ end
46
+
47
+ subgraph Corge["@corgelabs/corge Runtime & CLI"]
48
+ Router["Router & Transport Guards\n(Auth, RBAC, Rate Limits, Idempotency)"]
49
+ Tasks["Durable Workflow Engine\n(Sync -> 202 Cloud Tasks, Epoch Fencing, Saga Rollback)"]
50
+ AI["AI, Chat & Attachments\n(Vertex Gemini, Mistral OCR, Jina Rerank, Hybrid RAG, MCP)"]
51
+ SaaS["SaaS Primitives\n(core.db, core.files, core.auth, core.payments, core.emails)"]
52
+ end
53
+
54
+ subgraph GCP["Google Cloud & External Providers"]
55
+ Infra["Cloud Functions v2 · Cloud Tasks · Firestore · Cloud Storage · Secret Manager"]
56
+ Vendors["Stripe · Dodo Payments · SendGrid · Resend"]
57
+ end
58
+
59
+ Entry --> Router
60
+ Config --> Router
61
+ Services --> Tasks
62
+ Services --> AI
63
+ Services --> SaaS
64
+ Router --> Tasks
65
+ Router --> AI
66
+ Router --> SaaS
67
+ Tasks --> Infra
68
+ AI --> Infra
69
+ SaaS --> Infra
70
+ SaaS --> Vendors
71
+ ```
72
+
73
+ ---
74
+
75
+ ## 🚀 30-Second Quickstart
76
+
77
+ ### 1. Install & Scaffold
78
+
79
+ ```bash
80
+ npm install @corgelabs/corge
81
+ npx corge init
82
+ ```
83
+
84
+ ### 2. Define Your App (`src/index.ts`)
85
+
86
+ ```ts
87
+ import { core } from '@corgelabs/corge'
88
+ import { z } from 'zod'
89
+
90
+ const collections = core.define.collections({
91
+ invoice: core.define.collection({
92
+ schema: z.strictObject({
93
+ id: core.schemas.entryId,
94
+ userId: core.schemas.entryId,
95
+ vendor: z.string(),
96
+ totalCents: z.number().int().nonnegative()
97
+ }),
98
+ rbac: { user: ['create', 'read', 'list'], admin: ['create', 'read', 'update', 'delete', 'list'] }
99
+ })
100
+ })
101
+
102
+ const routes = core.define.routes({
103
+ 'extract-invoice': core.define.route({
104
+ mode: 'workflow',
105
+ method: 'POST',
106
+ path: '/invoices/extract',
107
+ description: 'Extracts structured invoice fields from an uploaded PDF and records a ledger entry',
108
+ mcp: true,
109
+ input: z.strictObject({ fileRef: core.schemas.fileRef }),
110
+ handler: async ({ input, step }) => {
111
+ const { ai, db, userId } = core
112
+
113
+ const extracted = await step('vision-extract', () =>
114
+ ai.vision({
115
+ fileRef: input.fileRef,
116
+ prompt: 'Extract vendor name and total amount in cents.',
117
+ schema: z.object({ vendor: z.string(), totalCents: z.number().int() })
118
+ })
119
+ )
120
+
121
+ const record = await step('persist-invoice', {
122
+ fn: () => db.create('invoice', { userId, ...extracted.output }),
123
+ rollback: async () => {
124
+ // Automatic reverse-order Saga compensation on downstream failure or task cancellation
125
+ }
126
+ })
127
+
128
+ return record
129
+ }
130
+ })
131
+ })
132
+
133
+ export const { app, devApp, functions } = core.createApp({
134
+ collections,
135
+ routes
136
+ })
137
+ ```
138
+
139
+ ### 3. Develop, Test & Deploy
140
+
141
+ ```bash
142
+ # Start local Hono server with live watch mode + automatic GCP Secret Manager injection
143
+ npx corge dev
144
+
145
+ # Typecheck (<1s via pre-built .d.ts with F12 source maps straight into Corge's TypeScript source)
146
+ npx corge check
147
+
148
+ # Bundle app + @corgelabs/corge into dist/index.cjs and deploy to Cloud Functions v2
149
+ npx corge deploy dev
150
+ npx corge deploy prod
151
+ ```
152
+
153
+ ---
154
+
155
+ ## 🏛️ The 4 Architectural Pillars
156
+
157
+ ### 1. Adaptive `200`/`202` Durable Workflows & Saga Rollbacks
158
+ Every route with `mode: 'workflow'` runs through Corge's durable execution engine:
159
+ - **Adaptive Sync-to-Async Promotion**: Starts executing synchronously. If the workflow finishes within the sync window (`syncTimeoutSeconds`), the caller gets an immediate `200 OK`. If it takes longer (or ` Prefer: respond-async` is sent), Corge seamlessly detaches and returns `202 Accepted` with `{ taskId, status: 'running' }` while Cloud Tasks continues execution in the background.
160
+ - **Per-Step Firestore Checkpointing (`step()`)**: Completed steps are memoized in `_tasks/{taskId}`. Retries and continuations replay completed steps in `0ms`.
161
+ - **Monotonic Epoch Fencing**: Every worker claim increments `epoch`. Zombie or hedged workers attempting to commit with a stale epoch are fenced immediately via `StaleWorkerEpochError`.
162
+ - **75% Deadline Auto-Yield**: Before a Cloud Function hits its wall-clock deadline, Corge checkpoints progress and dispatches a continuation task to Cloud Tasks.
163
+ - **Reverse-Order Saga Compensation**: Register `rollback` handlers on any `step()` or run parallel branches via `step.allWithRollback([...])`—if a downstream step fails or `DELETE /api/tasks/:taskId` cancels the workflow, completed steps are compensated in reverse order with crash-safe checkpointing.
164
+
165
+ ```ts
166
+ const { step } = useCore()
167
+
168
+ const [crmRecord, billingRecord] = await step.allWithRollback([
169
+ {
170
+ name: 'provision-crm',
171
+ fn: () => provisionCrmTenant(userId),
172
+ rollback: (crm) => deleteCrmTenant(crm.id)
173
+ },
174
+ {
175
+ name: 'provision-billing',
176
+ fn: () => core.payments.subscribe({ planId: 'pro' }),
177
+ rollback: (sub) => core.payments.cancelSubscription({ subscriptionId: sub.subscriptionId, immediate: true })
178
+ }
179
+ ])
180
+ ```
181
+
182
+ ---
183
+
184
+ ### 2. Multimodal AI Agents, Hybrid RAG & Opt-In MCP
185
+ - **`core.ai`**: Unified interface over **Vertex AI (Gemini 2.5 Pro / Flash)**, **Mistral (`mistral-ocr-latest`)**, and **Jina (`jina-embeddings-v3` + `jina-reranker-v2-base-multilingual`)** wrapped in distributed circuit breakers and singleflight deduplication:
186
+ - `core.ai.generate({ prompt, schema, system, tier })` — Structured Zod output or text generation with automatic Vertex ↔ Mistral fallback.
187
+ - `core.ai.vision({ fileRef, prompt, schema })` — Multimodal document/image extraction.
188
+ - `core.ai.decide({ query, questions })` — Parallel boolean/enum intent classification via `@typesafe-ai/sdk`.
189
+ - `core.ai.embed(text)` & `core.ai.rerank(query, docs)` — 768-dim embeddings & cross-encoder reranking.
190
+ - **`core.chat` & `core.define.agents()`**:
191
+ - Multi-agent registry with per-agent system prompts, allowed workflow tools, InfoBase markdown context (`core.define.context()`), and dynamic user context resolvers.
192
+ - **Hybrid Vector + Keyword RAG (`core.chat.retrieveHybrid`)**: Combines Firestore vector nearest-neighbor search (`embedding`) with lexical scoring and Jina reranking.
193
+ - **Dual Streaming Protocols**: Native `/api/chat/stream` SSE and OpenAI-compatible `/api/v1/chat/completions` (`stream: true | false`) with stream cancellation (`/api/chat/:chatId/cancel`).
194
+ - **Opt-In Model Context Protocol (`/api/mcp`)**: Any workflow route marked with `mcp: true` is automatically exposed as a JSON-RPC 2.0 MCP tool with Zod-to-JSON-Schema input validation.
195
+
196
+ ---
197
+
198
+ ### 3. Batteries-Included SaaS Engine (`db`, `files`, `auth`, `payments`, `emails`)
199
+
200
+ #### `core.db` — Schema-Driven Firestore with RBAC & User Connectors
201
+ - Every collection is defined with `z.strictObject()` and receives an automatic `FirestoreDataConverter<T>`.
202
+ - Built-in tenant isolation (`userId === caller.userId`), soft-delete (`deleted: true`), cursor pagination, strip-on-update for immutable/owner fields, and automatic GDPR erasure (`cascadeEraseUserCollections`).
203
+
204
+ #### `core.files` & `core.attachments` — Content-Addressed Storage & Magic-Byte Verification
205
+ - File IDs are content-addressed (`{userId}_{sha256_prefix}`), enabling **$O(1)$ tenant ownership checks** before touching Firestore or GCS.
206
+ - Enforces magic-byte signature verification (rejecting spoofed HTML/scripts disguised as PDF/PNG/JPEG) and caches OCR/vision scan results by SHA-256 across uploads.
207
+
208
+ #### `core.auth` — Zero-Trust Sessions, OIDC & Cluster-Wide Revocation
209
+ - Firebase Auth + HTTP-only session cookies, Google & Apple RS256 OIDC sign-in (`signInSocial`), email verification, recovery emails, password reset, and two-tier token cache with a **3-second cluster-wide Firestore revocation watermark**.
210
+
211
+ #### `core.payments` — Subscriptions, One-Time Checkouts & AI Token Quota Metering
212
+ - First-class **Stripe** and **Dodo Payments** adapters with automatic `isDev` sandbox switching, timing-safe HMAC webhook verification (`/api/payments/webhooks/:provider`), idempotent ledger (`payment_transaction`), and **automatic AI token quota enforcement** per subscription tier.
213
+
214
+ #### `core.emails` — Typed Transactional Emails, Batching & Bounce Suppression
215
+ - First-class **SendGrid** and **Resend** adapters, Zod-validated dynamic templates (`core.define.emailTemplates()`), `FileRef` attachments pulled straight from `core.files`, idempotency locks, and HMAC webhook handlers (`/api/emails/webhooks/:provider`) that automatically populate `email_suppression` on hard bounces or spam complaints.
216
+
217
+ ---
218
+
219
+ ### 4. AI-Native DX & Zero-Token Cloud Build
220
+
221
+ ```text
222
+ my-saas-backend/
223
+ ├── .env # Empty keys auto-resolved from GCP Secret Manager by `corge`
224
+ ├── firebase.json # Standard Firebase config
225
+ ├── package.json # Only 1 runtime dependency: "@corgelabs/corge"
226
+ ├── tsconfig.json # Extends "@corgelabs/corge/tsconfig.base.json"
227
+ └── src/
228
+ ├── index.ts # Exports core.createApp({ collections, routes, agents, ... })
229
+ ├── config/ # Declarative schemas, routes, agents, plans, emails
230
+ ├── context/ # Domain InfoBase markdown (.md) files
231
+ ├── routes/ # Domain HTTP & durable workflow handlers
232
+ └── services/ # Pure domain business logic
233
+ ```
234
+
235
+ 1. **Instant `<1s` Typecheck + `F12` Into Raw TypeScript Source**:
236
+ `@corgelabs/corge` ships both pre-compiled `dist/*.d.ts` + `dist/*.d.ts.map` **and** `src/**/*.ts` inside the npm tarball. Consumer `tsc --noEmit` runs in under a second while pressing **`F12` (Go to Definition)** in VS Code / Cursor / Antigravity opens the actual `.ts` implementation inside `node_modules/@corgelabs/corge/src/`.
237
+ 2. **Self-Bundling Cloud Functions Compiler (Zero GCP Cloud Build Auth Failures)**:
238
+ `corge build` bundles `@corgelabs/corge` directly into `dist/index.cjs` while keeping public npm packages external. During `corge deploy`, the CLI merges Corge's base Firestore/Storage rules & vector indexes with your project's rules and temporarily expands public runtime dependencies into `package.json`—so Google Cloud Build never needs a private `.npmrc` token.
239
+
240
+ ---
241
+
242
+ ## 🤖 Built for AI Coding Agents
243
+
244
+ `@corgelabs/corge` ships its complete machine-readable specification inside the npm package at `node_modules/@corgelabs/corge/docs/SDK_SPEC.md` (`@corgelabs/corge/spec`).
245
+
246
+ Add this rule to your consumer repository's `AGENTS.md`, `.cursorrules`, or `.gemini/GEMINI.md` so your coding agent writes 100% idiomatic Corge code on the first try:
247
+
248
+ ```markdown
249
+ ## Corge SDK (`@corgelabs/corge`) Rules
250
+ - Before creating or modifying routes, collections, agents, workflows, payments, or emails, read `node_modules/@corgelabs/corge/docs/SDK_SPEC.md`.
251
+ - Import `core` and `useCore` from `@corgelabs/corge`.
252
+ - Keep all consumer code strictly declarative (`core.define.{collections,routes,agents,plans,products,emailTemplates}`) and wrap multi-step side effects inside `useCore().step()` with `rollback` handlers where applicable.
253
+ ```
254
+
255
+ ---
256
+
257
+ ## 🛠️ Built-In `corge` CLI
258
+
259
+ | Command | Description |
260
+ | :--- | :--- |
261
+ | **`npx corge init`** | Scaffolds a clean consumer project (`tsconfig.json`, `src/index.ts`, `src/config/`, `src/routes/`, `src/services/`). |
262
+ | **`npx corge dev`** | Resolves `.env` + empty secrets from GCP Secret Manager, bundles `src/index.ts` in `esbuild` watch mode, and starts a hot-reloading Hono server on `PORT` (default `8080`). |
263
+ | **`npx corge build`** | Bundles `src/index.ts` + `@corgelabs/corge` into `dist/index.cjs` (`node24`, CJS, sourcemap) ready for Cloud Functions v2. |
264
+ | **`npx corge deploy <prod\|dev>`** | Enforces git branch guard (`main` for `prod`, `dev` for `dev`), runs `corge build`, merges Corge's base Firestore/Storage rules & indexes, expands runtime deps, and deploys via `firebase-tools`. |
265
+ | **`npx corge test`** | Bundles and executes the E2E contract & integration test suite (`node --test`) with GCP Secret Manager injection. |
266
+ | **`npx corge check`** | Runs `tsc --noEmit` in the workspace. |
267
+ | **`npx corge link [path]`** | Symlinks a local checkout of `corgelabs/corge` into `node_modules/@corgelabs/corge` for instant live multi-repo editing (`npx corge unlink` restores the npm version). |
268
+ | **`npx corge env -- <cmd>`** | Runs any arbitrary command with `.env` + GCP Secret Manager secrets injected into `process.env`. |
269
+
270
+ ---
271
+
272
+ ## 📄 License
273
+
274
+ MIT © [Corge Labs](https://github.com/corgelabs)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@corgelabs/corge",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Corge: High-load serverless AI, durable workflow, payments & auth SDK for GCP Cloud Functions v2",
5
5
  "license": "MIT",
6
6
  "repository": {