Repository navigation
feat(metadata): add structured context export endpoint - #1457
Conversation
Add GET /api/metadata/context that aggregates all project metadata into a single response for AI coding tools and developer onboarding. - Fetches auth, database schema, indexes, policies, triggers, storage, functions, and realtime data in parallel from existing services - Supports ?format=json (default) and ?format=markdown - Markdown formatter renders tables, foreign keys, RLS, indexes, etc. - No new database queries — reuses 100% of existing service methods - 3 unit tests for the markdown formatter Closes InsForge#1429
The exportDatabase JSON response already returns functions and views data. Extract and include them in the context payload and Markdown formatter.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds formatContextAsMarkdown, updates the admin GET / metadata route to return Markdown when ChangesProject Metadata Export
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review — feat(metadata): add structured context export endpoint
Overall shape is good: parallel Promise.all, pure formatter, tests for the happy path and edge cases. A few correctness issues need fixing before this merges.
🔴 Important — fix before merge
1. database.data is cast without a null guard — potential runtime crash
backend/src/api/routes/metadata/index.routes.ts, around the dbExport assignment:
const dbExport = database.data as {
tables: Record<string, unknown>;
functions: unknown[];
views: unknown[];
};exportDatabase returns a wrapper object; if .data is null or undefined in any edge-case path (empty project, feature flag off, partial failure inside the service), the subsequent accesses dbExport.tables, dbExport.functions, dbExport.views each throw a TypeError and the entire endpoint crashes. The catch → next(error) block rescues the request, but the caller gets a 500 with no data instead of a graceful partial response. Guard it:
const dbExport = (database.data ?? {}) as { ... };
// then use dbExport.tables ?? {}, dbExport.functions ?? [], dbExport.views ?? []2. Indexes, policies, and triggers are silently incomplete for non-public schemas
backend/src/api/routes/metadata/index.routes.ts line ~173:
const schemaName = 'public';getIndexes(schemaName), getPolicies(schemaName), and getTriggers(schemaName) are all scoped to public only. Any project that places tables in a custom schema (common for multi-tenant setups, extensions, private, etc.) will receive an empty indexes/policies/triggers array with no indication that data was omitted. Since dbAdvanceService.exportDatabase presumably already handles multi-schema export (it's passed undefined for the schema parameter), there is an implicit inconsistency in completeness between the database.tables section and the database.indexes/policies/triggers sections.
Consider either: passing undefined to those three calls if the services support it, or iterating over the fetched schemas list and merging results — or at least documenting the limitation.
🟡 Moderate — strongly recommended
3. Markdown table cells are not sanitised — | in DB identifiers breaks table structure
backend/src/utils/context-formatter.ts, column-rendering loop (~line 57):
lines.push(`| ${col.columnName} | ${col.dataType} | ${nullable} | ${def} |`);Column names, data types, and columnDefault values come directly from the database and can contain | (e.g. a default expression like array['a','b']::text[] is fine, but a pathological default or a type alias with | breaks the GFM table parser). AI coding tools that consume the Markdown may misparse the table entirely. Escape | → \| (and newlines → space) in every value interpolated into table cells:
const esc = (s: string) => String(s ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
lines.push(`| ${esc(col.columnName)} | ${esc(col.dataType)} | ${nullable} | ${esc(def)} |`);4. Policies are rendered twice in the Markdown output
backend/src/utils/context-formatter.ts, ~lines 68–79 and ~lines 93–100:
- Per-table:
tableData.policies(fromexportDatabase) is rendered under#### tableName. - Schema-level:
db.policies(fromgetPolicies('public')) is rendered again under### RLS Policies.
For a typical project these are the same policies, so every policy appears twice. An AI consuming the document will likely double-count them or treat them as two separate policy sets. Either remove the per-table policy sub-section and rely on the schema-level summary, or remove the schema-level summary and keep only the per-table view — pick one authoritative source.
🟢 Minor / Nit
5. process.env.npm_package_version is unreliable in production
backend/src/api/routes/metadata/index.routes.ts:
const version = process.env.npm_package_version || '1.0.0';npm_package_version is only injected into the environment by the npm CLI lifecycle. When the server is started via node dist/index.js (typical in Docker containers), this variable is absent and the fallback '1.0.0' is silently used, misreporting the actual deployed version. Prefer reading from package.json at startup, or pass the version in via a deliberate APP_VERSION env var.
✅ What's good
Promise.allfor parallel fetches — correct and efficient.- Route registration before
/:tableNamewildcard — correct placement. formatContextAsMarkdownis a pure function with no side effects — easy to test and extend.- The three unit test cases cover the full, empty, and no-FK/policy paths — solid coverage for the formatter.
- Error delegation via
next(error)is consistent with the rest of the router.
The structure is sound; findings 1 and 2 are the blockers.
Greptile SummaryRefactors the
Confidence Score: 5/5Safe to merge; the change is an additive refactoring with no breaking API changes and all previously noted gaps (realtime fetch, pipe escaping) are addressed. The aggregation logic is clean, the zod validation correctly handles invalid and missing format values, and the Markdown formatter's escaping logic is correct and well-tested. No regressions in existing sub-routes — the individual /auth, /database, etc. paths are untouched. The only open nit is a cosmetic inconsistency in the Storage section's total-size placement after a fallback message. No files require special attention; the minor style inconsistency in metadata.service.ts around Storage total-size rendering is the only open item. Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant Router as metadata/index.routes.ts
participant MS as MetadataService
participant Auth as AuthService
participant DB as DatabaseManager
participant Store as StorageService
participant Fn as FunctionService
participant RT as RealtimeChannelService
participant Deploy as DeploymentService
Client->>Router: "GET /api/metadata[?format=markdown]"
Router->>Router: zod.safeParse(req.query)
alt invalid format value
Router-->>Client: 400 Invalid format parameter
else valid / default
Router->>MS: getAppMetadata()
MS->>Auth: getMetadata()
MS->>DB: getMetadata()
MS->>Store: getMetadata()
MS->>Fn: getMetadata()
MS->>RT: getMetadata()
MS->>Deploy: getConfigMetadata()
Note over MS: Promise.all — all in parallel
MS-->>Router: AppMetadataSchema
alt "format === 'markdown'"
Router->>MS: formatAsMarkdown(metadata)
MS-->>Router: string
Router-->>Client: 200 text/markdown
else "format === 'json'"
Router-->>Client: 200 application/json
end
end
Reviews (9): Last reviewed commit: "fix(metadata): update OpenAPI schema, ha..." | Re-trigger Greptile |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
backend/src/utils/context-formatter.ts (2)
8-8: ⚖️ Poor tradeoffConsider a typed context interface instead of
any.Defining an interface for the context shape would let the formatter, endpoint, and tests share a single contract and catch field-name drift (e.g.,
dbFunctionsvsfunctions) at compile time rather than producing silently empty sections.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/utils/context-formatter.ts` at line 8, Replace the untyped parameter in formatContextAsMarkdown with a shared, exported interface (e.g., export interface Context) that declares the exact properties the formatter consumes (for example functions vs dbFunctions, systemPrompt, userMessage, etc.) and their appropriate types/optionality; change the function signature to formatContextAsMarkdown(context: Context): string, update any callers (endpoints and tests) to import and use the Context type, and adjust property names in the interface to match the concrete fields used by formatContextAsMarkdown so TypeScript catches any drift like dbFunctions vs functions.
50-59: 💤 Low valueUnescaped
|in Markdown table cells can break rendering.
columnDefault,dataType, orcolumnNamevalues containing a pipe character will corrupt the generated table row. Since this is sourced from arbitrary DB schema metadata, consider escaping|(and stripping newlines) before emitting cells.♻️ Optional escaping helper
+ const cell = (v: unknown) => String(v).replace(/\|/g, '\\|').replace(/\n/g, ' '); for (const col of tableData.schema) { const nullable = col.isNullable === 'YES' ? 'yes' : 'no'; const def = col.columnDefault ?? '-'; - lines.push(`| ${col.columnName} | ${col.dataType} | ${nullable} | ${def} |`); + lines.push(`| ${cell(col.columnName)} | ${cell(col.dataType)} | ${nullable} | ${cell(def)} |`); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/utils/context-formatter.ts` around lines 50 - 59, The table generation in the block that iterates tableData.schema can break when col.columnName, col.dataType or col.columnDefault contain pipe characters or newlines; sanitize those cell values (for example in a small helper used by the loop) by replacing or escaping '|' (e.g. with '\|') and stripping or replacing line breaks before building the markdown row so each cell is a single-line, pipe-safe string; update the loop that produces lines.push(`| ${col.columnName} | ${col.dataType} | ${nullable} | ${def} |`) to call that sanitizer for columnName, dataType and def (where def comes from col.columnDefault ?? '-') to ensure safe rendering.backend/src/api/routes/metadata/index.routes.ts (1)
179-190: Consider caching this aggregated export.This handler fans out nine service calls (including a full-database
exportDatabase) on every request. For large schemas the payload and latency can grow significantly. Given metadata changes infrequently, a short-lived cache (or ETag/Cache-Control) would reduce load while keeping the admin-only export responsive.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/api/routes/metadata/index.routes.ts` around lines 179 - 190, This handler aggregates nine heavy service calls (authService.getMetadata, dbAdvanceService.exportDatabase, storageService.getMetadata, functionService.getMetadata, realtimeChannelService.getMetadata, databaseService.getSchemas, databaseService.getIndexes, databaseService.getPolicies, databaseService.getTriggers) on every request—add a short-lived cache around this Promise.all call keyed by schemaName (and tenant/user if applicable) with a sensible TTL (e.g., 30–60s) and serve the cached aggregated payload when present; additionally emit/refresh the cache on relevant metadata mutations or set Cache-Control/ETag headers on the route response so clients can revalidate; implement cache retrieval before calling the Promise.all block and cache the result after it completes, and ensure cache invalidation is triggered by schema-changing operations to keep admin export accurate.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@backend/src/api/routes/metadata/index.routes.ts`:
- Around line 179-190: This handler aggregates nine heavy service calls
(authService.getMetadata, dbAdvanceService.exportDatabase,
storageService.getMetadata, functionService.getMetadata,
realtimeChannelService.getMetadata, databaseService.getSchemas,
databaseService.getIndexes, databaseService.getPolicies,
databaseService.getTriggers) on every request—add a short-lived cache around
this Promise.all call keyed by schemaName (and tenant/user if applicable) with a
sensible TTL (e.g., 30–60s) and serve the cached aggregated payload when
present; additionally emit/refresh the cache on relevant metadata mutations or
set Cache-Control/ETag headers on the route response so clients can revalidate;
implement cache retrieval before calling the Promise.all block and cache the
result after it completes, and ensure cache invalidation is triggered by
schema-changing operations to keep admin export accurate.
In `@backend/src/utils/context-formatter.ts`:
- Line 8: Replace the untyped parameter in formatContextAsMarkdown with a
shared, exported interface (e.g., export interface Context) that declares the
exact properties the formatter consumes (for example functions vs dbFunctions,
systemPrompt, userMessage, etc.) and their appropriate types/optionality; change
the function signature to formatContextAsMarkdown(context: Context): string,
update any callers (endpoints and tests) to import and use the Context type, and
adjust property names in the interface to match the concrete fields used by
formatContextAsMarkdown so TypeScript catches any drift like dbFunctions vs
functions.
- Around line 50-59: The table generation in the block that iterates
tableData.schema can break when col.columnName, col.dataType or
col.columnDefault contain pipe characters or newlines; sanitize those cell
values (for example in a small helper used by the loop) by replacing or escaping
'|' (e.g. with '\|') and stripping or replacing line breaks before building the
markdown row so each cell is a single-line, pipe-safe string; update the loop
that produces lines.push(`| ${col.columnName} | ${col.dataType} | ${nullable} |
${def} |`) to call that sanitizer for columnName, dataType and def (where def
comes from col.columnDefault ?? '-') to ensure safe rendering.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 776787fb-8897-4ef6-97c3-dc3436073924
📒 Files selected for processing (3)
backend/src/api/routes/metadata/index.routes.tsbackend/src/utils/context-formatter.tsbackend/tests/unit/context-export.test.ts
There was a problem hiding this comment.
2 issues found across 3 files
Confidence score: 3/5
- There is a concrete user-facing formatting risk in
backend/src/utils/context-formatter.ts: unescaped|characters in Markdown table cells can break table structure, especially forcolumnDefaultSQL expressions, so metadata output may render incorrectly. - There is also functional coverage risk in
backend/src/api/routes/metadata/index.routes.ts:getIndexes,getPolicies, andgetTriggersare fixed to'public'while schemas are discovered broadly, so custom-schema projects may get incomplete metadata. - Given one medium-severity/high-confidence rendering bug plus a schema-scoping inconsistency, this looks mergeable with caution but carries noticeable regression risk.
- Pay close attention to
backend/src/utils/context-formatter.tsandbackend/src/api/routes/metadata/index.routes.ts- Markdown escaping and schema-specific metadata retrieval need validation.
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
- Guard database.data with ?? {} to prevent TypeError on null/undefined
- Remove separate getIndexes/getPolicies/getTriggers calls scoped only to
'public' schema; per-table data from exportDatabase already covers all
schemas consistently
- Escape | and newlines in Markdown table cells to prevent GFM breakage
- Remove duplicate schema-level policy/index/trigger sections; render
indexes and triggers per-table alongside existing FK/RLS/policies
There was a problem hiding this comment.
🧹 Nitpick comments (1)
backend/src/utils/context-formatter.ts (1)
60-111: ⚡ Quick winApply
esc()consistently to interpolated content values.
esc()is used only for the column table cells, but other content-derived fields (foreign keys, policy names/roles, index/trigger names, edge-function descriptions, bucket names) are interpolated raw. A newline in any of these (e.g.f.description) would fragment the surrounding list/section, partly defeating the escaping you just added.♻️ Example for foreign keys / policies / triggers
- `- \`${fk.columnName}\` → \`${fk.foreignTableName}.${fk.foreignColumnName}\`` + `- \`${esc(fk.columnName)}\` → \`${esc(fk.foreignTableName)}.${esc(fk.foreignColumnName)}\``- lines.push(`- \`${p.policyname}\` (${p.cmd}) — roles: ${p.roles}`); + lines.push(`- \`${esc(p.policyname)}\` (${esc(p.cmd)}) — roles: ${esc(p.roles)}`);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/utils/context-formatter.ts` around lines 60 - 111, The code uses esc() for column cells but leaves many interpolated values unescaped, which can break formatting if they contain newlines; update all interpolations that read from tableData to wrap values with esc(), e.g. in the foreign keys loop escape fk.columnName, fk.foreignTableName, fk.foreignColumnName; in policies escape p.policyname, p.cmd and p.roles; in indexes escape idx.indexname (and any flag text if derived from data); in triggers escape t.triggerName, t.actionTiming and t.eventManipulation; and apply the same esc() treatment to other content-derived fields referenced elsewhere (edge/function descriptions, bucket names) so every inserted value is passed through esc() before concatenation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@backend/src/utils/context-formatter.ts`:
- Around line 60-111: The code uses esc() for column cells but leaves many
interpolated values unescaped, which can break formatting if they contain
newlines; update all interpolations that read from tableData to wrap values with
esc(), e.g. in the foreign keys loop escape fk.columnName, fk.foreignTableName,
fk.foreignColumnName; in policies escape p.policyname, p.cmd and p.roles; in
indexes escape idx.indexname (and any flag text if derived from data); in
triggers escape t.triggerName, t.actionTiming and t.eventManipulation; and apply
the same esc() treatment to other content-derived fields referenced elsewhere
(edge/function descriptions, bucket names) so every inserted value is passed
through esc() before concatenation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8cdece6b-1e0c-4bf2-a1e8-8cc7e518523d
📒 Files selected for processing (3)
backend/src/api/routes/metadata/index.routes.tsbackend/src/utils/context-formatter.tsbackend/tests/unit/context-export.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/tests/unit/context-export.test.ts
Escape pipe characters and newlines in all content-derived fields (FK columns, policy names/roles, index names, trigger names, schema names, bucket names, function slugs/descriptions, channel names) not just table cells.
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
… cells Pipe escaping (\|) is only needed inside Markdown table cells. Inline code spans render pipes literally, so escaping them produces a visible backslash. Split sanitization into esc() (table cells: pipes + newlines) and code() (code spans: newlines only).
|
This PR needs discussion first. |
|
@Fermionic-Lyu Sure — happy to discuss. Here's the current approach so we have something concrete to iterate on: Endpoint: What it does: aggregates existing service responses into a single payload — no new DB queries or service logic. Specifically:
All fetched in parallel via Open questions I'd like your input on:
Let me know what you'd like to change — happy to adjust. |
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
After discussion, we don't want to add a new endpoint for this. Instead, we already have a metadata endpoint that returns JSON. Please add a parameter to that existing endpoint so it can return Markdown as well, while keeping JSON as the default response.
Also, please don't disable any ESLint rules.
Per maintainer feedback: instead of a separate /context endpoint, add ?format=markdown to the existing GET /api/metadata/ endpoint. Rewrite formatter to accept AppMetadataSchema, remove eslint-disable, delete the /context route, and clean up unused DatabaseService imports.
|
@Fermionic-Lyu Updated — addressed both points in the latest commit (fa30fac):
The markdown output covers auth, database tables/sizes, storage buckets, edge functions, and realtime channels — exactly what Let me know if you'd like any adjustments to the response shape or which sections to include. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
backend/src/utils/context-formatter.ts (1)
11-16:⚠️ Potential issue | 🟠 Major | ⚡ Quick winBacktick characters in content will break inline code spans.
The
codehelper strips newlines but doesn't escape backticks. If any content (bucket names, function slugs, channel patterns, descriptions) contains backtick characters, the resulting markdown will be malformed. For example, a bucket namedmy`bucketwould produce`my`bucket`, rendering asmy+ plain textbucket+ stray backtick.🛡️ Proposed fix: sanitize backticks
Replace backticks with a safe alternative or use double-backtick delimiters:
/** Strip newlines for inline code spans (pipes are safe inside backticks). */ - const code = (s: unknown) => String(s ?? '').replace(/\n/g, ' '); + const code = (s: unknown) => + String(s ?? '') + .replace(/`/g, '\\`') + .replace(/\n/g, ' ');Alternatively, remove backticks entirely:
- const code = (s: unknown) => String(s ?? '').replace(/\n/g, ' '); + const code = (s: unknown) => + String(s ?? '') + .replace(/`/g, '') + .replace(/\n/g, ' ');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/utils/context-formatter.ts` around lines 11 - 16, The code helper (and esc helper) currently only strips newlines and escapes pipes but does not handle backticks, which can break Markdown inline code spans; update the code(s) that define esc and code to also sanitize backticks (e.g., replace ` with a safe alternative or escaped/backtick-safe form) so bucket names, slugs, patterns and descriptions containing backticks won't produce malformed Markdown; locate the helper functions named esc and code in context-formatter.ts and add backtick sanitization to their transformation pipeline.backend/tests/unit/context-export.test.ts (2)
1-155:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winFix Prettier formatting to unblock CI.
The pipeline is reporting code style issues. Run
npx prettier --write backend/tests/unit/context-export.test.tsto resolve the formatting and pass the lint check.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/tests/unit/context-export.test.ts` around lines 1 - 155, Run the Prettier formatter on the failing test file to fix style issues: execute npx prettier --write backend/tests/unit/context-export.test.ts and commit the updated file; ensure the file still imports and uses formatContextAsMarkdown and the test cases remain unchanged (describe('formatContextAsMarkdown', ...), the sampleMetadata and test assertions) so only formatting changes are applied to satisfy CI.
59-154: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winAdd test coverage for special character escaping.
The formatter includes
esc()andcode()helpers specifically to handle pipes, backticks, and newlines, but there are no tests validating this escaping logic. Consider adding a test case with metadata containing:
- Table names with pipe characters (
|)- Bucket/function names with backticks (
`)- Descriptions with embedded newlines (
\n)This will verify that the markdown output remains well-formed when user content includes special characters.
📝 Example test case
it('escapes special characters in content', () => { const specialChars: AppMetadataSchema = { version: '1.0.0', auth: { oAuthProviders: [], customOAuthProviders: [], smtpConfig: { /* ... */ }, requireEmailVerification: false, disableSignup: false, passwordMinLength: 8, requireNumber: false, requireLowercase: false, requireUppercase: false, requireSpecialChar: false, verifyEmailMethod: 'otp', resetPasswordMethod: 'otp', allowedRedirectUrls: [], }, database: { tables: [{ tableName: 'users|admin', recordCount: 10 }], totalSizeInGB: 0.1, hint: 'Multi\nline\nhint', }, storage: { buckets: [{ name: 'my`bucket', public: true, createdAt: '2026-01-01', objectCount: 5 }], totalSizeInGB: 0.2, }, functions: [{ slug: 'test`func', name: 'test', status: 'active', description: 'Has\nnewlines' }], }; const md = formatContextAsMarkdown(specialChars); // Pipes in table names should be escaped expect(md).toContain('users\\|admin'); // Newlines in hints/descriptions should be replaced with spaces expect(md).toContain('Multi line hint'); expect(md).toContain('Has newlines'); // Backticks should be handled (escaped or removed) expect(md).not.toContain('`my`bucket`'); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/tests/unit/context-export.test.ts` around lines 59 - 154, Add a unit test that verifies the formatter's escaping behavior by constructing an AppMetadataSchema with special characters (pipe in a table name, backticks in bucket/function names, and embedded newlines in descriptions/hints), calling formatContextAsMarkdown, and asserting that pipes are escaped (e.g., 'users\\|admin'), newlines are normalized to spaces (e.g., 'Multi line hint', 'Has newlines'), and backticks do not produce malformed inline code (no extra backticked sequences like '`my`bucket`'); place this test alongside the other tests in backend/tests/unit/context-export.test.ts and reference formatContextAsMarkdown and AppMetadataSchema when building the test data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@backend/src/api/routes/metadata/index.routes.ts`:
- Line 63: Add Zod validation for the request query instead of using
req.query.format directly: import z from 'zod', define a metadataQuerySchema
(e.g., z.object({ format: z.enum(['json','markdown']).optional().default('json')
})), then in the route handler parse/validate req.query with
metadataQuerySchema.parse or safeParse and use the returned value.format when
branching (replacing occurrences of req.query.format === 'markdown'). Also
handle validation errors (return 400) when safeParse fails to enforce type
safety.
---
Outside diff comments:
In `@backend/src/utils/context-formatter.ts`:
- Around line 11-16: The code helper (and esc helper) currently only strips
newlines and escapes pipes but does not handle backticks, which can break
Markdown inline code spans; update the code(s) that define esc and code to also
sanitize backticks (e.g., replace ` with a safe alternative or
escaped/backtick-safe form) so bucket names, slugs, patterns and descriptions
containing backticks won't produce malformed Markdown; locate the helper
functions named esc and code in context-formatter.ts and add backtick
sanitization to their transformation pipeline.
In `@backend/tests/unit/context-export.test.ts`:
- Around line 1-155: Run the Prettier formatter on the failing test file to fix
style issues: execute npx prettier --write
backend/tests/unit/context-export.test.ts and commit the updated file; ensure
the file still imports and uses formatContextAsMarkdown and the test cases
remain unchanged (describe('formatContextAsMarkdown', ...), the sampleMetadata
and test assertions) so only formatting changes are applied to satisfy CI.
- Around line 59-154: Add a unit test that verifies the formatter's escaping
behavior by constructing an AppMetadataSchema with special characters (pipe in a
table name, backticks in bucket/function names, and embedded newlines in
descriptions/hints), calling formatContextAsMarkdown, and asserting that pipes
are escaped (e.g., 'users\\|admin'), newlines are normalized to spaces (e.g.,
'Multi line hint', 'Has newlines'), and backticks do not produce malformed
inline code (no extra backticked sequences like '`my`bucket`'); place this test
alongside the other tests in backend/tests/unit/context-export.test.ts and
reference formatContextAsMarkdown and AppMetadataSchema when building the test
data.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d6e42ae0-14aa-4e17-91d6-d505e5b0eeea
📒 Files selected for processing (3)
backend/src/api/routes/metadata/index.routes.tsbackend/src/utils/context-formatter.tsbackend/tests/unit/context-export.test.ts
- Add Zod schema to validate ?format=json|markdown query parameter, consistent with other route handlers in the codebase - Strip backtick characters in code() helper to prevent malformed inline code spans in Markdown output
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
There was a problem hiding this comment.
2 issues found across 2 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/src/utils/context-formatter.ts">
<violation number="1" location="backend/src/utils/context-formatter.ts:15">
P2: Backticks are destructively removed from metadata values, causing loss/corruption of exported content</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
Match codebase convention: safeParse + AppError(400) instead of parse() which throws unhandled ZodError resulting in 500.
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
Thanks for the iteration. One more contract-level gap that is not anchorable in the diff: openapi/metadata.yaml still documents /api/metadata as JSON-only, with no format query or text/markdown response. Since this PR changes the public metadata API surface, please update the OpenAPI spec too.
|
|
||
| import type { AppMetadataSchema } from '@insforge/shared-schemas'; | ||
|
|
||
| export function formatContextAsMarkdown(metadata: AppMetadataSchema): string { |
There was a problem hiding this comment.
This helper is specific to /api/metadata export, so utils/context-formatter.ts feels too broad. Since there is currently no metadata service, I think this PR should add backend/src/services/metadata/metadata.service.ts and put the metadata aggregation plus JSON/Markdown export selection there. The route can then just validate format and delegate, instead of constructing the JSON shape in the route and importing a generic formatter from utils.
| const { format } = queryValidation.data; | ||
|
|
||
| // Fetch all metadata in parallel for better performance | ||
| const [auth, database, storage, functions, deployments] = await Promise.all([ |
There was a problem hiding this comment.
The Markdown formatter has a Realtime section and the PR summary says realtime is included, but this aggregation never calls realtimeChannelService.getMetadata() or adds realtime to metadata. As written, /api/metadata?format=markdown will never render realtime channels even when they exist.
| .replace(/\|/g, '\\|') | ||
| .replace(/\n/g, ' '); | ||
| /** Strip backticks and newlines for inline code spans. */ | ||
| const code = (s: unknown) => |
There was a problem hiding this comment.
code() currently strips backticks from metadata values, which corrupts exported content rather than escaping it. For example a hint or description containing `auth.uid()` would become auth.uid(), losing the original Markdown/code-span intent. Please make this Markdown-safe without deleting user/content characters, and add a special-character test for it.
| } | ||
| lines.push(''); | ||
|
|
||
| // Realtime |
There was a problem hiding this comment.
The route includes the optional deployments slice in metadata, but this formatter never renders it. Cloud projects would get customSlug in the JSON response and silently lose it in the Markdown response, so the two export formats are not equivalent.
Address maintainer feedback from Fermionic-Lyu: - Move formatter from utils/context-formatter.ts into a new MetadataService singleton (services/metadata/metadata.service.ts) following existing service patterns. Route now validates format and delegates to the service. - Add realtime channels to metadata aggregation (was missing from the Promise.all, so markdown never rendered realtime data). - Add deployments section to markdown output so JSON and markdown formats are equivalent. - Replace backtick-stripping code() helper with codeSpan() that uses double-backtick delimiters when values contain backticks, preserving content like `auth.uid()` instead of corrupting it. - Update OpenAPI spec with format query parameter and text/markdown response documentation. - Add tests for deployments rendering, backtick preservation, and pipe escaping in table cells vs code spans.
|
@Fermionic-Lyu Addressed all five points in 4a40b27:
|
There was a problem hiding this comment.
2 issues found across 5 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/src/services/metadata/metadata.service.ts">
<violation number="1" location="backend/src/services/metadata/metadata.service.ts:83">
P2: Markdown code-span escaping is incomplete for values with consecutive backtick runs</violation>
</file>
<file name="openapi/metadata.yaml">
<violation number="1" location="openapi/metadata.yaml:83">
P2: The /api/metadata endpoint does not document 401 Unauthorized and 403 Forbidden responses in its OpenAPI spec, even though verifyAdmin middleware returns these status codes.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
| if (!str.includes('`')) { | ||
| return `\`${str}\``; | ||
| } | ||
| return `\`\` ${str} \`\``; |
There was a problem hiding this comment.
P2: Markdown code-span escaping is incomplete for values with consecutive backtick runs
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/src/services/metadata/metadata.service.ts, line 83:
<comment>Markdown code-span escaping is incomplete for values with consecutive backtick runs</comment>
<file context>
@@ -0,0 +1,183 @@
+ if (!str.includes('`')) {
+ return `\`${str}\``;
+ }
+ return `\`\` ${str} \`\``;
+ };
+
</file context>
| '400': | ||
| description: Invalid format parameter | ||
| content: | ||
| application/json: | ||
| schema: | ||
| $ref: '#/components/schemas/ErrorResponse' | ||
|
|
There was a problem hiding this comment.
P2: The /api/metadata endpoint does not document 401 Unauthorized and 403 Forbidden responses in its OpenAPI spec, even though verifyAdmin middleware returns these status codes.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At openapi/metadata.yaml, line 83:
<comment>The /api/metadata endpoint does not document 401 Unauthorized and 403 Forbidden responses in its OpenAPI spec, even though verifyAdmin middleware returns these status codes.</comment>
<file context>
@@ -54,6 +69,23 @@ paths:
+ - **OAuth providers**: google, github
+ - **Email verification**: required
+ - **Signup**: enabled
+ '400':
+ description: Invalid format parameter
+ content:
</file context>
| '400': | |
| description: Invalid format parameter | |
| content: | |
| application/json: | |
| schema: | |
| $ref: '#/components/schemas/ErrorResponse' | |
| '400': | |
| description: Invalid format parameter | |
| content: | |
| application/json: | |
| schema: | |
| $ref: '#/components/schemas/ErrorResponse' | |
| '401': | |
| description: Unauthorized | |
| content: | |
| application/json: | |
| schema: | |
| $ref: '#/components/schemas/ErrorResponse' | |
| '403': | |
| description: Forbidden | |
| content: | |
| application/json: | |
| schema: | |
| $ref: '#/components/schemas/ErrorResponse' |
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
Thanks for putting this together. Could you fix these minor issues, and then this should be good to merge.
| /api/metadata: | ||
| get: | ||
| summary: Get app metadata | ||
| description: >- |
There was a problem hiding this comment.
The new description says this endpoint returns aggregated metadata, but the default JSON response schema/example below still documents the old app-health shape (name, environment, uptime, database.host, etc.). The implementation now returns auth, database, storage, functions, optional realtime/deployments, and version, so generated docs/clients will be wrong for the default response. Could you update the JSON schema and example to match AppMetadataSchema?
| if (!str.includes('`')) { | ||
| return `\`${str}\``; | ||
| } | ||
| return `\`\` ${str} \`\``; |
There was a problem hiding this comment.
As cubic noted, this handles single backticks but still breaks values containing a double-backtick run. For example, codeSpan('a``b') returns a code span delimited by and the inner closes it early. Could you choose a delimiter that is one backtick longer than the longest backtick run in the value?
| - **OAuth providers**: google, github | ||
| - **Email verification**: required | ||
| - **Signup**: enabled | ||
| '400': |
There was a problem hiding this comment.
As cubic noted, this endpoint is protected by verifyAdmin, which can return both 401 for missing/invalid credentials and 403 for non-admin JWTs. Could you document those responses alongside the new 400 so the OpenAPI contract matches the middleware behavior?
- Update JSON schema and example in openapi/metadata.yaml to match AppMetadataSchema (auth, database, storage, functions, realtime, deployments, version) instead of the old app-health shape. - Add 401 and 403 error responses to document verifyAdmin behavior. - Fix codeSpan() to choose a delimiter one backtick longer than the longest consecutive backtick run in the value, so double-backtick content like a``b is handled correctly. - Add test for consecutive backtick runs.
|
@Fermionic-Lyu Thanks for the review! All three fixed in 1a4e04e:
Let me know if anything else needs adjusting! |
Summary
Adds
GET /api/metadata/context— a single endpoint that aggregates all project metadata (auth, database schemas/tables/indexes/policies/triggers/functions/views, storage, edge functions, realtime channels) into one response for AI coding tools and developer onboarding.GET /api/metadata/contextGET /api/metadata/context?format=markdownThe endpoint reuses existing service methods (
authService.getMetadata(),dbAdvanceService.exportDatabase(),storageService.getMetadata(), etc.) fetched in parallel viaPromise.all. No new DB queries or service logic introduced.Key details:
verifyAdminmiddleware (admin JWT or API key required)/:tableNamewildcard to avoid conflictstry/catch → next(error)pattern as all existing metadata routesCloses #1429
How did you test this change?
backend/tests/unit/context-export.test.tswith 3 test cases:npm run typecheck— passesnpm run lint— passesnpx prettier --check— passesSummary by cubic
Adds Markdown export to
GET /api/metadatavia a newMetadataService, and removes/api/metadata/context. Validatesformat=json|markdown, includes realtime and optional deployments, and updates OpenAPI with proper schema and 401/403 errors.New Features
GET /api/metadata?format=markdownreturnstext/markdown; charset=utf-8; JSON remains default.MetadataServiceaggregates auth, database (tables, size, hint), storage, edge functions, realtime, and deployments; omits empty sections. JSON now includes arealtimesection.formatparam,text/markdownresponse, JSON schema aligned toAppMetadataSchema, and documented400/401/403responses. Closes [Feature]: Structured agent and developer context export #1429.Bug Fixes
formatwithzod.safeParse; returns 400 on invalid input and defaults tojsonwhen missing.Written for commit 1a4e04e. Summary will update on new commits.
Note
Add Markdown format support to the
GET /api/metadataendpointformatquery parameter (json|markdown, defaultjson) toGET /api/metadata; invalid values return a 400.MetadataServicesingleton that collects data from Auth, Database, Storage, Functions, Realtime, and Deployment services viaPromise.all.MetadataService.formatAsMarkdown()which renders metadata as a structured Markdown document, with a pipe-escaped table for database tables and double-backtick code spans for values containing backticks.realtimesection and conditionally includesdeployments.openapi/metadata.yamlto document the new parameter andtext/markdownresponse schema.Macroscope summarized a37c8e2.
Summary by CodeRabbit
New Features
Tests