Skip to content

feat(metadata): add structured context export endpoint - #1457

Merged
Fermionic-Lyu merged 12 commits into
InsForge:mainfrom
eunseo9311:feat/structured-context-export
Jun 10, 2026
Merged

Fermionic-Lyu merged 12 commits into
InsForge:mainfrom
eunseo9311:feat/structured-context-export

Conversation

@eunseo9311

@eunseo9311 eunseo9311 commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • JSON (default): GET /api/metadata/context
  • Markdown: GET /api/metadata/context?format=markdown

The endpoint reuses existing service methods (authService.getMetadata(), dbAdvanceService.exportDatabase(), storageService.getMetadata(), etc.) fetched in parallel via Promise.all. No new DB queries or service logic introduced.

Key details:

  • Protected by verifyAdmin middleware (admin JWT or API key required)
  • Route registered before the /:tableName wildcard to avoid conflicts
  • Error handling follows the same try/catch → next(error) pattern as all existing metadata routes
  • Markdown formatter is a pure function with no side effects, tested independently

Closes #1429

How did you test this change?

  • Added backend/tests/unit/context-export.test.ts with 3 test cases:
    1. Full context with all sections (auth, tables, FK, RLS, indexes, triggers, DB functions, views, storage, edge functions, realtime)
    2. Empty/null sections handled gracefully — no null pointer errors
    3. Tables with no foreign keys or policies render correctly
  • npm run typecheck — passes
  • npm run lint — passes
  • npx prettier --check — passes
  • Full test suite: 105 files passed, 1253 tests, 0 failures

Summary by cubic

Adds Markdown export to GET /api/metadata via a new MetadataService, and removes /api/metadata/context. Validates format=json|markdown, includes realtime and optional deployments, and updates OpenAPI with proper schema and 401/403 errors.

  • New Features

    • GET /api/metadata?format=markdown returns text/markdown; charset=utf-8; JSON remains default.
    • MetadataService aggregates auth, database (tables, size, hint), storage, edge functions, realtime, and deployments; omits empty sections. JSON now includes a realtime section.
    • OpenAPI updated with format param, text/markdown response, JSON schema aligned to AppMetadataSchema, and documented 400/401/403 responses. Closes [Feature]: Structured agent and developer context export #1429.
    • Unit tests cover minimal/full payloads, hint, deployments, backticks (including consecutive runs), and pipe escaping.
  • Bug Fixes

    • Validates format with zod.safeParse; returns 400 on invalid input and defaults to json when missing.
    • Markdown sanitization: code spans use a fence longer than the longest backtick run to preserve content; escapes pipes only in table cells.

Written for commit 1a4e04e. Summary will update on new commits.

Review in cubic

Note

Add Markdown format support to the GET /api/metadata endpoint

  • Adds a format query parameter (json | markdown, default json) to GET /api/metadata; invalid values return a 400.
  • Extracts metadata aggregation into a new MetadataService singleton that collects data from Auth, Database, Storage, Functions, Realtime, and Deployment services via Promise.all.
  • Adds 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.
  • The JSON response now includes a realtime section and conditionally includes deployments.
  • Updates the OpenAPI spec in openapi/metadata.yaml to document the new parameter and text/markdown response schema.

Macroscope summarized a37c8e2.

Summary by CodeRabbit

  • New Features

    • Admin-only metadata export now supports a human-readable Markdown format via a query parameter, showing Project Metadata with sections for Auth, Database, Storage, Edge Functions, and Realtime, including explicit "none configured" fallbacks.
  • Tests

    • Added unit tests validating Markdown output, section contents, hints, and fallback behavior when subsystems are absent.

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.
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds formatContextAsMarkdown, updates the admin GET / metadata route to return Markdown when ?format=markdown, and adds unit tests validating full and fallback Markdown outputs.

Changes

Project Metadata Export

Layer / File(s) Summary
Markdown formatter for metadata
backend/src/utils/context-formatter.ts
Adds formatContextAsMarkdown(metadata: AppMetadataSchema): string that builds a Markdown "Project Metadata" document with conditional sections for Auth, Database, Storage, Edge Functions, and Realtime, including escaping and fallback messages.
GET / metadata route markdown branch
backend/src/api/routes/metadata/index.routes.ts
Imports formatContextAsMarkdown and, in the existing admin GET / handler, returns text/markdown; charset=utf-8 with the formatted Markdown when req.query.format === 'markdown'; otherwise returns JSON via successResponse.
Formatter unit tests
backend/tests/unit/context-export.test.ts
Vitest suite asserting the formatter's output for a full sample metadata object, verifying fallback messages for empty storage/functions, omitting Realtime when undefined, and including database.hint when present.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I hopped through headers, buckets, tables, and more,
I penned the project's story in Markdown lore.
Providers, rows, functions, channels in line,
A rabbit's small export, neat and fine.
Copy, paste, share — the context aligns.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive The PR addresses core requirements from #1429 (JSON/Markdown export, metadata aggregation) but implementation gaps exist: no environment redaction, no per-environment exports, no timestamp/freshness metadata, and no explicit per-environment scoping. Verify whether secret redaction, per-environment exports, and timestamp metadata are intentionally deferred or should be implemented. Clarify scope alignment with issue #1429 requirements.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(metadata): add structured context export endpoint' directly summarizes the main change: adding an endpoint for structured context export.
Out of Scope Changes check ✅ Passed All changes directly support the context export feature: metadata endpoint enhancement, Markdown formatter implementation, and comprehensive unit tests.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@agent-zhang-beihai agent-zhang-beihai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (from exportDatabase) is rendered under #### tableName.
  • Schema-level: db.policies (from getPolicies('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.all for parallel fetches — correct and efficient.
  • Route registration before /:tableName wildcard — correct placement.
  • formatContextAsMarkdown is 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-apps

greptile-apps Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Refactors the GET /api/metadata endpoint to support a ?format=markdown query parameter by introducing a new MetadataService singleton that aggregates metadata from all sub-services (auth, database, storage, functions, realtime, deployments) in parallel. The Markdown formatter handles pipe-escaping in table cells and backtick-safe code spans correctly.

  • MetadataService centralises aggregation and Markdown rendering; realtime channels are now correctly fetched via realtimeChannelService.getMetadata(), resolving the previously noted gap.
  • Route handler validates format with zod ('json' | 'markdown', default 'json'); invalid values return 400; the /:tableName wildcard is unaffected since the new logic is on /.
  • OpenAPI spec updated with the format parameter, text/markdown response, and accurate 200 schema; 400/401/403 errors documented.

Confidence Score: 5/5

Safe 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

Filename Overview
backend/src/services/metadata/metadata.service.ts New singleton service aggregating metadata from all sub-services and formatting as Markdown; realtime channels now correctly fetched; pipe-escaping and backtick-safe code spans implemented; minor inconsistency between Storage and other sections on "no data" rendering
backend/src/api/routes/metadata/index.routes.ts Route refactored to delegate aggregation to MetadataService; zod validation on format param is correct; conditional markdown/JSON response path is clean; all sub-service instances still used for individual sub-routes
backend/tests/unit/context-export.test.ts Comprehensive formatter unit tests covering full metadata, empty sections, hints, deployments, backtick escaping, and pipe escaping; no integration tests for the HTTP handler but formatter is the main logic surface
openapi/metadata.yaml OpenAPI spec updated with format query param, text/markdown response, and corrected 200 schema to match the new AppMetadataSchema shape; 400/401/403 error responses documented

Sequence Diagram

sequenceDiagram
    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
Loading

Reviews (9): Last reviewed commit: "fix(metadata): update OpenAPI schema, ha..." | Re-trigger Greptile

Comment thread backend/src/utils/context-formatter.ts Resolved
Comment thread backend/src/utils/context-formatter.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
backend/src/utils/context-formatter.ts (2)

8-8: ⚖️ Poor tradeoff

Consider 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., dbFunctions vs functions) 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 value

Unescaped | in Markdown table cells can break rendering.

columnDefault, dataType, or columnName values 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

📥 Commits

Reviewing files that changed from the base of the PR and between b9eb95b and dd437e8.

📒 Files selected for processing (3)
  • backend/src/api/routes/metadata/index.routes.ts
  • backend/src/utils/context-formatter.ts
  • backend/tests/unit/context-export.test.ts

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 for columnDefault SQL expressions, so metadata output may render incorrectly.
  • There is also functional coverage risk in backend/src/api/routes/metadata/index.routes.ts: getIndexes, getPolicies, and getTriggers are 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.ts and backend/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

Comment thread backend/src/utils/context-formatter.ts Resolved
- 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
backend/src/utils/context-formatter.ts (1)

60-111: ⚡ Quick win

Apply 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

📥 Commits

Reviewing files that changed from the base of the PR and between dd437e8 and d2d6f9d.

📒 Files selected for processing (3)
  • backend/src/api/routes/metadata/index.routes.ts
  • backend/src/utils/context-formatter.ts
  • backend/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.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread backend/src/utils/context-formatter.ts Resolved
… 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).
@Fermionic-Lyu

Copy link
Copy Markdown
Member

This PR needs discussion first.

@eunseo9311

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Sure — happy to discuss. Here's the current approach so we have something concrete to iterate on:

Endpoint: GET /api/metadata/context?format=json|markdown
Auth: behind existing verifyAdmin middleware (admin JWT or API key)

What it does: aggregates existing service responses into a single payload — no new DB queries or service logic. Specifically:

Data Source
Auth (OAuth providers, email verification, signup) authService.getMetadata()
Database (schemas, tables/columns/FK/RLS/policies/indexes/triggers, functions, views) dbAdvanceService.exportDatabase() + databaseService.getSchemas()
Storage (buckets, total size) storageService.getMetadata()
Edge Functions (slug, status, description) functionService.getMetadata()
Realtime (channels) realtimeChannelService.getMetadata()

All fetched in parallel via Promise.all. The Markdown formatter is a pure function with no side effects.

Open questions I'd like your input on:

  1. Should the response schema be different? (e.g., fewer/more sections, different nesting)
  2. Any concerns about exposing DB function source or trigger definitions to admin users?
  3. Should there be a schema query param to scope beyond the default export, or is the current behavior fine for v1?

Let me know what you'd like to change — happy to adjust.

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@eunseo9311

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Updated — addressed both points in the latest commit (fa30fac):

  1. No new endpoint. Removed /context entirely. Added ?format=markdown to the existing GET /api/metadata/ instead. JSON remains the default — zero breaking change.
  2. No ESLint disables. The formatter now accepts the typed AppMetadataSchema directly.

The markdown output covers auth, database tables/sizes, storage buckets, edge functions, and realtime channels — exactly what GET / already returns, just rendered as markdown.

Let me know if you'd like any adjustments to the response shape or which sections to include.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Backtick characters in content will break inline code spans.

The code helper 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 named my`bucket would produce `my`bucket`, rendering as my + plain text bucket + 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 win

Fix Prettier formatting to unblock CI.

The pipeline is reporting code style issues. Run npx prettier --write backend/tests/unit/context-export.test.ts to 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 win

Add test coverage for special character escaping.

The formatter includes esc() and code() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 42a264c and fa30fac.

📒 Files selected for processing (3)
  • backend/src/api/routes/metadata/index.routes.ts
  • backend/src/utils/context-formatter.ts
  • backend/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
@greptile-apps

greptile-apps Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread backend/src/utils/context-formatter.ts Resolved
Match codebase convention: safeParse + AppError(400) instead of
parse() which throws unhandled ZodError resulting in 500.

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/src/utils/context-formatter.ts Outdated

import type { AppMetadataSchema } from '@insforge/shared-schemas';

export function formatContextAsMarkdown(metadata: AppMetadataSchema): string {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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([

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/src/utils/context-formatter.ts Outdated
.replace(/\|/g, '\\|')
.replace(/\n/g, ' ');
/** Strip backticks and newlines for inline code spans. */
const code = (s: unknown) =>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/src/utils/context-formatter.ts Outdated
}
lines.push('');

// Realtime

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@eunseo9311

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Addressed all five points in 4a40b27:

  1. MetadataService — Moved aggregation + formatter into backend/src/services/metadata/metadata.service.ts (standard singleton pattern). Route now validates format and delegates to metadataService.getAppMetadata() / metadataService.formatAsMarkdown(). Deleted utils/context-formatter.ts.

  2. Realtime missing — Added realtimeChannelService.getMetadata() to the Promise.all in getAppMetadata(). Markdown now renders realtime channels when present.

  3. Backtick corruption — Replaced the backtick-stripping code() with codeSpan() that uses double-backtick delimiters (`` value ``) when the value contains backticks. Content like `auth.uid()` is preserved. Added a dedicated test.

  4. Deployments not rendered — Added a ## Deployments section showing customSlug (or "not set" for null). JSON and Markdown are now equivalent. Added tests for both slug-present and null-slug cases.

  5. OpenAPI spec — Added format query parameter (json/markdown, default json), text/markdown response content type, and 400 error response to openapi/metadata.yaml.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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} \`\``;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Comment thread openapi/metadata.yaml
Comment on lines +83 to 89
'400':
description: Invalid format parameter
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
'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'

@eunseo9311
eunseo9311 requested a review from Fermionic-Lyu June 8, 2026 06:18

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this together. Could you fix these minor issues, and then this should be good to merge.

Comment thread openapi/metadata.yaml
/api/metadata:
get:
summary: Get app metadata
description: >-

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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} \`\``;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread openapi/metadata.yaml
- **OAuth providers**: google, github
- **Email verification**: required
- **Signup**: enabled
'400':

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@eunseo9311

eunseo9311 commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Thanks for the review! All three fixed in 1a4e04e:

  1. OpenAPI JSON schema — Good catch, the old app-health shape was stale. Updated to match AppMetadataSchema (auth, database.tables, storage.buckets, functions, realtime, deployments, version) with a matching example.
  2. codeSpan() — Makes sense. Now it finds the longest consecutive backtick run and uses a delimiter one longer, so even a``b renders correctly. Added a test for it.
  3. 401/403 — Added both alongside the new 400.

Let me know if anything else needs adjusting!

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@Fermionic-Lyu
Fermionic-Lyu merged commit 1fc5c83 into InsForge:main Jun 10, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Structured agent and developer context export

2 participants