openapi: 3.1.0 info: # Do not change the title, if the title changes, the import paths will be broken title: Api version: 0.1.0 description: CS Rescue API specification servers: - url: /api description: Base API path tags: - name: health description: Health operations - name: architecture description: Architecture nodes and diagram - name: resources description: System resources and integrations - name: connectors description: Connector registry and configuration - name: deployments description: Customer deployments and rollouts - name: accounts description: Customer accounts - name: lifecycle description: Lifecycle motions - name: portfolio description: PE-firm tenant portfolio bootstrap data - name: Auth description: Browser and mobile authentication endpoints. paths: /healthz: get: operationId: healthCheck tags: [health] summary: Health check responses: "200": description: Healthy content: application/json: schema: $ref: "#/components/schemas/HealthStatus" /architecture: get: operationId: getArchitecture tags: [architecture] summary: Get full architecture map responses: "200": description: Full architecture data content: application/json: schema: $ref: "#/components/schemas/ArchitectureMap" /graph: get: operationId: getGraph tags: [architecture] summary: Get the full architecture graph (nodes + edges + groups) responses: "200": description: Graph data for visualization content: application/json: schema: $ref: "#/components/schemas/GraphData" /edges: get: operationId: listEdges tags: [architecture] summary: List all architecture edges responses: "200": description: List of edges content: application/json: schema: type: array items: $ref: "#/components/schemas/ArchitectureEdge" /metrics/{nodeId}: get: operationId: getNodeMetrics tags: [architecture] summary: Get time-series metrics for a node parameters: - name: nodeId in: path required: true schema: type: string responses: "200": description: List of metric series for the node content: application/json: schema: type: array items: $ref: "#/components/schemas/NodeMetricSeries" /architecture/nodes: get: operationId: listArchitectureNodes tags: [architecture] summary: List all architecture nodes parameters: - name: layer in: query schema: type: string enum: [lifecycle, delivery, platform] - name: lifecycleMotionId in: query schema: type: string responses: "200": description: List of nodes content: application/json: schema: type: array items: $ref: "#/components/schemas/ArchitectureNode" /architecture/nodes/{id}: get: operationId: getArchitectureNode tags: [architecture] summary: Get a specific architecture node parameters: - name: id in: path required: true schema: type: string responses: "200": description: Node detail content: application/json: schema: $ref: "#/components/schemas/ArchitectureNode" "404": description: Not found /architecture/summary: get: operationId: getArchitectureSummary tags: [architecture] summary: Get architecture summary stats responses: "200": description: Summary statistics content: application/json: schema: $ref: "#/components/schemas/ArchitectureSummary" /resources: get: operationId: listResources tags: [resources] summary: List all resources parameters: - name: category in: query schema: type: string - name: status in: query schema: type: string responses: "200": description: List of resources content: application/json: schema: type: array items: $ref: "#/components/schemas/Resource" post: operationId: createResource tags: [resources] summary: Create a new resource requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/NewResourceInput" responses: "201": description: Created resource content: application/json: schema: $ref: "#/components/schemas/Resource" /resources/{id}: get: operationId: getResource tags: [resources] summary: Get a resource by ID parameters: - name: id in: path required: true schema: type: string responses: "200": description: Resource detail content: application/json: schema: $ref: "#/components/schemas/Resource" "404": description: Not found patch: operationId: updateResource tags: [resources] summary: Update a resource parameters: - name: id in: path required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PatchResourceInput" responses: "200": description: Updated resource content: application/json: schema: $ref: "#/components/schemas/Resource" /connectors: get: operationId: listConnectors tags: [connectors] summary: List all connectors responses: "200": description: List of connectors content: application/json: schema: type: array items: $ref: "#/components/schemas/Connector" post: operationId: createConnector tags: [connectors] summary: Register a new connector requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/NewConnectorInput" responses: "201": description: Created connector content: application/json: schema: $ref: "#/components/schemas/Connector" /connectors/{id}: patch: operationId: updateConnector tags: [connectors] summary: Update a connector parameters: - name: id in: path required: true schema: type: string requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PatchConnectorInput" responses: "200": description: Updated connector content: application/json: schema: $ref: "#/components/schemas/Connector" /connectors/health: get: operationId: getConnectorHealth tags: [connectors] summary: Get health status of all connectors responses: "200": description: Connector health overview content: application/json: schema: $ref: "#/components/schemas/ConnectorHealthSummary" /deployments: get: operationId: listDeployments tags: [deployments] summary: List all deployments parameters: - name: accountId in: query schema: type: string - name: stage in: query schema: type: string responses: "200": description: List of deployments content: application/json: schema: type: array items: $ref: "#/components/schemas/Deployment" /deployments/{id}: get: operationId: getDeployment tags: [deployments] summary: Get a deployment by ID parameters: - name: id in: path required: true schema: type: string responses: "200": description: Deployment detail content: application/json: schema: $ref: "#/components/schemas/Deployment" "404": description: Not found /accounts: get: operationId: listAccounts tags: [accounts] summary: List all accounts responses: "200": description: List of accounts content: application/json: schema: type: array items: $ref: "#/components/schemas/Account" /lifecycle-motions: get: operationId: listLifecycleMotions tags: [lifecycle] summary: List all lifecycle motions responses: "200": description: List of lifecycle motions content: application/json: schema: type: array items: $ref: "#/components/schemas/LifecycleMotion" /portfolio/bootstrap: get: operationId: getPortfolioBootstrap tags: [portfolio] summary: Get raw portfolio bootstrap data for all firm tenants description: > Serves RAW company/assessment data sourced from Postgres — no derived values (tiers, composites, gaps, etc). Clients re-derive those via @workspace/portfolio-engine. Returns 500 if the underlying data fails validation at load time (fail-soft: never crashes the server). responses: "200": description: Raw portfolio bootstrap payload content: application/json: schema: $ref: "#/components/schemas/PortfolioBootstrap" "500": description: Portfolio data failed validation and could not be served content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /portfolio/raviga/signals: get: operationId: getRavigaSignals tags: [portfolio] summary: Structured diagnostic signals for the Raviga sandbox tenant description: > Returns the structured per-pillar evidence signal records captured during pipeline scoring for every Raviga company, as a flat list keyed by companySlug + pillarId (clients group as needed). Raviga-only demo surface: no other firm slug has this route, so every other tenant 404s. Signals are evidence metadata only and never participate in composite/tier/denominator math. responses: "200": description: Flat list of Raviga signal records content: application/json: schema: $ref: "#/components/schemas/RavigaSignals" "404": description: Raviga firm row not present in the database content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "500": description: Failed to load signals content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms: get: operationId: listAdminFirms tags: [admin] summary: List all firms with company counts, for the internal admin index responses: "200": description: All firms content: application/json: schema: type: array items: $ref: "#/components/schemas/AdminFirmSummary" post: operationId: createAdminFirm tags: [admin] summary: Create a new firm (status "pending") and queue a discovery job description: > Landing step of the internal /admin firm-onboarding flow. Creates a firm row with status "pending" and a matching jobs row (type "discovery", status "queued") targeting that firm. The job is a stub — nothing actually runs discovery yet. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminFirmInput" responses: "201": description: Created firm and queued discovery job content: application/json: schema: $ref: "#/components/schemas/CreateAdminFirmResponse" "400": description: Invalid input content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/order: put: operationId: reorderAdminFirms tags: [admin] summary: Persist a custom display order for firms description: > Admin-only. Accepts the full ordered list of firm ids and writes each firm's sort_order to its index in the array (transactional). Firms not included keep a null sort_order and list after ordered firms. The order applies to every admin firm listing (GET /admin/firms sorts by sort_order NULLS LAST, then id). requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ReorderAdminFirmsInput" responses: "200": description: Order persisted content: application/json: schema: $ref: "#/components/schemas/OkResult" "400": description: Invalid input (unknown or duplicate firm ids) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/manual: post: operationId: createManualAdminFirm tags: [admin] summary: Create a firm record directly, without the AI discovery pipeline description: > Admin-only. Creates a firm row in "pending" status with portal meta (statusLabel, internalOnly) and NO discovery job. Companies and diagnostics can be added later via the firm review screen's guided company entry or by running discovery from there. Slug must be lowercase kebab-case, unique, and not a reserved route word. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateManualAdminFirmInput" responses: "201": description: Created firm content: application/json: schema: $ref: "#/components/schemas/Firm" "400": description: Invalid input (bad slug format or reserved slug) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "409": description: A firm with this slug already exists content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/{id}: get: operationId: getAdminFirm tags: [admin] summary: Get a firm and its companies, for the review screen parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Firm detail with companies content: application/json: schema: $ref: "#/components/schemas/AdminFirmDetail" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" patch: operationId: updateAdminFirm tags: [admin] summary: Update a firm's dataAuthority and/or portal meta (admin toggle) description: > Admin-only. Promotes dataAuthority (best_effort to strict) and/or updates portal meta (statusLabel, internalOnly, requireLogin). Invalidates the server-side portfolio bootstrap cache so meta/requireLogin changes take effect on the next tenant load. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminFirmInput" responses: "200": description: Updated firm content: application/json: schema: $ref: "#/components/schemas/Firm" "400": description: Invalid input content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" delete: operationId: deleteAdminFirm tags: [admin] summary: Permanently delete a firm and all of its data description: > Admin-only, irreversible. Cascades in FK-safe order through report validations, drive shipments, report revisions, Notion sync state, report exports, findings, assessments, companies, jobs, and ingestion sources before removing the firm row, all in one transaction. Rejected (409) for the 5 hand-authored legacy tenants (their identity lives in the static frontend registry) and for firms with a queued or running job. Invalidates the portfolio bootstrap cache so the tenant portal disappears immediately. parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Firm deleted content: application/json: schema: $ref: "#/components/schemas/DeleteAdminFirmResult" "400": description: Invalid firm id content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "409": description: Firm is a protected legacy tenant or has an active job content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/{id}/clearance: post: operationId: setAdminFirmClearance tags: [admin] summary: Flip a firm's clearance (internalOnly) with admin password verification description: > Admin-only. Verifies the supplied password against CLEARANCE_ADMIN_PASSWORD server-side, then merges the new internalOnly value into firm.meta, and invalidates the portfolio bootstrap cache. 401 on wrong password; 503 if CLEARANCE_ADMIN_PASSWORD is not configured on the server. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SetFirmClearanceInput" responses: "200": description: Updated firm content: application/json: schema: $ref: "#/components/schemas/Firm" "400": description: Invalid input content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": description: Wrong clearance password content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "503": description: CLEARANCE_ADMIN_PASSWORD not configured content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/{id}/companies: post: operationId: addAdminFirmCompany tags: [admin] summary: Add a company to a firm under review parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/AddAdminCompanyInput" responses: "201": description: Company added to the firm content: application/json: schema: $ref: "#/components/schemas/Company" "400": description: Invalid input content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/firms/{id}/confirm: post: operationId: confirmAdminFirm tags: [admin] summary: Confirm the reviewed company selection and queue a build job description: > Marks the selected companies "active" and any unselected companies "excluded", sets the firm's status to "reviewed", and queues a stub jobs row (type "build", status "queued") targeting the firm. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ConfirmAdminFirmInput" responses: "200": description: Firm confirmed and build job queued content: application/json: schema: $ref: "#/components/schemas/AdminFirmConfirmResult" "400": description: Invalid input content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "409": description: A build job for this firm is already queued or running content: application/json: schema: $ref: "#/components/schemas/ActiveJobConflict" /admin/firms/{id}/refresh: post: operationId: refreshAdminFirm tags: [admin] summary: Re-run the diagnostic build for an already-onboarded firm description: > Queues a fresh "build" job for a firm that has already been confirmed and built, re-scoring every currently-active company. Each re-run APPENDS a new assessment per company (the assessment history is never overwritten) and refreshes the company/firm portal metadata. Rejected (400) for the 5 hand-authored legacy tenants, which are not pipeline-managed. Like confirm, this returns immediately and runs the build in the background. parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Refresh build job queued content: application/json: schema: $ref: "#/components/schemas/AdminFirmConfirmResult" "400": description: Invalid firm id, or firm is a hand-authored legacy tenant content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Firm not found, or has no active companies to re-score content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "409": description: A build job for this firm is already queued or running content: application/json: schema: $ref: "#/components/schemas/ActiveJobConflict" /admin/companies/{id}/report-data: get: operationId: getAdminCompanyReportData tags: [admin] summary: Get the full editor/validation/delivery workflow state for a company's report description: > Returns the company's EFFECTIVE report (computed scores/tier/gap-titles overlaid with the current edited-or-generated narrative) plus the current revision, dual-validation, and Google Drive shipment state. Read-only — never calls Claude, so it is safe for React Query to refetch. `report.reportData` is safe to copy verbatim into the Claude prompt; `report.meta`, `revision`, `validation` and `shipment` are admin-only bookkeeping that must NOT be included in the exported JSON. parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Report workflow state content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/report-revision: post: operationId: saveAdminCompanyReportRevision tags: [admin] summary: Save an admin edit of the report's narrative sections (creates a new revision) description: > Persists a new report revision from the admin-edited NARRATIVE sections (execSummary, compositeContext, existingSystems, pathForward, gaps[].impact/recommendation, nextSteps). Scores, tier, gap titles/descriptions, pillar signals/evidence and the P6 recommendation stay server-computed and are re-derived, never taken from the body. The saved narrative is sanitized (em-dash stripping, name redaction) exactly like generated narrative. Saving a revision RESETS all prior validations (a new revision must be re-validated). Returns the fresh workflow state. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ReportRevisionInput" responses: "200": description: Revision saved; fresh workflow state (validation reset) content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "400": description: Invalid company id or malformed body content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/report-meta: patch: operationId: updateAdminCompanyReportMeta tags: [admin] summary: Update the report cover metadata (Prepared For / Prepared By) for a company description: > Persists the per-company cover-page metadata directly on the companies row: Prepared For (name, title, company-line override) and Prepared By (name, organization, report date). Only supplied fields are changed; an empty string or null clears a field back to its default (blank Prepared For lines, the static INVESQ Prepared By constants, the company name, today's date). These values are read fresh on every report load, so they apply to drafts and validated reports alike WITHOUT creating a revision or resetting sign-offs. Returns the fresh workflow state. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateReportMetaInput" responses: "200": description: Cover metadata saved; fresh workflow state content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "400": description: Invalid company id or malformed body (e.g. a non-YYYY-MM-DD date) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/arr: patch: operationId: updateAdminCompanyArr tags: [admin] summary: Manually set or clear a company's disclosed ARR figure (CQ-47) description: > Full-state write of the CQ-45 ARR columns (companies.arr / arr_as_of / arr_source): all three fields must be supplied, each nullable. Setting arr to null clears ALL three columns back to "Undisclosed" (never zero-filled, excluded from rollups). A non-null arr may carry a null as-of date or source. Does not touch scoring, tiers, revisions, or sign-offs, and never affects other companies. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateCompanyArrInput" responses: "200": description: ARR saved (or cleared); the stored state as persisted content: application/json: schema: $ref: "#/components/schemas/CompanyArrState" "400": description: Invalid company id, negative ARR, or malformed as-of date content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Company not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/pillar-evidence: patch: operationId: updateAdminCompanyPillarEvidence tags: [admin] summary: Update the per-pillar evidence text on a company's latest assessment description: > Persists admin corrections to the raw per-pillar evidence text on the company's latest assessment (assessments.p1_evidence..p8_evidence) and mirrors each change into the matching findings row. Only supplied fields are changed; an empty string or null clears the field. The effective report rebuilds pillar evidence and gap descriptions from the live assessment on every load, so edits show up immediately in the scorecard pillar notes and gap cards WITHOUT creating a revision, resetting sign-offs, or changing any score, composite, or tier. Returns the fresh workflow state. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdatePillarEvidenceInput" responses: "200": description: Pillar evidence saved; fresh workflow state content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "400": description: Invalid company id or malformed body content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/validate: post: operationId: validateAdminCompanyReport tags: [admin] summary: Record a validator's sign-off on the current report revision description: > Records the calling admin (who must be one of the configured VALIDATOR_EMAILS) as having validated the company's CURRENT revision. Idempotent per (revision, validator). The client PDF unlocks only once every configured validator has signed the same current revision. parameters: - name: id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ReportValidateInput" responses: "200": description: Validation recorded; fresh workflow state content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "403": description: Caller is not a configured validator content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "404": description: Company not found, has no assessments, or has no saved revision to validate content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "409": description: The supplied revisionId is not the company's current revision content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "503": description: Validation is not configured (VALIDATOR_EMAILS unset) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/ship-to-drive: post: operationId: shipAdminCompanyReportToDrive tags: [admin] summary: Upload the validated report PDF to Google Drive and record the shipment description: > Renders the validated (stamped) client PDF and uploads it to Google Drive under "INVESQ Customers/{Firm}/{Company}/", then records the shipment. Requires the current revision to be fully dual-validated; a non-validated report is rejected with 412. parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Uploaded to Drive and shipment recorded; fresh workflow state content: application/json: schema: $ref: "#/components/schemas/AdminReportWorkflow" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "412": description: Report is not fully dual-validated, so it cannot be shipped content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "502": description: Google Drive upload failed content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/companies/{id}/report-export: post: operationId: generateAdminCompanyReportExport tags: [admin] summary: Generate (or return the already-cached) AI-written narrative sections of the report description: > Fills in the report-data.json fields that require synthesis rather than a straight DB read (execSummary, compositeContext, existingSystems, pathForward, pillarSignals, each gap's impact/recommendation, nextSteps) via Claude, grounded in the company's scored pillars/evidence and the Notion scoring rubric. Idempotent per (assessment, rubric version): if a report_exports row already exists for the company's current latest assessment, it is returned as-is with no new Claude call — calling this endpoint repeatedly (e.g. a user re-clicking Generate) never re-triggers paid generation unless a new assessment has landed or the rubric version changed. Synchronous — the response is not returned until generation (or the cache check) completes. parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Report data with AI-generated narrative sections populated (meta.generatedAt is non-null) content: application/json: schema: $ref: "#/components/schemas/AdminCompanyReportData" "404": description: Company not found, or has no assessments yet content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "502": description: Claude generation failed (e.g. malformed response, API error) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/backfill-pipeline-meta: post: operationId: backfillPipelineMeta tags: [admin] summary: Idempotent data-repair for pipeline-onboarded firms description: > Repairs the firm-level and company-status data on pipeline-onboarded (non-legacy) firms: (1) stamps the default "internal preview" firms.meta on any firm that is already "ready" but has no meta, and (2) resolves duplicate companies within a firm (same normalized name) by keeping the lowest-id active row and marking the rest "excluded" — a unification, never a delete. Leaves the 5 hand-authored legacy tenants completely untouched. Safe to call repeatedly. Note: this does NOT fabricate company CompanyMeta, so a firm built before the pipeline started writing full CompanyMeta still needs a re-run (POST /admin/firms/{id}/refresh) to render — backfill alone only fixes firm meta and duplicate rows. responses: "200": description: Per-firm repair result content: application/json: schema: $ref: "#/components/schemas/BackfillPipelineMetaResult" "401": description: Not authenticated as an allowed admin content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "500": description: Repair failed content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/system-health: get: operationId: getAdminSystemHealth tags: [admin] summary: Live system health audit of all firm states description: > Returns a structured health report classifying every firm by its current operational state. Stuck, discovery-empty, and build-failed firms are flagged with their recovery URLs. Used by the admin Health dashboard and the pre-publish gate banner. responses: "200": description: System health report content: application/json: schema: $ref: "#/components/schemas/SystemHealthReport" "401": description: Not authenticated as an allowed admin content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /jobs/{id}: get: operationId: getJob tags: [jobs] summary: Get a job's current status, progress, and ETA parameters: - name: id in: path required: true schema: type: integer responses: "200": description: Job status content: application/json: schema: $ref: "#/components/schemas/Job" "404": description: Job not found content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /auth/user: get: tags: [Auth] operationId: getCurrentAuthUser summary: Get the currently authenticated user parameters: - $ref: "#/components/parameters/AuthorizationSessionHeader" - $ref: "#/components/parameters/SessionCookie" responses: "200": description: Auth status resolved successfully. content: application/json: schema: $ref: "#/components/schemas/AuthUserEnvelope" /login: get: tags: [Auth] operationId: beginBrowserLogin summary: Start the browser OIDC login flow parameters: - name: returnTo in: query required: false description: Relative path to redirect to after login (must start with `/`). Defaults to `/`. schema: type: string responses: "302": description: Redirect to the OIDC authorization endpoint. /callback: get: tags: [Auth] operationId: handleBrowserLoginCallback summary: Complete the browser OIDC login flow parameters: - name: code in: query required: false schema: type: string - name: state in: query required: false schema: type: string - name: iss in: query required: false schema: type: string format: uri responses: "302": description: Redirect to the `returnTo` path on success (defaults to `/`) or `/api/login` on failure. /logout: get: tags: [Auth] operationId: logoutBrowserSession summary: Clear the session and begin OIDC logout parameters: - $ref: "#/components/parameters/AuthorizationSessionHeader" - $ref: "#/components/parameters/SessionCookie" responses: "302": description: Redirect to the OIDC provider logout URL. /mobile-auth/token-exchange: post: tags: [Auth] operationId: exchangeMobileAuthorizationCode summary: Exchange a mobile OIDC code for a session token requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MobileTokenExchangeRequest" responses: "200": description: Session created successfully. content: application/json: schema: $ref: "#/components/schemas/MobileTokenExchangeSuccess" "400": description: Missing or invalid required fields. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": description: Token did not contain usable claims. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "500": description: Token exchange failed. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /mobile-auth/logout: post: tags: [Auth] operationId: logoutMobileSession summary: Delete a mobile session token parameters: - $ref: "#/components/parameters/AuthorizationSessionHeader" responses: "200": description: Logout processed. content: application/json: schema: $ref: "#/components/schemas/LogoutSuccess" # ---- CQ-37: tiered confidence model (admin surface only) ---- /admin/tier-summary: get: operationId: listAdminTierSummary tags: [admin] summary: Paginated cross-tenant tier confidence summary (Tier 1/2/3 per company) parameters: - name: limit in: query required: false schema: { type: integer, minimum: 1, maximum: 100, default: 25 } - name: offset in: query required: false schema: { type: integer, minimum: 0, default: 0 } - name: sortBy in: query required: false schema: { type: string, enum: [company, tenant, tier2, tier3, disputes], default: company } - name: sortDir in: query required: false schema: { type: string, enum: [asc, desc], default: asc } - name: firmSlug in: query required: false schema: { type: string } - name: tier3Status in: query required: false schema: { $ref: "#/components/schemas/Tier3StatusValue" } responses: "200": description: One page of the tier summary content: application/json: schema: $ref: "#/components/schemas/TierSummaryPage" /admin/companies/{companyId}/tier2: patch: operationId: updateAdminCompanyTier2 tags: [admin] summary: Set one Tier 2 connector's status (writes a tier audit-log row) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateTier2Input" responses: "200": description: Updated tier snapshot content: application/json: schema: $ref: "#/components/schemas/TierMutationResult" /admin/companies/{companyId}/tier3: patch: operationId: updateAdminCompanyTier3 tags: [admin] summary: Set the Tier 3 validation status directly (writes a tier audit-log row) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateTier3Input" responses: "200": description: Updated tier snapshot content: application/json: schema: $ref: "#/components/schemas/TierMutationResult" /admin/companies/{companyId}/tier3-disputes: post: operationId: createAdminTierDispute tags: [admin] summary: Flag a Tier 3 dispute for review (never mutates the disputed value) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateTierDisputeInput" responses: "201": description: Pending dispute created content: application/json: schema: $ref: "#/components/schemas/TierDisputeRecord" /admin/tier-disputes: get: operationId: listAdminTierDisputes tags: [admin] summary: List tier disputes (filterable by status/company) parameters: - name: status in: query required: false schema: { type: string, enum: [pending, applied, rejected] } - name: companyId in: query required: false schema: { type: integer } responses: "200": description: Disputes, newest first content: application/json: schema: type: array items: $ref: "#/components/schemas/TierDisputeRecord" /admin/tier-disputes/{disputeId}/resolve: post: operationId: resolveAdminTierDispute tags: [admin] summary: Apply or reject a pending dispute (apply mutates + audit-logs atomically) parameters: - name: disputeId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ResolveTierDisputeInput" responses: "200": description: Resolution result content: application/json: schema: $ref: "#/components/schemas/TierMutationResult" /admin/companies/{companyId}/tier-audit: get: operationId: listAdminTierAudit tags: [admin] summary: Append-only tier audit-log rows for one company, newest first parameters: - name: companyId in: path required: true schema: { type: integer } responses: "200": description: Audit rows content: application/json: schema: type: array items: $ref: "#/components/schemas/TierAuditRecord" # ---- Data Moat action #3: Outcome Data (admin surface ONLY — internal # retention outcomes + interventions log; never tenant-facing, never in # reports or PDFs) ---- /admin/companies/{companyId}/outcomes: get: operationId: getAdminCompanyOutcomes tags: [admin] summary: Internal outcome metrics + interventions log for one company (Admin Lens only) parameters: - name: companyId in: path required: true schema: { type: integer } responses: "200": description: Outcome metrics and interventions content: application/json: schema: $ref: "#/components/schemas/AdminCompanyOutcomes" patch: operationId: updateAdminCompanyOutcomeMetrics tags: [admin] summary: Update entry/milestone GRR-NRR outcome metrics (partial; null clears a value) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateOutcomeMetricsInput" responses: "200": description: Updated outcome snapshot content: application/json: schema: $ref: "#/components/schemas/AdminCompanyOutcomes" /admin/companies/{companyId}/outcomes/interventions: post: operationId: createAdminOutcomeIntervention tags: [admin] summary: Append an intervention (pillar, action, date, owner) to the company's log parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateOutcomeInterventionInput" responses: "201": description: Created intervention row content: application/json: schema: $ref: "#/components/schemas/OutcomeInterventionRecord" /admin/outcome-interventions/{interventionId}: delete: operationId: deleteAdminOutcomeIntervention tags: [admin] summary: Delete one intervention log row parameters: - name: interventionId in: path required: true schema: { type: integer } responses: "204": description: Deleted # ---- Calibration Ledger (Admin Lens ONLY): locked Stage 1 prediction # snapshots, observed records, computed deltas, and resolution events # (which live in the existing signals table). Never tenant-facing. /admin/companies/{companyId}/calibration: get: operationId: getAdminCompanyCalibration tags: [admin] summary: Calibration ledger for one company (prediction, observations, deltas, resolution events) parameters: - name: companyId in: path required: true schema: { type: integer } responses: "200": description: Full calibration ledger for the company content: application/json: schema: $ref: "#/components/schemas/AdminCompanyCalibration" "404": description: Company not found /admin/companies/{companyId}/calibration/prediction: post: operationId: lockAdminCalibrationPrediction tags: [admin] summary: Snapshot + lock the Stage 1 prediction from the company's latest scored assessment description: > Creates the company's one immutable prediction snapshot (per-pillar scores, composite, band, rubric version, prediction timestamp), derived server-side from the latest assessment row. 409 if a locked snapshot already exists; 422 if the company has no scored assessment. parameters: - name: companyId in: path required: true schema: { type: integer } responses: "201": description: Locked prediction snapshot content: application/json: schema: $ref: "#/components/schemas/CalibrationPredictionRecord" "409": description: A locked snapshot already exists (immutable) "422": description: Company has no scored assessment to snapshot patch: operationId: updateAdminCalibrationPrediction tags: [admin] summary: Always rejected — locked prediction snapshots are immutable description: > Exists so the immutability contract is explicit and testable. Any attempt to edit a locked snapshot returns 409; there is no writable field on a locked prediction. parameters: - name: companyId in: path required: true schema: { type: integer } responses: "409": description: Locked prediction snapshots are immutable "404": description: No prediction snapshot exists for this company /admin/companies/{companyId}/calibration/observations: post: operationId: createAdminCalibrationObservation tags: [admin] summary: Record observed reality for one or more pillars (any source, own timestamp) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateCalibrationObservationInput" responses: "201": description: Created observation plus recomputed deltas content: application/json: schema: $ref: "#/components/schemas/AdminCompanyCalibration" "404": description: Company not found /admin/companies/{companyId}/confirmation: get: operationId: getAdminCompanyConfirmation tags: [admin] summary: Confirmation Status (tier3_status) plus auto-flagged pillars and confirmation requests for one company parameters: - name: companyId in: path required: true schema: { type: integer } responses: "200": description: Confirmation state for the company content: application/json: schema: $ref: "#/components/schemas/AdminCompanyConfirmation" "404": description: Company not found /admin/companies/{companyId}/confirmation-requests: post: operationId: createAdminConfirmationRequest tags: [admin] summary: Create a single-purpose expiring confirmation link for the portco CS lead or PE operating partner description: > Generates an unguessable token (returned exactly once in the link; only its hash is stored), snapshots the auto-flagged pillars, and returns the shareable /confirm/{token} link for the admin to send. 409 if the company has no flagged pillars to confirm. parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateConfirmationRequestInput" responses: "201": description: Created request plus the one-time shareable link content: application/json: schema: $ref: "#/components/schemas/CreatedConfirmationRequest" "404": description: Company not found "409": description: No flagged pillars to confirm /admin/confirmation-requests/{requestId}/revoke: post: operationId: revokeAdminConfirmationRequest tags: [admin] summary: Revoke a pending confirmation link before it is used or expires parameters: - name: requestId in: path required: true schema: { type: integer } responses: "200": description: Request revoked content: application/json: schema: $ref: "#/components/schemas/ConfirmationRequestRecord" "404": description: Request not found "409": description: Request is not pending (already submitted, revoked, or expired) /admin/companies/{companyId}/calibration/resolution-events: post: operationId: createAdminResolutionEvent tags: [admin] summary: Record a resolution event (stored as a signals-table row with event_type set) parameters: - name: companyId in: path required: true schema: { type: integer } requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateResolutionEventInput" responses: "201": description: Created resolution event content: application/json: schema: $ref: "#/components/schemas/ResolutionEventRecord" "404": description: Company not found "422": description: Company has no assessment row to attach the signal to /admin/calibration/resolution-events/{signalId}: delete: operationId: deleteAdminResolutionEvent tags: [admin] summary: Delete one resolution event (refuses to touch non-event signal rows) parameters: - name: signalId in: path required: true schema: { type: integer } responses: "204": description: Deleted "404": description: No resolution event with this id /portfolio/cs-rescue-internal/backengine: get: operationId: getCsRescueInternalBackengine tags: [portfolio] summary: Anonymized BackEngine evidence for the CS Rescue Internal dogfood tenant description: > Returns ONLY anonymized data — deterministic "Prospect N" placeholders plus engagement metrics (accounts shape) and anonymized signal text (monitor/feed shape). Real account names never appear in this payload; the real-name mapping is Admin-Lens-only. Literal-slug route like /portfolio/raviga/signals: no other tenant has it. responses: "200": description: Anonymized BackEngine accounts and signals content: application/json: schema: $ref: "#/components/schemas/BackengineEvidence" "500": description: Failed to load BackEngine evidence content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/backengine/import: post: operationId: importAdminBackengine tags: [admin] summary: Import a BackEngine CSV/XLSX export with mandatory anonymization description: > Accepts either the Accounts-tab shape or the Monitor/Feed-tab shape (auto-detected from headers). Every real account name is replaced with a stable "Prospect N" placeholder (keyed by sha256 of the normalized name, never row order) BEFORE anything is persisted to any tenant-visible table. Null engagement metrics are a valid shape. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/BackengineImportInput" responses: "200": description: Import summary content: application/json: schema: $ref: "#/components/schemas/BackengineImportResult" "422": description: Unrecognized file shape or unparseable content content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /admin/backengine/name-map: get: operationId: listAdminBackengineNameMap tags: [admin] summary: Admin-only real-name → placeholder mapping (never tenant-visible) responses: "200": description: Full mapping table content: application/json: schema: type: object required: [rows] properties: rows: type: array items: $ref: "#/components/schemas/BackengineNameMapRow" components: parameters: AuthorizationSessionHeader: name: Authorization in: header required: false description: Opaque session token — `Bearer `. schema: type: string SessionCookie: name: sid in: cookie required: false description: Browser session cookie. schema: type: string schemas: AuthUser: type: object required: [id, email, firstName, lastName, profileImageUrl] properties: id: type: string email: type: [string, "null"] format: email firstName: type: [string, "null"] lastName: type: [string, "null"] profileImageUrl: type: [string, "null"] AuthUserEnvelope: type: object required: [user] properties: user: oneOf: - $ref: "#/components/schemas/AuthUser" - type: "null" MobileTokenExchangeRequest: type: object required: [code, code_verifier, redirect_uri, state] properties: code: type: string minLength: 1 code_verifier: type: string minLength: 1 redirect_uri: type: string minLength: 1 format: uri state: type: string minLength: 1 nonce: type: string minLength: 1 MobileTokenExchangeSuccess: type: object required: [token] properties: token: type: string LogoutSuccess: type: object required: [success] properties: success: type: boolean const: true ErrorEnvelope: type: object required: [error] properties: error: type: string ActiveJobConflict: type: object description: > Returned instead of creating a duplicate job when the target already has a queued/running job of the requested type. required: [error, job] properties: error: type: string job: $ref: "#/components/schemas/Job" CreateAdminFirmInput: type: object required: [name, website] properties: name: type: string minLength: 1 website: type: string minLength: 1 FirmMeta: type: object required: [statusLabel, internalOnly] properties: statusLabel: type: string internalOnly: type: boolean requireLogin: type: boolean description: > When true, the tenant portal for this firm requires an authenticated admin session to view. Default/absent = false (public). UI-gate only; the bootstrap API stays public. Firm: type: object required: [id, name, website, slug, status, dataAuthority, meta, createdAt] properties: id: type: integer name: type: string website: type: [string, "null"] slug: type: string status: type: string dataAuthority: type: string enum: [strict, best_effort] description: > "strict" firms fail loudly on bad data; "best_effort" degrade gracefully. Promotion is always an explicit admin action. meta: description: > Portal display metadata (statusLabel, internalOnly, requireLogin). Null for pipeline firms not yet promoted to a tenant portal. oneOf: - $ref: "#/components/schemas/FirmMeta" - type: "null" createdByEmail: type: [string, "null"] description: > Email of the admin who created this firm, captured from their session at creation time. Used to notify them when the build job finishes. Null for firms created before this field existed or outside an authenticated session. createdAt: type: string format: date-time Job: type: object required: [id, type, targetId, status, progressPct, etaSeconds, error] properties: id: type: integer type: type: string targetId: type: string status: type: string progressPct: type: integer etaSeconds: type: [integer, "null"] error: type: [string, "null"] CreateAdminFirmResponse: type: object required: [firm, job] properties: firm: $ref: "#/components/schemas/Firm" job: $ref: "#/components/schemas/Job" OkResult: type: object required: [ok] properties: ok: type: boolean ReorderAdminFirmsInput: type: object required: [firmIds] properties: firmIds: type: array description: > Firm ids in the desired display order. Each firm's sort_order is set to its index. Ids must be unique and must all exist. items: type: integer minItems: 1 CreateManualAdminFirmInput: type: object required: [name, slug] properties: name: type: string minLength: 1 slug: type: string minLength: 1 description: > Lowercase kebab-case URL slug (letters, digits, hyphens). Must be unique and not a reserved route word (e.g. admin, portfolio, api). statusLabel: type: string description: Optional portal status pill text (stored in meta). internalOnly: type: boolean description: Marks the firm internal-only in portal meta. Default false. DeleteAdminFirmResult: type: object required: [deletedFirmId, removedCompanies, removedAssessments] properties: deletedFirmId: type: integer removedCompanies: type: integer removedAssessments: type: integer AdminFirmSummary: type: object required: [id, name, website, slug, status, dataAuthority, meta, companyCount, createdAt, latestJob, sortOrder] properties: id: type: integer name: type: string website: type: [string, "null"] slug: type: string status: type: string dataAuthority: type: string enum: [strict, best_effort] meta: description: Portal display metadata, or null for pipeline firms not yet promoted to a tenant portal. oneOf: - $ref: "#/components/schemas/FirmMeta" - type: "null" companyCount: type: integer latestJob: description: The most recently created job (any status) targeting this firm, or null if none exists. oneOf: - $ref: "#/components/schemas/Job" - type: "null" sortOrder: type: [integer, "null"] description: > Admin-controlled display position (lower = first); null = unordered, listed after ordered firms. The list is already sorted by this server-side. createdAt: type: string format: date-time Company: type: object required: [id, firmId, name, website, status, slug, createdAt, hasAssessment] properties: id: type: integer firmId: type: integer name: type: string website: type: [string, "null"] status: type: string slug: type: [string, "null"] createdAt: type: string format: date-time hasAssessment: type: boolean description: Whether the company has at least one assessment row (eligible for report export). AdminCompanyReportData: type: object description: > Assembled report-data.json export payload for the Diagnostic Report pattern. `reportData` matches the external report-data.json schema (Notion: "External CS Diagnostic — Scoring Rubric & Cowork Instructions", Step 7) field-for-field, so it is safe to copy verbatim into the Claude design-file prompt. `meta` carries admin-only context (assessment provenance, derived rubric-v2 bands/composite) that must NOT be included in the exported JSON. required: [reportData, meta] properties: reportData: $ref: "#/components/schemas/DiagnosticReportData" meta: type: object required: [ companyId, assessmentDate, rubric, generatedAt, model, preparedByName, preparedByOrg, preparedForCompany, preparedForCompanyOverride, ] properties: companyId: type: integer assessmentDate: type: string description: Date of the source assessment used (ISO date). rubric: type: object description: > Rubric v2 (4-pillar Low/Medium/High) values for the source assessment, matching computeRubricV2/computePortcoScore in @workspace/portfolio-engine exactly. Stored assessments columns win when the row carries all five; otherwise derived live via computeRubricV2(). portcoComposite is the 0-8 numeric composite (Low=0, Medium=1, High=2, Insufficient Data counts as 1), banded 0-2 Low / 3-5 Medium / 6-8 High. required: [ orgDesignScore, onboardingScore, healthScoringScore, renewalExpansionScore, portcoComposite, portcoBand, ] properties: orgDesignScore: type: string enum: [Low, Medium, High, Insufficient Data] onboardingScore: type: string enum: [Low, Medium, High, Insufficient Data] healthScoringScore: type: string enum: [Low, Medium, High, Insufficient Data] renewalExpansionScore: type: string enum: [Low, Medium, High, Insufficient Data] portcoComposite: type: integer description: Numeric composite 0-8. portcoBand: type: string enum: [Low, Medium, High] generatedAt: type: [string, "null"] description: > When the AI-generated narrative sections (execSummary, compositeContext, existingSystems, pathForward, pillarSignals, gap impact/recommendation, nextSteps) were produced, or null if this response still carries the blank-placeholder fallback (no report_exports row yet for this assessment). model: type: [string, "null"] description: Claude model used to generate the narrative, or null if not yet generated. preparedByName: type: string description: > Effective "Prepared By - Name" cover line (per-company override from the companies row, else the static INVESQ default). Cover display metadata only, kept OUT of the exported report-data.json. preparedByOrg: type: string description: Effective "Prepared By - Organization" cover line (override else "INVESQ"). preparedForCompany: type: string description: > Effective "Prepared For - Company" cover line (override else the company's name). Only affects the cover card, never the report H1 or narrative. preparedForCompanyOverride: type: [string, "null"] description: The raw stored override for the Prepared For company line, or null when unset. DiagnosticReportData: type: object description: > Exact shape of report-data.json per the Notion scoring rubric's Step 7 ("Producing the Branded Client PDF"). Fields with no real data yet are left as "" / [] — the branded report template treats a blank field as an accepted, designed fallback (a neutral placeholder), not an error. required: [ companyName, parentFund, preparedForName, preparedForTitle, reportDate, csHeadcount, execSummary, compositeContext, existingSystems, pathForward, scores, pillarSignals, pillarEvidence, p6Recommendation, gaps, nextSteps, ] properties: companyName: type: string parentFund: type: string preparedForName: type: string preparedForTitle: type: string reportDate: type: string description: Date this report-data.json was assembled (ISO date). csHeadcount: type: string execSummary: type: array description: One string per paragraph. items: type: string compositeContext: type: string existingSystems: type: string pathForward: type: string scores: type: object description: Raw pillar scores 0/1/2, or "NA" for Insufficient Data. required: [p1, p2, p3, p4, p5, p6, p7, p8] properties: p1: type: [integer, string] p2: type: [integer, string] p3: type: [integer, string] p4: type: [integer, string] p5: type: [integer, string] p6: type: [integer, string] p7: type: [integer, string] p8: type: [integer, string] pillarSignals: type: object description: > One-line "what the signals show" per pillar (scorecard column). Left "" when no data beyond the raw score is on file. required: [p1, p2, p3, p4, p5, p6, p7, p8] properties: p1: type: string p2: type: string p3: type: string p4: type: string p5: type: string p6: type: string p7: type: string p8: type: string pillarEvidence: type: object description: > Longer pillar-by-pillar narrative Claude produced during scoring (assessments.p{n}Evidence). Left "" when no evidence is on file. required: [p1, p2, p3, p4, p5, p6, p7, p8] properties: p1: type: string p2: type: string p3: type: string p4: type: string p5: type: string p6: type: string p7: type: string p8: type: string p6Recommendation: type: string description: > Derived from the p6 (CS Leadership) score: 2 = "Retain and Develop", 1 = "Augment", 0 = "Replace". Empty if p6 is "NA". gaps: type: array description: Top 3 identified gaps (the three lowest-scoring pillars). items: type: object required: [title, description, impact, recommendation] properties: title: type: string description: type: string impact: type: string recommendation: type: string nextSteps: type: array items: type: string ReportValidator: type: object required: [email, name, hasValidated, validatedAt] properties: email: type: string name: type: string hasValidated: type: boolean description: Whether this validator has signed off on the CURRENT revision. validatedAt: type: [string, "null"] overrideFor: type: [string, "null"] description: If this validator submitted an override, the email of the validator they overrode. Null on a normal sign-off. overrideReason: type: [string, "null"] description: The typed override justification, or null if no override was submitted. ReportValidationState: type: object description: > Dual-validation state for the company's current report revision. `configured` is false when VALIDATOR_EMAILS is unset (fail-closed: validation is impossible and the client PDF stays locked). required: [ configured, requiredCount, validatedCount, isValidated, validators, validatorNames, validatedAt, ] properties: configured: type: boolean requiredCount: type: integer description: Number of configured validators required to unlock the client PDF. validatedCount: type: integer description: How many required validators have signed the current revision. isValidated: type: boolean description: > True when a current revision exists and either every configured validator has signed it, or one validator has submitted an override for the other's missing sign-off (override_for IS NOT NULL on any validation row for the revision). validators: type: array items: $ref: "#/components/schemas/ReportValidator" validatorNames: type: array description: Display names of the validators who have signed the current revision (used for the PDF stamp). items: type: string validatedAt: type: [string, "null"] description: Timestamp of the most recent signature on the current revision, or null. ReportRevisionState: type: object description: > The company's current (latest, matching-rubric-version) saved narrative revision, or a hasRevision:false placeholder when none has been saved. required: [hasRevision, revisionId, rubricVersion, isStale, editedByEmail, editedByName, createdAt] properties: hasRevision: type: boolean revisionId: type: [integer, "null"] rubricVersion: type: [string, "null"] isStale: type: boolean description: True when the revision's rubricVersion differs from the server's current RUBRIC_VERSION. editedByEmail: type: [string, "null"] editedByName: type: [string, "null"] createdAt: type: [string, "null"] DriveShipmentState: type: object description: The latest Google Drive shipment recorded for this company, if any. required: [shipped, isCurrent, revisionId, fileId, webViewLink, folderPath, shippedByName, shippedAt] properties: shipped: type: boolean isCurrent: type: boolean description: True when the shipped revision is the company's current revision. revisionId: type: [integer, "null"] fileId: type: [string, "null"] webViewLink: type: [string, "null"] folderPath: type: [string, "null"] shippedByName: type: [string, "null"] shippedAt: type: [string, "null"] AdminReportWorkflow: type: object description: > Full editor/validation/delivery state for a company's current report: the effective report data (computed scores/tier/gap-titles + the current edited-or-generated narrative), plus revision, dual-validation, and Google Drive shipment state. required: [report, revision, validation, shipment] properties: report: $ref: "#/components/schemas/AdminCompanyReportData" revision: $ref: "#/components/schemas/ReportRevisionState" validation: $ref: "#/components/schemas/ReportValidationState" shipment: $ref: "#/components/schemas/DriveShipmentState" ReportRevisionGapInput: type: object required: [title, impact, recommendation] properties: title: type: string description: Used only to match the gap to its computed slot; the server keeps the computed title/description. impact: type: string recommendation: type: string ReportRevisionInput: type: object description: > Narrative-only edit payload. Only these fields are editable; scores, tier, gap titles/descriptions, pillar signals/evidence and the P6 recommendation stay server-computed and are ignored if sent. required: [execSummary, compositeContext, existingSystems, pathForward, nextSteps, gaps] properties: execSummary: type: array items: type: string compositeContext: type: string existingSystems: type: string pathForward: type: string nextSteps: type: array items: type: string gaps: type: array items: $ref: "#/components/schemas/ReportRevisionGapInput" ReportValidateInput: type: object required: [revisionId] properties: revisionId: type: integer description: The revision the caller intends to validate; must equal the current revision or the request 409s. overrideFor: type: [string, "null"] description: > Email of the validator being overridden. When present, overrideReason is also required. The submitter's sign-off is recorded AND the other validator's missing sign-off is waived, unlocking the client PDF. Stored in report_validations.override_for. overrideReason: type: [string, "null"] description: > Mandatory justification text when overrideFor is set. Stored verbatim and shown in the PDF validation stamp as "override: {other} - {reason}". UpdateReportMetaInput: type: object description: > Partial cover-metadata update. Every field is optional; only supplied fields are changed. An empty string or null clears the field back to its default (blank Prepared For lines, static INVESQ Prepared By constants, the company name, today's date). properties: preparedForName: type: [string, "null"] preparedForTitle: type: [string, "null"] preparedForCompany: type: [string, "null"] description: Override for the Prepared For card's Company line only; never changes the report H1 or narrative. preparedByName: type: [string, "null"] preparedByOrg: type: [string, "null"] preparedByDate: type: [string, "null"] pattern: "^\\d{4}-\\d{2}-\\d{2}$" description: Report date shown on the Prepared By card (YYYY-MM-DD); becomes reportData.reportDate. UpdateCompanyArrInput: type: object description: > Full-state ARR write. All three keys are required; each value is nullable. arr must be >= 0 whole US dollars or null. A null OR zero arr clears all three columns back to "Undisclosed" regardless of the other values (the portfolio engine only treats a positive figure as a first-class ARR, so zero is an explicit clear, never a stored value). required: [arr, arrAsOf, arrSource] properties: arr: type: [number, "null"] minimum: 0 description: Disclosed ARR in whole US dollars, or null to clear. arrAsOf: type: [string, "null"] pattern: "^\\d{4}-\\d{2}-\\d{2}$" description: Date the figure was valid as of (YYYY-MM-DD) or null. arrSource: type: [string, "null"] maxLength: 500 description: Free-text source citation (press release, filing, call note) or null. CompanyArrState: type: object description: The ARR columns exactly as persisted after an update. required: [companyId, arr, arrAsOf, arrSource] properties: companyId: type: integer arr: type: [number, "null"] arrAsOf: type: [string, "null"] arrSource: type: [string, "null"] UpdatePillarEvidenceInput: type: object description: > Partial per-pillar evidence update for the company's latest assessment. Every field is optional; only supplied fields are changed. An empty string or null clears the field. Keys map to assessments.p1_evidence..p8_evidence in PILLARS order (p1 CS Org Design through p8 AI Adoption Maturity). properties: p1: type: [string, "null"] p2: type: [string, "null"] p3: type: [string, "null"] p4: type: [string, "null"] p5: type: [string, "null"] p6: type: [string, "null"] p7: type: [string, "null"] p8: type: [string, "null"] AdminFirmDetail: type: object required: [firm, companies, latestJob] properties: firm: $ref: "#/components/schemas/Firm" companies: type: array items: $ref: "#/components/schemas/Company" latestJob: description: The most recently created job (any status) targeting this firm, or null if none exists. oneOf: - $ref: "#/components/schemas/Job" - type: "null" AddAdminCompanyInput: type: object required: [name, website] properties: name: type: string minLength: 1 website: type: string minLength: 1 ConfirmAdminFirmInput: type: object required: [companyIds] properties: companyIds: type: array items: type: integer UpdateAdminFirmInput: type: object description: > Partial update of a firm's admin-controlled fields. Only provided keys are changed. `meta` replaces the whole portal-metadata object. properties: dataAuthority: type: string enum: [strict, best_effort] meta: $ref: "#/components/schemas/FirmMeta" SetFirmClearanceInput: type: object required: [internalOnly, password] properties: internalOnly: type: boolean description: The new clearance state. true = internal only; false = client-ready. password: type: string description: The clearance admin password, verified server-side against CLEARANCE_ADMIN_PASSWORD. AdminFirmConfirmResult: type: object required: [firm, job] properties: firm: $ref: "#/components/schemas/Firm" job: $ref: "#/components/schemas/Job" BackfillPipelineMetaFirm: type: object required: [id, slug, metaStamped, duplicatesExcluded] properties: id: type: integer slug: type: string metaStamped: type: boolean description: True if this firm was missing meta and had the default stamped this run. duplicatesExcluded: type: integer description: Number of duplicate-named active companies marked "excluded" in this firm. BackfillPipelineMetaResult: type: object required: [firmsMetaStamped, duplicatesExcluded, firms] properties: firmsMetaStamped: type: integer duplicatesExcluded: type: integer firms: type: array items: $ref: "#/components/schemas/BackfillPipelineMetaFirm" HealthStatus: type: object properties: status: type: string required: - status ArchitectureMap: type: object properties: nodes: type: array items: $ref: "#/components/schemas/ArchitectureNode" connections: type: array items: $ref: "#/components/schemas/NodeConnection" layers: type: array items: type: string required: - nodes - connections - layers ArchitectureNode: type: object properties: id: type: string name: type: string type: type: string layer: type: string enum: [lifecycle, delivery, platform] icon: type: string shortDescription: type: string capabilities: type: array items: type: string lifecycleMotionIds: type: array items: type: string connectedNodeIds: type: array items: type: string resourceIds: type: array items: type: string kpis: type: array items: $ref: "#/components/schemas/KPI" status: type: string enum: [active, degraded, offline, warning] ownerTeam: type: string color: type: string healthScore: type: number subtype: type: string position: type: object properties: x: type: number y: type: number visibleToPersonas: type: array description: Personas for which this node is visible at all items: type: string enum: [vp, sales, post-sales, cs, support, engineering] defaultPriorityByPersona: type: object description: Per-persona priority (primary | secondary | hidden) additionalProperties: type: string enum: [primary, secondary, hidden] simplifiedLabel: type: string description: Short, scannable label for compact card view clusterGroup: type: string description: Logical cluster id for the Business view (e.g. revenue, delivery, customer-data) dependencyVisibilityLevel: type: string enum: [low, medium, high] description: How much dependency context to surface for this node businessCriticality: type: number description: 1-5 — how critical to revenue / customer outcomes technicalCriticality: type: number description: 1-5 — how critical to platform stability microStat: type: string description: Single short stat shown on compact cards (e.g. "12 active") roleTag: type: string description: Single role chip shown on compact cards required: - id - name - type - layer - icon - shortDescription - capabilities - lifecycleMotionIds - connectedNodeIds - resourceIds - kpis - status - ownerTeam - color ArchitectureEdge: type: object properties: id: type: string source: type: string target: type: string relationshipType: type: string enum: [data_flow, dependency, sync, composition, control] label: type: string strength: type: number status: type: string enum: [active, degraded, inactive] required: - id - source - target - relationshipType - strength - status ArchitectureGroup: type: object properties: id: type: string name: type: string layer: type: string nodeIds: type: array items: type: string color: type: string required: - id - name - layer - nodeIds - color GraphData: type: object properties: nodes: type: array items: $ref: "#/components/schemas/ArchitectureNode" edges: type: array items: $ref: "#/components/schemas/ArchitectureEdge" groups: type: array items: $ref: "#/components/schemas/ArchitectureGroup" required: - nodes - edges - groups MetricPoint: type: object properties: timestamp: type: string value: type: number label: type: string required: - timestamp - value NodeMetricSeries: type: object properties: id: type: string nodeId: type: string metricName: type: string unit: type: string chartType: type: string enum: [line, bar, donut, radial, sparkline] trendDirection: type: string enum: [up, down, flat] currentValue: type: number delta: type: number points: type: array items: $ref: "#/components/schemas/MetricPoint" required: - id - nodeId - metricName - unit - chartType - points NodeConnection: type: object properties: from: type: string to: type: string type: type: string enum: [data, dependency, bidirectional] required: - from - to - type KPI: type: object properties: label: type: string value: type: string trend: type: string enum: [up, down, flat] required: - label - value ArchitectureSummary: type: object properties: totalNodes: type: integer activeNodes: type: integer totalResources: type: integer healthyResources: type: integer totalConnectors: type: integer activeDeployments: type: integer systemHealth: type: number required: - totalNodes - activeNodes - totalResources - healthyResources - totalConnectors - activeDeployments - systemHealth Resource: type: object properties: id: type: string name: type: string category: type: string vendor: type: string environment: type: string enum: [production, sandbox, staging] status: type: string enum: [connected, disconnected, degraded, pending] dataDirection: type: string enum: [inbound, outbound, bidirectional] linkedNodeIds: type: array items: type: string owner: type: string sensitivity: type: string enum: [public, internal, confidential, restricted] lastSyncAt: type: string nullable: true metadata: type: object additionalProperties: true required: - id - name - category - vendor - environment - status - dataDirection - linkedNodeIds - owner - sensitivity NewResourceInput: type: object properties: name: type: string category: type: string vendor: type: string environment: type: string enum: [production, sandbox, staging] dataDirection: type: string enum: [inbound, outbound, bidirectional] linkedNodeIds: type: array items: type: string owner: type: string sensitivity: type: string enum: [public, internal, confidential, restricted] required: - name - category - vendor - environment - dataDirection - linkedNodeIds - owner - sensitivity PatchResourceInput: type: object properties: status: type: string enum: [connected, disconnected, degraded, pending] environment: type: string enum: [production, sandbox, staging] dataDirection: type: string enum: [inbound, outbound, bidirectional] owner: type: string sensitivity: type: string enum: [public, internal, confidential, restricted] Connector: type: object properties: id: type: string name: type: string type: type: string authType: type: string enum: [oauth2, api_key, basic, jwt, none] status: type: string enum: [enabled, disabled, pending] health: type: string enum: [healthy, degraded, offline, unknown] configSchema: type: object additionalProperties: true supportedResourceCategories: type: array items: type: string environment: type: string enum: [production, sandbox, staging] dataOwner: type: string businessOwner: type: string syncDirection: type: string enum: [inbound, outbound, bidirectional] sensitivityLevel: type: string enum: [public, internal, confidential, restricted] dependencies: type: array items: type: string lastCheckedAt: type: string nullable: true required: - id - name - type - authType - status - health - supportedResourceCategories - environment - dataOwner - businessOwner - syncDirection - sensitivityLevel - dependencies NewConnectorInput: type: object properties: name: type: string type: type: string authType: type: string enum: [oauth2, api_key, basic, jwt, none] environment: type: string enum: [production, sandbox, staging] dataOwner: type: string businessOwner: type: string syncDirection: type: string enum: [inbound, outbound, bidirectional] sensitivityLevel: type: string enum: [public, internal, confidential, restricted] required: - name - type - authType - environment - dataOwner - businessOwner - syncDirection - sensitivityLevel PatchConnectorInput: type: object properties: status: type: string enum: [enabled, disabled, pending] health: type: string enum: [healthy, degraded, offline, unknown] syncDirection: type: string enum: [inbound, outbound, bidirectional] environment: type: string enum: [production, sandbox, staging] dataOwner: type: string businessOwner: type: string ConnectorHealthSummary: type: object properties: healthy: type: integer degraded: type: integer offline: type: integer unknown: type: integer total: type: integer connectors: type: array items: type: object properties: id: type: string name: type: string health: type: string lastCheckedAt: type: string nullable: true required: - id - name - health required: - healthy - degraded - offline - unknown - total - connectors Deployment: type: object properties: id: type: string accountId: type: string accountName: type: string name: type: string stage: type: string enum: [pre_sales, contracting, implementation, csm, support, completed] architectureNodeIds: type: array items: type: string resourceIds: type: array items: type: string blockers: type: array items: $ref: "#/components/schemas/Blocker" milestones: type: array items: $ref: "#/components/schemas/Milestone" healthScore: type: number startedAt: type: string estimatedCompletionAt: type: string nullable: true workstreams: type: array items: $ref: "#/components/schemas/Workstream" required: - id - accountId - accountName - name - stage - architectureNodeIds - resourceIds - blockers - milestones - healthScore - startedAt - workstreams Blocker: type: object properties: id: type: string description: type: string severity: type: string enum: [critical, high, medium, low] status: type: string enum: [open, in_progress, resolved] owner: type: string required: - id - description - severity - status - owner Milestone: type: object properties: id: type: string name: type: string status: type: string enum: [completed, in_progress, pending, blocked] dueDate: type: string nullable: true completedAt: type: string nullable: true required: - id - name - status Workstream: type: object properties: id: type: string name: type: string status: type: string enum: [active, paused, completed, not_started] owner: type: string progress: type: number required: - id - name - status - owner - progress Account: type: object properties: id: type: string name: type: string segment: type: string enum: [enterprise, mid_market, smb] lifecycleStage: type: string enum: [pre_sales, contracting, implementation, csm, support, churned] deploymentIds: type: array items: type: string owner: type: string status: type: string enum: [active, at_risk, churned, prospect] industry: type: string arr: type: number nullable: true required: - id - name - segment - lifecycleStage - deploymentIds - owner - status - industry LifecycleMotion: type: object properties: id: type: string name: type: string icon: type: string description: type: string order: type: integer color: type: string nodeIds: type: array items: type: string kpis: type: array items: $ref: "#/components/schemas/KPI" required: - id - name - icon - description - order - color - nodeIds - kpis PortfolioActionLogEntry: type: object description: Dated event annotated as a marker on the trend / forecast chart. properties: date: type: string label: type: string required: - date - label PortfolioRubricScores: type: object description: > Rubric v2 (Phase 2) — 4-pillar Low/Medium/High fields stored on the assessment row. Computed exclusively via computeRubricV2() in @workspace/portfolio-engine; clients read these stored values, never re-derive them ad hoc. portcoScore never carries Insufficient Data (the rollup substitutes Medium for ID pillars). properties: orgDesignScore: type: string enum: [Low, Medium, High, Insufficient Data] onboardingScore: type: string enum: [Low, Medium, High, Insufficient Data] healthScoringScore: type: string enum: [Low, Medium, High, Insufficient Data] renewalExpansionScore: type: string enum: [Low, Medium, High, Insufficient Data] portcoScore: type: string enum: [Low, Medium, High] rubricVersion: type: string required: - orgDesignScore - onboardingScore - healthScoringScore - renewalExpansionScore - portcoScore - rubricVersion PortfolioAssessment: type: object description: A single diagnostic run for a company. The company's current state always derives from the LATEST assessment in the array. properties: date: type: string pillarScores: type: object description: Keyed by pillar id; all 8 pillars must be present. 0/1/2 = scored, null = Insufficient Data (NA). additionalProperties: type: [integer, "null"] enum: [0, 1, 2, null] rubric: $ref: "#/components/schemas/PortfolioRubricScores" note: type: string required: - date - pillarScores PortfolioCompany: type: object description: Raw company record — only raw inputs, never derived values (RawCompany in @workspace/portfolio-engine). properties: id: type: string name: type: string sector: type: string hq: type: string employeesDisplay: type: string arrDisplay: type: string arrForRollup: type: [array, "null"] minItems: 2 maxItems: 2 items: type: number # CQ-45: first-class ARR (companies.arr / arr_as_of / arr_source). # All optional & nullable; absent/null = Undisclosed. When set, the # portfolio engine (client-side too) derives the ARR-at-risk dollar # range from the tier's published risk-% band. arr: type: [number, "null"] arrAsOf: type: [string, "null"] arrSource: type: [string, "null"] confidence: type: string enum: [High, Medium, Low] engagement: type: string invesqSignal: type: string leadershipFraming: type: string enum: [establish] summary: type: string calloutNote: type: string assessments: type: array items: $ref: "#/components/schemas/PortfolioAssessment" gapNotes: type: object additionalProperties: type: string actionsLog: type: array items: $ref: "#/components/schemas/PortfolioActionLogEntry" portfolioStatus: type: string enum: [Active, Exited, Pre-investment] sectorCategory: type: string enum: [Fintech, Healthtech, Martech, HRtech, Security, Other B2B SaaS, Non-SaaS] investmentDate: type: string required: - id - name - sector - hq - employeesDisplay - arrDisplay - arrForRollup - confidence - engagement - invesqSignal - summary - assessments PortfolioBootstrapFirm: type: object properties: slug: type: string displayName: type: string statusLabel: type: string internalOnly: type: boolean requireLogin: type: boolean description: > When true, the tenant portal requires an authenticated admin session. Absent/false = public (no behavior change). companies: type: array items: $ref: "#/components/schemas/PortfolioCompany" required: - slug - displayName - statusLabel - internalOnly - companies SystemHealthFirmIssue: type: object properties: firmId: type: integer firmName: type: string slug: type: string firmStatus: type: string issue: type: string enum: - discovery_empty - discovery_failed - build_failed - ready_no_active_companies - pending_no_job - candidate_review_needed issueLabel: type: string severity: type: string enum: [broken, needs_action] recoveryUrl: type: string lastJobType: type: string nullable: true lastJobStatus: type: string nullable: true companyCount: type: integer required: - firmId - firmName - slug - firmStatus - issue - issueLabel - severity - recoveryUrl - companyCount SystemHealthReport: type: object properties: ok: type: boolean description: True when no firm is in a broken state checkedAt: type: string description: ISO 8601 timestamp of when this check ran summary: type: object properties: total: type: integer healthy: type: integer needsAction: type: integer broken: type: integer required: [total, healthy, needsAction, broken] issues: type: array items: $ref: "#/components/schemas/SystemHealthFirmIssue" required: [ok, checkedAt, summary, issues] SignalRecord: type: object description: > One structured evidence signal captured for a pillar during pipeline scoring. Evidence metadata only; never feeds composite/tier math. required: [id, companySlug, pillarId, source, direction, confidence, note] properties: id: type: integer companySlug: type: string pillarId: type: string description: One of the 8 portfolio-engine pillar ids source: type: string description: > Where the signal was observed, e.g. "linkedin", "job_posting", "g2_capterra", "press", "crunchbase", "pitchbook", "company_site", "other" dateObserved: type: string nullable: true description: ISO date (YYYY-MM-DD) when the artifact is dated url: type: string nullable: true direction: type: string enum: [positive, negative, neutral] confidence: type: string enum: [High, Medium, Low] note: type: string RavigaSignals: type: object required: [signals] properties: signals: type: array items: $ref: "#/components/schemas/SignalRecord" PortfolioBootstrap: type: object properties: asOfDate: type: string firms: type: array items: $ref: "#/components/schemas/PortfolioBootstrapFirm" required: - asOfDate - firms # ---- CS Rescue Internal dogfood: anonymized BackEngine import ---- BackengineAccountRecord: type: object required: [placeholder, quarterlySentiment, monthlySentiment, emailsReceived, emailsSent, meetings, importedAt] properties: placeholder: { type: string } quarterlySentiment: { type: [string, "null"] } monthlySentiment: { type: [string, "null"] } emailsReceived: { type: [integer, "null"] } emailsSent: { type: [integer, "null"] } meetings: { type: [integer, "null"] } importedAt: { type: string } BackengineSignalRecord: type: object required: [id, pillarId, field, value, dateObserved] properties: id: { type: integer } pillarId: { type: string } field: { type: [string, "null"] } value: { type: [string, "null"] } dateObserved: { type: [string, "null"] } BackengineEvidence: type: object required: [accounts, signals] properties: accounts: type: array items: $ref: "#/components/schemas/BackengineAccountRecord" signals: type: array items: $ref: "#/components/schemas/BackengineSignalRecord" BackengineImportInput: type: object required: [format, content] properties: format: type: string enum: [csv, xlsx] content: type: string description: Raw CSV text, or base64-encoded XLSX bytes. additionalProperties: false BackengineImportResult: type: object required: [shape, rowsRead, uniqueAccounts, duplicatesCollapsed, newPlaceholders, accountsUpserted, signalsInserted] properties: shape: type: string enum: [accounts, signals] rowsRead: { type: integer } uniqueAccounts: { type: integer } duplicatesCollapsed: { type: integer } newPlaceholders: { type: integer } accountsUpserted: { type: integer } signalsInserted: { type: integer } BackengineNameMapRow: type: object required: [id, realName, placeholder, createdAt] properties: id: { type: integer } realName: { type: string } placeholder: { type: string } createdAt: { type: string } # ---- Data Moat action #3: Outcome Data (admin-only) ---- OutcomePillarValue: type: string enum: [org_design, onboarding, health_scoring, renewal_expansion] OutcomeMetricsSnapshot: type: object description: > Entry/milestone retention outcomes, all nullable percentages (null = not yet measured). INTERNAL ONLY — never rendered on tenant pages, client reports, or exported PDFs. properties: grrEntry: { type: number, nullable: true } nrrEntry: { type: number, nullable: true } grr90d: { type: number, nullable: true } nrr90d: { type: number, nullable: true } grr180d: { type: number, nullable: true } nrr180d: { type: number, nullable: true } grrAnnual: { type: number, nullable: true } nrrAnnual: { type: number, nullable: true } UpdateOutcomeMetricsInput: type: object description: Partial update; provided keys overwrite (null clears a value). 0-200 range. properties: grrEntry: { type: number, nullable: true, minimum: 0, maximum: 200 } nrrEntry: { type: number, nullable: true, minimum: 0, maximum: 200 } grr90d: { type: number, nullable: true, minimum: 0, maximum: 200 } nrr90d: { type: number, nullable: true, minimum: 0, maximum: 200 } grr180d: { type: number, nullable: true, minimum: 0, maximum: 200 } nrr180d: { type: number, nullable: true, minimum: 0, maximum: 200 } grrAnnual: { type: number, nullable: true, minimum: 0, maximum: 200 } nrrAnnual: { type: number, nullable: true, minimum: 0, maximum: 200 } CreateOutcomeInterventionInput: type: object required: [pillar, action, occurredOn, owner] properties: pillar: { $ref: "#/components/schemas/OutcomePillarValue" } action: { type: string, minLength: 1, maxLength: 2000 } occurredOn: type: string pattern: '^\d{4}-\d{2}-\d{2}$' description: Calendar day, YYYY-MM-DD. owner: { type: string, minLength: 1, maxLength: 200 } OutcomeInterventionRecord: type: object required: [id, companyId, pillar, action, occurredOn, owner, createdAt, createdBy] properties: id: { type: integer } companyId: { type: integer } pillar: { $ref: "#/components/schemas/OutcomePillarValue" } action: { type: string } occurredOn: { type: string } owner: { type: string } createdAt: { type: string } createdBy: { type: string } AdminCompanyOutcomes: type: object required: [companyId, companyName, firmSlug, metrics, interventions] properties: companyId: { type: integer } companyName: { type: string } firmSlug: { type: string, nullable: true } metrics: { $ref: "#/components/schemas/OutcomeMetricsSnapshot" } interventions: type: array items: $ref: "#/components/schemas/OutcomeInterventionRecord" # ---- Calibration Ledger (Admin Lens only) ---- CalibrationPillarScores: type: object description: > Per-pillar scores keyed by pillar id (org, onboarding, health, escalation, revenue, leadership, planning, ai). Values are the assessment text scores "0" | "1" | "2" | "NA". Observations may be partial (absent keys = not yet observed). additionalProperties: type: string CalibrationPredictionRecord: type: object required: [id, companyId, pillars, composite, band, rubricVersion, predictedAt, lockedAt] properties: id: { type: integer } companyId: { type: integer } assessmentId: { type: integer, nullable: true, description: "Provenance only; null after the source assessment is deleted (e.g. same-day re-score)." } pillars: { $ref: "#/components/schemas/CalibrationPillarScores" } composite: { type: integer, description: Phase 1 tier composite 0-16, NA substituted as 1. } band: { type: string, description: Tier band label frozen at snapshot time. } rubricVersion: { type: string } predictedAt: { type: string } lockedAt: { type: string } createdBy: { type: string, nullable: true } CreateCalibrationObservationInput: type: object required: [pillars, observedAt, source] properties: pillars: $ref: "#/components/schemas/CalibrationPillarScores" observedAt: type: string description: When the real-world signal was observed (ISO timestamp or YYYY-MM-DD). source: { type: string, minLength: 1, maxLength: 200 } note: { type: string, maxLength: 2000, nullable: true } CalibrationObservationRecord: type: object required: [id, companyId, pillars, observedAt, source, note, createdAt, createdBy] properties: id: { type: integer } companyId: { type: integer } pillars: { $ref: "#/components/schemas/CalibrationPillarScores" } observedAt: { type: string } source: { type: string } note: { type: string, nullable: true } createdAt: { type: string } createdBy: { type: string, nullable: true } CalibrationDeltaEntry: type: object required: [pillarId, predicted, observed, delta] properties: pillarId: { type: string } predicted: { type: string, nullable: true, description: Frozen predicted score ("0"|"1"|"2"|"NA"). } observed: { type: string, nullable: true, description: Latest observed score for this pillar. } delta: type: number nullable: true description: Observed minus Predicted (numeric). Null when either side is NA/unobserved. ConfirmationRecipientRoleValue: type: string enum: [portco_cs_lead, pe_operating_partner] ConfirmationStatusValue: type: string enum: [unconfirmed, portco_confirmed, pe_confirmed] description: External Confirmation Status — the existing companies.tier3_status column (CQ-12 vocabulary), NOT a new field. FlaggedPillarEntry: type: object required: [pillarId, label, predicted, reason] properties: pillarId: { type: string } label: { type: string } predicted: { type: string, nullable: true, description: Pillar score at flag time ("0"|"1"|"2"|"NA"). } reason: { type: string, description: Why the pillar was auto-flagged (insufficient_data | low_confidence). } ConfirmationRequestRecord: type: object required: [id, companyId, recipientRole, flaggedPillars, status, expiresAt, createdAt, createdBy, respondedAt] properties: id: { type: integer } companyId: { type: integer } recipientRole: { $ref: "#/components/schemas/ConfirmationRecipientRoleValue" } flaggedPillars: type: array items: { $ref: "#/components/schemas/FlaggedPillarEntry" } status: { type: string, description: pending | submitted | revoked | expired (expired is derived at read time). } expiresAt: { type: string } createdAt: { type: string } createdBy: { type: string, nullable: true } respondedAt: { type: string, nullable: true } CreateConfirmationRequestInput: type: object required: [recipientRole] properties: recipientRole: { $ref: "#/components/schemas/ConfirmationRecipientRoleValue" } expiresInDays: { type: integer, minimum: 1, maximum: 90, description: Link lifetime; default 14 days. } CreatedConfirmationRequest: type: object required: [request, link] properties: request: { $ref: "#/components/schemas/ConfirmationRequestRecord" } link: type: string description: One-time shareable /confirm/{token} URL. The raw token is never stored or shown again. AdminCompanyConfirmation: type: object required: [companyId, companyName, confirmationStatus, flaggedPillars, requests] properties: companyId: { type: integer } companyName: { type: string } confirmationStatus: { $ref: "#/components/schemas/ConfirmationStatusValue" } flaggedPillars: type: array items: { $ref: "#/components/schemas/FlaggedPillarEntry" } description: Auto-flagged live from the latest scored assessment (Insufficient Data/NA pillars). requests: type: array items: { $ref: "#/components/schemas/ConfirmationRequestRecord" } ResolutionEventTypeValue: type: string enum: [leadership_departure, cs_layoffs, rating_drop, funding_cs_rebuild, acquisition_distress] CalibrationVerdictValue: type: string enum: [confirms, contradicts] CreateResolutionEventInput: type: object required: [eventType, eventDate, source, pillarId, verdict, note] properties: eventType: { $ref: "#/components/schemas/ResolutionEventTypeValue" } eventDate: type: string pattern: '^\d{4}-\d{2}-\d{2}$' description: Calendar day the event occurred, YYYY-MM-DD. source: { type: string, minLength: 1, maxLength: 200 } pillarId: { type: string, minLength: 1, maxLength: 50 } verdict: { $ref: "#/components/schemas/CalibrationVerdictValue" } note: type: string minLength: 1 maxLength: 500 description: One line on whether/why the event confirms or contradicts the original pillar prediction. url: { type: string, nullable: true, maxLength: 2000 } ResolutionEventRecord: type: object required: [id, companyId, pillarId, eventType, verdict, eventDate, source, note, createdAt] properties: id: { type: integer } companyId: { type: integer } pillarId: { type: string } eventType: { $ref: "#/components/schemas/ResolutionEventTypeValue" } verdict: { $ref: "#/components/schemas/CalibrationVerdictValue" } eventDate: { type: string, nullable: true } source: { type: string } note: { type: string } url: { type: string, nullable: true } createdAt: { type: string } AdminCompanyCalibration: type: object required: [companyId, companyName, firmSlug, prediction, observations, deltas, resolutionEvents] properties: companyId: { type: integer } companyName: { type: string } firmSlug: { type: string, nullable: true } prediction: oneOf: - $ref: "#/components/schemas/CalibrationPredictionRecord" - type: "null" observations: type: array items: $ref: "#/components/schemas/CalibrationObservationRecord" deltas: type: array description: Per-pillar Observed minus Predicted, computed at read time (never stored). items: $ref: "#/components/schemas/CalibrationDeltaEntry" resolutionEvents: type: array items: $ref: "#/components/schemas/ResolutionEventRecord" # ---- CQ-37 tier model ---- Tier2ConnectorValue: type: string enum: [backengine, crm, conversation_intelligence, product_telemetry] Tier2ConnectorStatusValue: type: string enum: [not_connected, partial, connected] Tier3StatusValue: type: string enum: [unconfirmed, portco_confirmed, pe_confirmed] Tier2Snapshot: type: object required: [backengine, crm, conversation_intelligence, product_telemetry, connectedCount, totalCount] properties: backengine: { $ref: "#/components/schemas/Tier2ConnectorStatusValue" } crm: { $ref: "#/components/schemas/Tier2ConnectorStatusValue" } conversation_intelligence: { $ref: "#/components/schemas/Tier2ConnectorStatusValue" } product_telemetry: { $ref: "#/components/schemas/Tier2ConnectorStatusValue" } connectedCount: type: integer description: Connectors with status "connected" (partial does not count). totalCount: type: integer TierSummaryRow: type: object required: [companyId, companyName, companySlug, companyStatus, firmName, firmSlug, tier1Complete, tier2, tier3Status, pendingDisputes] properties: companyId: { type: integer } companyName: { type: string } companySlug: { type: [string, "null"] } companyStatus: { type: string } firmName: { type: string } firmSlug: { type: string } tier1Complete: type: boolean description: Derived — true when the company has at least one Phase 1 assessment row. tier2: { $ref: "#/components/schemas/Tier2Snapshot" } tier3Status: { $ref: "#/components/schemas/Tier3StatusValue" } pendingDisputes: { type: integer } TierSummaryPage: type: object required: [total, limit, offset, rows] properties: total: { type: integer } limit: { type: integer } offset: { type: integer } rows: type: array items: $ref: "#/components/schemas/TierSummaryRow" UpdateTier2Input: type: object required: [connector, status] properties: connector: { $ref: "#/components/schemas/Tier2ConnectorValue" } status: { $ref: "#/components/schemas/Tier2ConnectorStatusValue" } note: { type: [string, "null"] } UpdateTier3Input: type: object required: [status] properties: status: { $ref: "#/components/schemas/Tier3StatusValue" } note: { type: [string, "null"] } CreateTierDisputeInput: type: object required: [reason] properties: field: type: string description: Disputed field; defaults to tier3_status (the only auto-applicable field today). default: tier3_status reason: { type: string, minLength: 3 } proposedValue: { type: [string, "null"] } ResolveTierDisputeInput: type: object required: [action] properties: action: { type: string, enum: [apply, reject] } newValue: oneOf: - $ref: "#/components/schemas/Tier3StatusValue" - type: "null" description: Required for apply when the dispute has no proposedValue. note: { type: [string, "null"] } TierDisputeRecord: type: object required: [id, companyId, companyName, firmSlug, field, reason, proposedValue, status, createdAt, resolvedAt, resolvedBy, resolutionNote] properties: id: { type: integer } companyId: { type: integer } companyName: { type: string } firmSlug: { type: string } field: { type: string } reason: { type: string } proposedValue: { type: [string, "null"] } status: { type: string, enum: [pending, applied, rejected] } createdAt: { type: string } resolvedAt: { type: [string, "null"] } resolvedBy: { type: [string, "null"] } resolutionNote: { type: [string, "null"] } TierAuditRecord: type: object required: [id, companyId, field, oldValue, newValue, editor, note, disputeId, createdAt] properties: id: { type: integer } companyId: { type: integer } field: { type: string } oldValue: { type: [string, "null"] } newValue: { type: [string, "null"] } editor: { type: string } note: { type: [string, "null"] } disputeId: { type: [integer, "null"] } createdAt: { type: string } TierMutationResult: type: object required: [companyId, tier2, tier3Status, auditRowId] properties: companyId: { type: integer } tier2: { $ref: "#/components/schemas/Tier2Snapshot" } tier3Status: { $ref: "#/components/schemas/Tier3StatusValue" } auditRowId: type: [integer, "null"] description: The audit-log row this mutation wrote. Every successful mutation (including a reject resolution) writes one; nullable only for forward compatibility.