Skip to content

feat(context): prepare catalog audit from saved assessment - #1173

Merged
sswiftdrtv merged 5 commits into
mainfrom
cosmo/context-catalog-journey
Nov 16, 2026
Merged

sswiftdrtv merged 5 commits into
mainfrom
cosmo/context-catalog-journey

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add pending, read-only prepare_catalog_audit to HTTP /api/context and the dedicated standard MCP catalog. It prepares an unsaved revision-zero case from one authorized current saved company_onboarding assessment.

  • Copy retained source-version fingerprints; reject missing, foreign, withdrawn or malformed evidence.
  • Preserve the exact summary, input manifest and coverage gaps in an assessment dependent on every selected source.
  • Recheck workspace membership and saved-brief/source availability after asynchronous reads.
  • Exclude delegated OAuth. Preparation performs no persistence, provider call or external action; explicit save_catalog_case, optimistic revisions, idempotent retries and withdrawal readback remain separate and authoritative.

Current source and coordinated fixtures

Final candidate b7bddd14ff1d9e81b4e531ef7e152cf34cc6f728, tree eb30766e807cd79cc0dec4c769ec3af91b5c2a11, parent 5c9bb1a37991af21f1654d77d9a7e95f54c96b9b. This 12-file review-fix successor follows normal merge 549cf08c with ordered parents original 588f4ae and released main 0b1450b3, then the duplicate-import correction 5c9bb1a3. No history rewrite or held typed-error, ingestion or accounting feature integration.

Released freshness, selected-evidence validation, OAuth policy additions and valuation contracts remain preserved. The original Docs producer at 09200d825130c7b2e04f266d5090bcebc341dd50 adds pending labels in the existing discovery tables. The API fixture pair matches its proposal byte-for-byte; both change only the Context source hash, with all request/response schemas, examples, mappings and non-Context values preserved:

  • Context source SHA-256: 10b243ab1098a7428fb935dfb0780ff0f9a1c8885b96feda8e453acff4a1df17
  • context-contract.json: 05235cc4cdf05a51290397526214656a0cc022ce72a01e9dcba76d141c73a81c
  • published-docs.json: 396f1f4354450b263570179ed55fefe50389aa0cb32147ac5b82283021c4b599

The valuation release-source hash remains 0e1239e256b2c1f8f189d81e013f942518619a24214b7c2b7f99baad15de7d3c. Producer --check and independent comparison pass. Runtime request/response/example exports compare exactly with the predecessor.

Review findings and fixes

All 11 Cubic findings on 5c9bb1a3 were assessed; no automated review-thread replies or resolutions were performed.

Finding Disposition
4586985475 Batch both retained metadata lookups at 200 IDs, following the existing catalog pattern; preserve projections, owner/deletion filters, complete-result validation and requested order.
4586985431 Select denial cases by action; explicitly cover both save_catalog_case and prepare_catalog_audit.
4586985449 / 4586985461 Assert intended domain errors or schema-validation errors, and verify injected private storage detail is absent. The changed-brief test reaches the consistency comparison.
4586985482 Reject normalized duplicate IDs within a document before lookup; retain legitimate shared sources across documents and their complete manifest.
4586985493 / 4586985526 Clarify fixed generic scope and a new, unreserved random case UUID on every prepare call.
4586985533 Use catalog metadata for direct delegated denial, preserving the existing error envelope and evidence-operation behavior.
4586985540 Extract pure response assembly/validation; keep reads, rechecks and UUID generation in the orchestrator.
4586985414 / 4586985424 Decline unrelated inventory splitting: the claimed under-100-line rule is absent from the checked repository instructions. Released inventories already contain 767/108 lines; the focused declarative additions do not violate the owning SRP rule. Independently reviewed.

Validation

Local RED→GREEN regressions cover large lookups, reversed results, later-batch failure/completeness checks, private-error redaction, within-document duplicates, shared-source lineage and both denial paths. Initial RED: 6 failed, 93 passed. Corrected focused regressions: 116 passed. No checker weakened.

The repaired implementation passed 9,561 full-suite tests (51 skipped), 1,240 focused tests (8 skipped), and 314 Node 22 OAuth tests (5 skipped). These runs preceded the final fixture source-hash adoption; the final pair then passed all 328 contract tests. A final test-only assertion improvement passed all 21 retained-source tests. Scoped/production/OAuth/response-contract types, lint, formatting and whitespace checks passed. Independent review reran 106 tests, approved the implementation, and bound the final 12-file successor and fixture hashes to the exact head/tree with no new findings.

Exact-head required checks for b7bddd14 all passed: test, compatibility, format, lint, and Cubic completed successfully. Cubic reported one description finding, 4587125102: it compared the new fixture source hash with the predecessor hash in an earlier PR-description snapshot. The current description now states the correct 10b243ab… source and exact 05235cc4… / 396f1f43… fixture pair; readback confirms the predecessor hash is no longer claimed. No source or fixture change was needed. No review-thread reply or resolution was performed. The earlier 11 findings retain the explicit dispositions above; a successful review check alone is not finding-free approval.

Release order and remaining acceptance

  1. Complete and merge Docs contract #15, pinned to final candidate b7bddd14 with paired checks and rendered review qualified.
  2. After coordinator acceptance of the exact-head checks, review dispositions and paired Docs release, merge/deploy this API change.
  3. Release App #2363, then verify the intended account, deployed catalog-case schema and native workflow.

The coordinator retains merge ownership under the standing qualified-merge authorization. No schema migration, provider/customer/account operation, production write or native/browser acceptance occurred in this repair. Preparation alone never saves an audit or verifies rights, ownership, registration, delivery or external execution.

Related: recoupable/app#2116, recoupable/app#2277. This does not close either epic or establish complete catalog diligence/provider integration.

@vercel

vercel Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Nov 16, 2026 2:35pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Solid & Clean Code Warning Verdict: FAIL. The PR head is b7bddd1. The four catalog-audit files flagged by the prior run are new in this PR (git diff against base 60af564 shows status A for validateCatalogAuditBrief.ts, readRe… Make these changes before merge: - Split validateCatalogAuditBrief.ts into a small shape check, a document-ownership check and a manifest-equality check. Keep each function under about 20 lines. - Split readRetainedContextSourceVersions.ts …
Full details: Solid & Clean Code

Explanation

Verdict: FAIL. The PR head is b7bddd1. The four catalog-audit files flagged by the prior run are new in this PR (git diff against base 60af564 shows status A for validateCatalogAuditBrief.ts, readRetainedContextSourceVersions.ts and buildCatalogAuditPreparation.ts). Three findings still match explicit rules in the check. 1. Function length (SRP: "Look for functions longer than 20 lines"): - validateCatalogAuditBrief.ts, function body at lines 5–53 (about 49 lines). It runs the envelope check, brief-shape limits, document ownership checks and manifest equality in one body. - readRetainedContextSourceVersions.ts, function body at lines 19–60 (about 42 lines). It validates input, reads versions, checks integrity, reads sources, checks those and maps the result. - buildCatalogAuditPreparation.ts, function body at lines 5–64 (about 60 lines). It is mostly one object literal. 2. Repeated literal (DRY: "Use constants for repeated values"): the string "Retained Context sources unavailable" is written inline at readRetainedContextSourceVersions.ts lines 35, 42, 48 and 57. No named constant exists. 3. Hardcoded values (DRY: "Use configuration objects instead of hardcoded values"): in buildCatalogAuditPreparation.ts, the source: prefix is inline at lines 25, 27 and 43. The rule version "context-catalog-audit-v1" is inline at line 44. No constant exists. Prior-failure disposition: part of the prior FAIL is resolved. prepareCatalogAudit.ts is now 29 lines, and its snapshot assembly moved into buildCatalogAuditPreparation.ts. I did not re-verify the handleContextToolOperation.ts item. The three function-length findings, the repeated-literal finding and the hardcoded-value finding still hold at b7bddd1. The file-name/function-name match holds for the new files. The processContextOperation.ts size is pre-existing and was not counted. Note on the PR description: it declines to split inventories because of a "under-100-line" rule. That rule is not in the custom check. The check itself sets the 20-line function limit, so the declined split does not address the check's criteria.

Resolution

Make these changes before merge: - Split validateCatalogAuditBrief.ts into a small shape check, a document-ownership check and a manifest-equality check. Keep each function under about 20 lines. - Split readRetainedContextSourceVersions.ts into a version-row read and a source-row read, each with its own integrity check. Move "Retained Context sources unavailable" into one named constant and use it for all four throws. - Reduce buildCatalogAuditPreparation.ts below about 20 lines per function. Move the source-map builder and the assessment builder into helper files named after each function. - Name the "source:" prefix and the "context-catalog-audit-v1" rule version as constants. Use them in buildCatalogAuditPreparation.ts.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 26 files

Confidence score: 5/5

  • scripts/mcp-oauth/tool-policy.json is 776 lines, which makes the policy inventory harder to maintain. Split it into smaller files and update the imports.
  • lib/context/contracts/contextOperationResponseCatalog.ts is 111 lines and exceeds the stated size limit. Split the response catalog into smaller modules.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="scripts/mcp-oauth/tool-policy.json">

<violation number="1" location="scripts/mcp-oauth/tool-policy.json:713">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

`tool-policy.json` is now 776 lines, far beyond Rule 3’s under-100-line limit. Split the inventory into smaller files and update its import and validation path.</violation>
</file>

<file name="lib/context/contracts/contextOperationResponseCatalog.ts">

<violation number="1" location="lib/context/contracts/contextOperationResponseCatalog.ts:30">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This registry is now 111 lines, above Rule 3’s under-100 limit, and this entry extends it further. Split the response catalog into smaller modules.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client as MCP Client / HTTP Client
    participant HTTP as HTTP /api/context
    participant MCP as MCP Server
    participant Auth as Auth & Ownership
    participant Handler as processContextOperation
    participant Prep as prepareCatalogAudit
    participant Validator as validateCatalogAuditBrief
    participant RPC as Supabase RPC
    participant Sources as Retained Sources

    Note over Client,Sources: NEW: Catalog Audit Preparation Flow (read-only, non-persisting)

    alt HTTP Transport
        Client->>HTTP: POST /api/context - prepare_catalog_audit(brief_id, organization_id?)
        HTTP->>Auth: Authenticate request
        Auth-->>HTTP: account_id
        HTTP->>Handler: Route to prepare_catalog_audit
    else MCP Transport
        Client->>MCP: prepare_catalog_audit(brief_id, organization_id?)
        MCP->>Handler: Route via context tool
    end

    Note over Handler: Input schema: action, brief_id required, organization_id optional
    Note over MCP: Annotations: readOnlyHint, openWorldHint=false, destructiveHint=false

    Handler->>Auth: authorizeContextOwner(actor, brief_id, organization_id)
    Auth-->>Handler: owner_id

    Handler->>Prep: prepareCatalogAudit(owner_id, brief_id, rpc, recheckOwner)

    Note over Prep: Phase 1: Read saved brief (first read)

    Prep->>RPC: read_context_brief(owner, brief_id)
    RPC-->>Prep: raw saved brief

    Prep->>Auth: recheckOwner() - verify membership unchanged
    Auth-->>Prep: ok

    Prep->>Validator: validate read snapshot
    Note over Validator: Checks: state=saved, not superseded,<br/>purpose=company_onboarding,<br/>documents present (1-256),<br/>text valid, request_ids valid,<br/>manifest matches, owner matches
    Validator-->>Prep: valid snapshot

    Note over Prep: Phase 2: Load exact source fingerprints

    Prep->>Prep: Collect unique sourceVersionIds from documents

    Prep->>Sources: readRetainedContextSourceVersions(owner_id, version_ids)
    Note over Sources: Queries context_source_versions + context_sources,<br/>metadata only, owner-bound, non-removed/withdrawn,<br/>exact fingerprint match required

    alt All sources available
        Sources-->>Prep: [{id, fingerprint}] - exact matches only
    else Missing/foreign/withdrawn/malformed source
        Sources-->>Prep: Error - fail closed
        Prep-->>Handler: Throw: "Retained Context sources unavailable"
    end

    Note over Prep: Phase 3: Re-read and verify unchanged

    Prep->>RPC: read_context_brief(owner, brief_id) - second read
    RPC-->>Prep: current raw saved brief

    Prep->>Auth: recheckOwner() - verify membership still valid
    Auth-->>Prep: ok

    Prep->>Validator: Validate current snapshot
    Validator-->>Prep: valid snapshot

    alt Evidence changed during preparation
        Prep->>Prep: Compare saved vs current (JSON.stringify)
        Prep-->>Handler: Throw: "evidence changed during preparation"
    else Evidence unchanged
        Prep->>Prep: Build revision-0 snapshot
        Note over Prep: Creates: case_id (new UUID), revision=0,<br/>sources (with sha256 fingerprints),<br/>assessment:context (stage=audit, status=partial,<br/>summary, source_refs, input_manifest, gaps)
    end

    Prep-->>Handler: { state: "prepared", persisted: false, external_actions: "unsupported", snapshot }

    opt Save flow (separate explicit call)
        Client->>Handler: save_catalog_case(case_id, expected_revision=0, idempotency_key)
        Note over Handler: Existing save flow - not changed by this PR
    end

    Note over Client,Prep: Failure masking
    alt Storage error
        Handler->>Handler: Mask error: "Could not complete... No catalog case was saved"
        Handler-->>Client: 409 - generic guidance, no sensitive details
    end

    Note over Handler: Delegated OAuth exclusion
    alt OAuth delegated request
        MCP->>Client: Error: "Catalog case operations are unavailable for delegated OAuth"
    end
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@@ -709,6 +709,15 @@
"status": "full OAuth permission; production generation feature gated",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

tool-policy.json is now 776 lines, far beyond Rule 3’s under-100-line limit. Split the inventory into smaller files and update its import and validation path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At scripts/mcp-oauth/tool-policy.json, line 713:

<comment>`tool-policy.json` is now 776 lines, far beyond Rule 3’s under-100-line limit. Split the inventory into smaller files and update its import and validation path.</comment>

<file context>
@@ -709,6 +709,15 @@
     "authorizationWork": "Import only explicitly selected attachment bytes or signed download URLs into the authorized private workspace. Enforce DNS, redirects, byte and MIME bounds; bind signed upload finalization to the owner and never export account OAuth credentials or read unrelated files."
   },
+  {
+    "name": "prepare_catalog_audit",
+    "file": "lib/mcp/tools/context/registerCatalogCaseTools.ts",
+    "scopes": [
</file context>


/** Source-described responses only: this registry is not runtime validation or permission. */
export const contextResponseSchemas = {
catalogAuditPreparation: catalogAuditPreparationResponseSchema,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This registry is now 111 lines, above Rule 3’s under-100 limit, and this entry extends it further. Split the response catalog into smaller modules.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/contracts/contextOperationResponseCatalog.ts, line 30:

<comment>This registry is now 111 lines, above Rule 3’s under-100 limit, and this entry extends it further. Split the response catalog into smaller modules.</comment>

<file context>
@@ -26,6 +27,7 @@ import {
 
 /** Source-described responses only: this registry is not runtime validation or permission. */
 export const contextResponseSchemas = {
+  catalogAuditPreparation: catalogAuditPreparationResponseSchema,
   catalogCase: catalogCaseReceiptSchema,
   catalogCases: catalogCasePageSchema,
</file context>

Comment thread lib/context/README.md Resolved
Comment thread lib/context/README.md Resolved
Comment thread lib/context/prepareCatalogAudit.ts Resolved

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 12 files (changes from recent commits).

Confidence score: 4/5

  • The provenance hash in the PR description doesn’t match the hash committed in lib/contracts/fixtures/published-docs.json. Update the claim to 10b243ab….
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/contracts/fixtures/published-docs.json">

<violation number="1" location="lib/contracts/fixtures/published-docs.json:1238">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**

The committed Context source hash is `10b243ab…`, not the `8cc1c245…` reported in the PR description. Update the provenance claim to the hash pinned by both fixtures, or regenerate the fixtures from the claimed source.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

"content/docs/source/api-reference/openapi/releases.json": "0e1239e256b2c1f8f189d81e013f942518619a24214b7c2b7f99baad15de7d3c",
"content/docs/source/api-reference/openapi/social.json": "5bd167a78cf6a17c46724486e2921882be20969ea32f3c0297f5b7e7ba9a30aa",
"content/docs/source/api-reference/openapi/context.json": "7784ee1d8c4b6753cc47bf518f468effa58d50fb9d0289009edf0caad3d05a67",
"content/docs/source/api-reference/openapi/context.json": "10b243ab1098a7428fb935dfb0780ff0f9a1c8885b96feda8e453acff4a1df17",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Custom agent: Flag AI Slop and Fabricated Changes

The committed Context source hash is 10b243ab…, not the 8cc1c245… reported in the PR description. Update the provenance claim to the hash pinned by both fixtures, or regenerate the fixtures from the claimed source.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/contracts/fixtures/published-docs.json, line 1238:

<comment>The committed Context source hash is `10b243ab…`, not the `8cc1c245…` reported in the PR description. Update the provenance claim to the hash pinned by both fixtures, or regenerate the fixtures from the claimed source.</comment>

<file context>
@@ -1235,7 +1235,7 @@
     "content/docs/source/api-reference/openapi/releases.json": "0e1239e256b2c1f8f189d81e013f942518619a24214b7c2b7f99baad15de7d3c",
     "content/docs/source/api-reference/openapi/social.json": "5bd167a78cf6a17c46724486e2921882be20969ea32f3c0297f5b7e7ba9a30aa",
-    "content/docs/source/api-reference/openapi/context.json": "8cc1c245e714e22399f035b851f1c97798bd72839be567e4379bbc2493425266",
+    "content/docs/source/api-reference/openapi/context.json": "10b243ab1098a7428fb935dfb0780ff0f9a1c8885b96feda8e453acff4a1df17",
     "content/docs/source/api-reference/openapi/projects.json": "b059cf8baa83a7f73a3c15db19f54fa56e46a3840e91bd42979b83550f543ace",
     "content/docs/source/api-reference/openapi/sessions.json": "85af56cc150374b28c25541c45db15849c71fdeb6288cf90dc2beb08f494e83e",
</file context>

@sswiftdrtv
sswiftdrtv merged commit 486d32e into main Nov 16, 2026
7 checks passed

This branch was successfully deployed

1 active deployment
Preview — b7bddd14 Deployed Nov 16, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants