Comprehensive coding rules for building an AI-powered, full-stack knowledge-sharing platform that emphasises discoverability, security, and continuous improvement.
Transform your organization's scattered information into a searchable, intelligent knowledge ecosystem that actually gets used.
Your team's knowledge is trapped everywhere—Slack threads, Google Docs, tribal knowledge in developers' heads, outdated wikis, and buried email chains. When someone needs information, they interrupt colleagues, waste hours searching, or worse, reinvent solutions that already exist.
The hidden costs are staggering:
These Cursor Rules define a production-ready, AI-powered knowledge platform that treats information like code—versioned, searchable, automatically maintained, and designed for discoverability.
What you get:
// Hybrid search combines text matching with AI understanding
POST /search {
"query": "authentication flow mobile app",
"userId": "dev-123",
"locale": "en"
}
// Returns: BM25 (40%) + vector similarity (60%) results
// Response time: <200ms with Redis caching
Impact: Developers find relevant code patterns, architecture decisions, and troubleshooting guides instantly instead of asking in Slack or digging through repositories.
# PR Template automatically enforces knowledge updates
Knowledge Impact:
- [ ] Updated API documentation in /docs/api
- [ ] Architecture decision recorded in ADRs
- [ ] Runbook updated for new deployment steps
- [ ] Ownership assigned to @team-platform
Impact: Every code change triggers documentation updates. CI fails if coverage drops, ensuring your knowledge base never becomes a graveyard of outdated information.
Before: New developer spends weeks asking basic questions, interrupting productive team members, and making assumptions about undocumented systems.
After: AI-powered search surfaces relevant onboarding materials, code examples, and team conventions based on their role and project assignments.
// Contextual search understands developer intent
await searchService.query({
text: "how to set up local development environment",
context: {
userRole: "frontend-developer",
team: "platform",
experience: "junior"
}
});
// Returns: setup guides, common pitfalls, team-specific tooling
Before: Teams waste days in meetings explaining APIs, sharing Postman collections, and writing one-off documentation that quickly becomes outdated.
After: GraphQL schema snapshots, API examples, and integration guides are automatically maintained and discoverable through semantic search.
// Automatic API documentation sync
@Resolver(() => User)
export class UserResolver {
@Query(() => [User])
@Description("Retrieve users with role-based filtering")
async getUsers(@Args() filter: UserFilter): Promise<User[]> {
// Implementation automatically generates searchable docs
}
}
Before: During outages, teams scramble through Slack history, outdated runbooks, and individual knowledge to find solutions.
After: Incident commanders find relevant troubleshooting procedures, past incident reports, and escalation paths through intelligent search that understands the context of the current situation.
# Clone and initialize the knowledge platform
git clone <your-repo>
cd knowledge-platform
# Install dependencies and start development stack
npm install
docker-compose up -d # PostgreSQL, Elasticsearch, Redis
# Run initial migrations
npx prisma migrate deploy
npm run seed:search-index
// Configure hybrid search in search.service.ts
export class SearchService {
async hybridSearch(query: SearchQuery): Promise<SearchResult[]> {
const [textResults, vectorResults] = await Promise.all([
this.elasticsearchClient.search({
index: 'knowledge_base',
body: { query: { match: { content: query.text } } }
}),
this.vectorSearch.findSimilar(query.embeddings, {
threshold: 0.7,
limit: 10
})
]);
// Combine results with 40/60 weighting
return this.combineResults(textResults, vectorResults, [0.4, 0.6]);
}
}
# .github/workflows/knowledge-gate.yml
name: Knowledge Coverage Gate
on: [pull_request]
jobs:
documentation-check:
runs-on: ubuntu-latest
steps:
- name: Check Documentation Coverage
run: |
npm run docs:coverage
# Fails if coverage < 90%
- name: Validate Knowledge Impact
run: |
npm run validate:knowledge-impact
# Ensures PR template knowledge section is completed
// Scheduled job to identify stale content
@Cron('0 2 * * MON') // Every Monday at 2 AM
async identifyStaleContent() {
const staleThreshold = new Date();
staleThreshold.setDate(staleThreshold.getDate() - 180);
const staleDocs = await this.knowledgeRepository.findStaleDocuments(
staleThreshold
);
for (const doc of staleDocs) {
await this.ticketService.createStaleContentTicket({
title: `Update stale documentation: ${doc.title}`,
assignee: doc.owner,
priority: 'medium',
labels: ['documentation', 'maintenance']
});
}
}
Before: Information hoarding, repeated questions, documentation debt, knowledge silos
After: Knowledge sharing culture, self-service information discovery, automated documentation maintenance, cross-team transparency
This isn't just another documentation tool—it's a complete knowledge platform that treats information as a first-class citizen in your development process. The AI-powered search, automated maintenance, and comprehensive architecture give you enterprise-grade knowledge management without the enterprise complexity.
Your team will wonder how they ever worked without intelligent, searchable, automatically maintained knowledge at their fingertips.
Start building your knowledge platform today and watch productivity soar as information becomes truly accessible.
You are an expert in building AI-powered knowledge-sharing platforms with TypeScript, React/Next.js, Node.js (NestJS), GraphQL, PostgreSQL, Elasticsearch, Redis, Docker, Kubernetes, and GitHub Actions.
Key Principles
- Build for discoverability: every artifact (code, docs, decisions) must be searchable via Elasticsearch + vector embedding.
- Default to openness; restrict only what must be private via granular RBAC.
- Automate documentation: each PR must update or create docs; provide CI gate that fails if coverage < 90 %.
- Enforce single source of truth: no duplicated schemas, enums, or constants.
- Treat knowledge as code: version in Git, reviewed in PRs, validated by linters.
- Prioritise happy path readability; guard clauses for errors first.
- Continuous measurement: export metrics (Grafana/Loki) on read/write latency, search success % and stale-content rate.
TypeScript
- "strict": true; noImplicitAny, exactOptionalPropertyTypes, strictNullChecks.
- Use ESLint @typescript-eslint + Prettier; CI fails on ❌.
- Prefer type aliases for primitives, interfaces for objects; never use “any”.
- Function signatures: (input: Readonly<Args>): Promise<Result>.
- Use enums only for closed, stable sets; otherwise union string literals.
- Directory names: lowercase-kebab (e.g., knowledge-graph, user-profile).
- File order: imports → constants → types → helpers → main export(s).
Node.js / NestJS (Backend)
- Each domain feature = Nest module; strictly no circular deps (ts-depend-cy).
- Expose GraphQL API (code-first @nestjs/graphql + Apollo) with schema-stitching disabled.
- Resolver ➜ Service ➜ Repository ➜ Data-source layering; never skip layers.
- Use CQRS (Command/Query buses) to decouple writes (commands) from reads (queries).
- Validation: Zod schema at resolver boundary; fail fast with 400.
- Error handling: Nest Exception Filters convert internal errors → Problem Details (RFC 7807). Map.errorCode to i18n user messages.
- RBAC Guard: @Roles(…) decorator; ownership rules (owner, editor, viewer) stored per knowledge-entity row.
React / Next.js (Frontend)
- Functional components only; use React 18 with Suspense.
- Collocate GraphQL queries with components using gql macro.
- Use SWR for query caching; cache key must include userId + locale.
- Atomic design: atoms / molecules / organisms / templates / pages.
- State management: zustand for local, GraphQL cache for remote; no Redux.
- Style: Tailwind CSS; extend theme in /styles/tailwind.config.ts only.
- Pre-fetch search results with getServerSideProps + stale-while-revalidate headers.
Database (PostgreSQL)
- Use Prisma ORM; schema.prisma is canonical.
- Migrations via prisma migrate deploy executed in CI before tests.
- All tables include: id (uuid pk), created_at, updated_at, deleted_at (soft delete).
- Text search fields sync to Elasticsearch using Debezium CDC.
Search & AI Layer
- Elasticsearch 8 + k-NN plugin; each article indexed with BM25 + sentence-transformer embeddings.
- POST /search accepts {query, userId, locale} ➜ hybrid search (BM25 0.4, vector 0.6).
- Periodic job marks docs untouched > 180 days as “stale” and creates Jira ticket.
Error Handling & Validation
- Guard clauses for permissions, not-found, validation errors.
- HTTP codes: 400 validation, 403 permission, 404 missing, 409 conflict, 500 unexpected.
- Log structured JSON (pino) with err.stack, requestId.
- Client shows toast with user-friendly msg; Sentry captures stack trace + breadcrumbs.
Testing
- Unit: Jest + ts-jest; coverage ≥ 90 %.
- Contract: GraphQL schema snapshots committed.
- E2E: Cypress runs headless against docker-compose stack.
- Search relevance tests: assert top-3 contain expected doc for golden queries.
Performance
- Enable GZIP + brotli on Next.js; set Cache-Control: s-maxage=60, stale-while-revalidate=300.
- Use Redis cache for ACL checks (< 10 ms target).
- SQL: use EXPLAIN on PRs; any query > 100 ms blocked until fixed.
- Purge unused Tailwind CSS classes via content globs.
Security
- Store secrets in Kubernetes Secrets; mount as tmpfs, never committed.
- OWASP ASVS L2 compliance.
- GraphQL depth-limit 8, complexity limit 3000.
- Rate-limit /login and /search (20 req/s/user).
- Regular dependency scans with Snyk.
DevOps / CI-CD
- GitHub Actions: lint → type-check → test → build docker → push → deploy via Argo CD.
- Require passing Lighthouse score ≥ 90 before merge to main.
- Tag images semver + commit SHA; promote via GitOps.
Documentation & Knowledge Capture
- Each merge triggers /docs sync to Confluence via Atlassian API.
- PR template includes “Knowledge Impact” section (updated pages, owners).
- Outdated doc flagged by CI (GitHub Action) comparing updated_at ≤ code commit date.
Common Pitfalls
- Forgetting to update search index after schema change – add PostDeploy hook.
- Circular NestJS dependencies – use forwardRef or refactor.
- GraphQL N+1 – use DataLoader in resolvers.
Ready-To-Use Snippet
```ts
// Example guarded resolver
@Resolver(() => Article)
export class ArticleResolver {
constructor(private readonly bus: QueryBus) {}
@Query(() => [Article])
async searchArticles(
@Args('query') query: string,
@CurrentUser() user: SessionUser
) {
await authorize(user, Permission.SEARCH_ARTICLE);
return this.bus.execute(new SearchArticlesQuery({ query, userId: user.id }));
}
}
```