Skip to content

feat(integrations): connect company Postgres databases - #217

Merged
allisonmahmood merged 4 commits into
mainfrom
sdk/201-integrations
Sep 12, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
sdk/201-integrations

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Company admins have no way to connect Postgres databases or publish patches bound to their discovered schemas.

Adds secure company connections with encrypted credentials, verified TLS and public-address checks, immutable schema discovery, and publish-time connection/revision checks. The company pages cover the full administration lifecycle. Postgres operations remain deferred to ticket 9.

Stacked on #216 (sdk/200-shared-tables); this PR targets that branch. Includes the page polish in df56d39. Uses migration 0007_integrations_baseline, after the runtime baseline.

Closes #201.

Verified on the complete branch, including the page polish: pnpm test (540 tests), pnpm typecheck, and pnpm lint.

Implementation and PR prepared with GPT-6 Astra in Oh My Pi; page polish contributed with Claude Fable 5.1.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 10, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed git diff origin/sdk/200-shared-tables...HEAD at df56d39559d8479daed0b9ce15fe12db012e5a58 against issue #201 and its referenced integration decisions. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings. Reviewed the Effect service boundaries, credential/network isolation, persistence and locking, and reuse of the existing session and page shell conventions. The definition and credential-free dev layer are explicitly requested; deferred Postgres operations remain unavailable.

Spec

No merge-blocking intent findings. Connection administration and its reverse states, credential protection, immutable discovery revisions, and publish-time connection/revision checks match this ticket's scope. Reviewed the affected wire/CLI, migration wiring, pages, dev keyring, vocabulary/product docs and package-layout surfaces. No new company-database caller is introduced. Operations, generation and fixtures remain deferred as specified.

Verification run:

  • pnpm --filter @patchy/integrations test — 37 passed.
  • pnpm --filter @patchy/patches exec vitest run src/PatchesApi.test.ts -t 'Postgres declaration publishing' — 2 passed, 22 unrelated tests skipped.

Verification was offline and isolated; no live-source or browser verification was performed.

Summary: Standards: 0 blockers, worst: none. Spec: 0 blockers, worst: none.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 217 vs #201

Reviewed origin/sdk/200-shared-tables...HEAD (3 commits, +4541/−72). Axes: Standards, Spec (#201 plus the #180 Binding/Discovery decisions it cites), method/YAGNI, Effect services, UI consistency, hit-every-surface, and credential/network correctness.

#201’s intent is the definition helper, company Postgres connections, encrypted credentials, connect flow, immutable discovery, admin pages, and publish binding. Ticket 9 owns operations, generated clients, and fixtures. “Admitted at merge” is a declaring publish that resolves and then sits inert. That split is what landed.


Standards

Effect services (ConnectionStore, CredentialKeys, Source, SourceClient, SourceNetwork) match the review spec: one-file order, yield* deps, Config.redacted, catchTags, it.layer, no runPromise in domain. Pages go through Auth pageResponse → htmlPage; user text is escaped. Wire shapes live in packages/api. Migration 0007_integrations_baseline is registered on the server, the dev runner, and the vitest template.

No UI consistency findings. No hard ADR-0002 / 0003 / 0004 / 0009 breaches.

  1. Speculative Generality (judgement; CLAUDE.md YAGNI / “smallest model”). packages/integrations/src/definition.ts (defineIntegration, operation) and packages/integrations/src/postgres/index.ts are unused by ConnectionStore, the pages, or publish. Production discovery is Source.inspect. The registry still requires operations: {} plus generate/dev that always fail. CONTEXT.md already defers handlers and generated clients. Drop the registry until a second integration or a real generate/dev consumer exists. (PostgresOperationsUnavailable.code = "source_unavailable" would also collide with SourceUnavailable if it ever hit the wire.)

  2. Feature Envy (judgement; capability ownership). Delete reaches into Patches’ tables instead of a Patches query (declaringPatchRows already walks manifest->'uses'):

const references =
  yield* sql`SELECT 1 FROM patch_versions v JOIN patches p ON p.id = v.patch_id
    WHERE p.company_id = ${input.companyId} AND EXISTS (
      SELECT 1 FROM jsonb_each(v.manifest->'uses') AS declaration
      WHERE declaration.value->>'kind' = 'postgres' AND declaration.value->>'id' = ${input.id}

Ask Patches whether any version declares the connection.

  1. Package boundary (judgement). Serving does not depend on @patchy/integrations, but tests reach in relatively because Patches.layer now needs ConnectionStore:
import { ConnectionStore } from "../../integrations/src/index.js";

Add a devDependency and import the package name.

  1. ConnectionStorageFailed.operation is Schema.String (convention). A shared storage failure should use a closed multi-value discriminator (list / get / connect / …), same shape as other service-level storage errors.

Spec

Intent of #201 is the definition, company connections, credentials, connect flow, discovery, and publish binding — not Postgres operations, generated clients, or fixtures.

  1. Partial vs Binding. The integration definition, the Postgres integration and its fixture #180: “At publish the server resolves postgres/warehouse to the connection id and the current snapshot revision.” feat(integrations): the integration definition, connections on /company, credentials and discovery #201: “the handle must name a connected connection (connection_not_connected) … the manifest carries the connection id and the revision.” Incoming PostgresDeclaration already requires id + revision; ConnectionStore.resolve loads by id, then checks handle/status/revision. A handle-only declaration is a schema failure, not a server resolve. That matches this PR’s product text (verify the triple) more than The integration definition, the Postgres integration and its fixture #180’s resolve-from-handle. Until ticket 9 stamps id/revision, a declaring publish only works if the client already knows the id — and the detail page labels handle and schema revision but not the connection id (it lives only in the URL).

  2. AAD does not match the spec. feat(integrations): the integration definition, connections on /company, credentials and discovery #201: “associated data company id + connection id + integration.” CredentialKeys AAD is JSON.stringify([companyId, id, integration, keyId]). Extra keyId is stricter and probably better; it is not the specified AAD.

  3. Decrypt sites vs the closed list (judgement, not a leak). feat(integrations): the integration definition, connections on /company, credentials and discovery #201: “decryption only at connect test, discovery, rotation and pool creation.” Stored ciphertext is decrypted in test, refresh, and reconnect. rotate tests the submitted string and never decrypts the stored secret. Reconnect has to decrypt to re-check TLS/DNS/role; treat it as a connect test of stored credentials. No decrypt on list/get/pages.

  4. Small scope beyond feat(integrations): the integration definition, connections on /company, credentials and discovery #201. Discovery drops query / schema-name collisions as reserved_name — generated-surface work from The integration definition, the Postgres integration and its fixture #180, not this ticket’s snapshot list. Discovery audit (postgres.discover, credentialKind: "admin") is the right attribution; the recent-calls UI is correctly deferred.

  5. Migration name — not a defect. feat(integrations): the integration definition, connections on /company, credentials and discovery #201 asks for 0005_integrations_baseline. The ledger already has company-database 5 and runtime 6; 0007_integrations_baseline is the correct next number.

Covered: type-level defineIntegration / operation; boundary codes in packages/api; postgres module with redacted URL, snapshot+discover, operations: {}; prod+dev ConnectionStore; PATCHY_CREDENTIAL_KEYS; AES-256-GCM; keyring rotation without re-encrypt-on-read; snapshot contents/bounds/immutability/failed refresh leaves current; /company/connections reverse states (admins mutate, members read); connection_not_connected / stale_generated (“the warehouse schema changed; run patchy refresh”); no postgres ops in the handler map; no CLI secret path.


Method and YAGNI

The live path is the right size: one ConnectionStore for lifecycle + publish lock + a metadata-only layerDev, CredentialKeys as a module (encrypt/decrypt has one consumer; config has a second at startup), pg for the untrusted source (TLS verify-full, public-IP pin, no pool, destroy-on-cancel) while platform rows stay on @effect/sql-pg, typed Snapshot as the stored contract, SourceNetwork as a test seam rather than a fourth product. Hardcoded 'postgres' on the row and the AAD is honest until a second integration exists. Pages compose the shell; company list/row/actions moved into htmlPage because two pages share them.

The plugin shell is not load-bearing. defineIntegration / operation are identity functions with a 15-parameter generic. Production never calls postgres.generate, postgres.dev, postgres.operations, or postgres.metadata.discover. Empty operations plus failing generate/dev match the ticket’s refusal, but wrapping that in an unused integration SDK is ticket-9 machinery sitting in this PR. #201 asked for the helper; it is still unused. Keep it as the contract ticket 9 will fill, or delete it until that ticket actually needs it — do not grow it.

Smaller YAGNI:

  • connections.metadata JSONB is written on insert/update and never selected. Current snapshot already lives in connection_snapshots keyed by metadata_revision. Drop the denormalized column.
  • SourceClient.layer is never referenced; Source.make calls SourceClient.make. Delete the layer.
  • Modes extends ReadonlyArray<"company" | "personal"> while the row is CHECK (mode = 'company'). Drop personal from the helper until a second mode exists.

Do not split ConnectionStore. Gathering connect/test/rotate/retarget/refresh/disconnect/reconnect/describe/delete/resolve in one service is the YAGNI win.


Surfaces and security (short)

Hit-every-surface is mostly done (wire, CLI --json + ADR-0004 + skill hash, dev keyring, product.md, Integrations glossary, reverse states, README layout). Two glossary misses: packages/companies/CONTEXT.md still describes yesterday’s admin (no connections); packages/sql/README.md migrate({…}) example still omits Integrations (SQL CONTEXT.md already says 7).

Credential/network: no secret leak, no decrypt-on-read, no DNS-rebinding SSRF found. Resolve → refuse any non-public A/AAAA → connect to that IP; lookup again on every inspect/test. sslmode=require refused; omitted sslmode still forces verify-full. Superuser / CREATEDB / CREATEROLE checked on CURRENT_USER only (does not walk pg_auth_members). Form credentials is a plain Schema.String until Redacted.make — not rendered today; a future logger on SchemaError would print the URL.


Standards: 4 findings, worst is unused defineIntegration registry (speculative generality).
Spec: 4 findings (plus one justified migration rename), worst is publish binding as id-verify rather than handle-resolve, with the connection id unlabeled on the page.

@allisonmahmood

allisonmahmood commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner Author

Reviewed both PR-comment reviews: Astra and Grok. Fixes are in d43350b; df56d39's page polish is preserved.

Fixed

  • Unlabelled connection ID: the detail page now labels the escaped, copyable ID beside the schema revision, for admins and members. Agents can obtain the resolved identity before feat(sdk): catalog, generate and project skills; patchy init, refresh, add and remove #204 exists. The HTTP acceptance test checks the labelled value for both roles.
  • Unused metadata copy: removed connections.metadata and its duplicate writes. Immutable connection_snapshots, selected by metadata_revision, remain the authority. This changes the unmerged 0007 baseline; no live database was touched.
  • Unused client layer: removed SourceClient.layer; scoped construction already uses SourceClient.make.
  • Premature personal mode: narrowed the definition helper to company connections, matching the persisted model.
  • Serving test package boundary: declared @patchy/integrations as a devDependency and replaced the relative source import with the package import; lockfile updated.
  • Storage failure discriminator: ConnectionStorageFailed.operation is now a closed schema union, also used to type the error mapper.
  • Documentation omissions: Companies' member/admin glossary includes connections, and SQL's migration example includes Integrations.

Kept as is, with reasons

  • Resolved-ID verification at publish: spec §8 explicitly says each uses entry includes the resolved ID and revision copied from generation, and “publish requires them.” Verifying company, ID, handle, connected state and exact revision is the specified contract—not a handle-only lookup. Both preflight and transaction-time checks stay.
  • defineIntegration / operation: feat(integrations): the integration definition, connections on /company, credentials and discovery #201 explicitly requires this contract; feat(integrations): the Postgres integration: read-only execution, the generated surface and its fixture #202 fills it. Empty operations and explicit generation/dev refusals accurately represent today's admission. Sharing the normalized source_unavailable code is not a wire collision between internal error tags.
  • Deletion's historical-reference query: it checks every stored version under the connection row lock, coordinated with publishing. Patches already depends on Integrations; calling a Patches service here would introduce a dependency cycle. Keep the small transactional query and the unsplit ConnectionStore; the publish/delete race test covers it.
  • Key ID in AES-GCM associated data: this binds the ciphertext to the selected key as well as company/connection/integration. Removing it would weaken authentication and invalidate existing ciphertext unnecessarily; old-key decryption remains tested.
  • Reconnect decryption: reconnect is a connect test of stored credentials and must recheck DNS/TLS/role before restoring access. Rotation tests the submitted replacement, so it does not need to decrypt the old secret. Metadata reads remain credential-free.
  • Reserved-name exclusions and discovery audit: the referenced §6 generated surface reserves query; naming collisions as exclusions avoids silently changing names. Discovery remains admin-attributed; query operations and recent-calls UI stay deferred.
  • Migration 0007: company-database and runtime already occupy 0005/0006. Keep the contiguous baseline number.
  • Role/form security notes: checking CURRENT_USER's flags matches the stated admission rule; this is not a role-membership security audit. Form SchemaErrors are converted to generic refusals without logging or returning their causes, and credentials are redacted before source operations. The hypothetical future logger is not a present leak.

Astra reported no blockers; no additional changes were necessary for that review.

Verification

  • pnpm test: 540 passed across 56 files, including lifecycle/snapshot/keyring, publish checks and the publish/delete locking race.
  • pnpm typecheck (including definition contract checks) and pnpm lint: passed.
  • Browser: labelled ID visible for admin and member; member has no management forms; 390px layout has no horizontal overflow.
  • CI run 34533063977 completed successfully on d43350b. All seven checks passed: Node 22 tests, Node 24 tests, lint, Clerk live, CLI smoke, dependency review and label. GitHub reports no branch-required checks; every configured check is green.
  • GitHub reports MERGEABLE / CLEAN against sdk/200-shared-tables. No newer review findings or unresolved blockers. Ready to merge into the stacked base; not merged.

allisonmahmood and others added 4 commits September 12, 2026 13:57
Status is a shell pill, timestamps read as minutes in UTC, the detail
page lists its facts in a two-column grid, breadcrumbs link both levels,
completed actions get a green notice, and the company-wide access note
sits with the credentials field it is about on connect and retarget.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@allisonmahmood
allisonmahmood merged commit aea07d5 into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/201-integrations branch September 12, 2026 12:01
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patches can declare company Postgres connections, but cannot yet read
from them.

This adds bounded, read-only Postgres operations using each published
version's pinned schema and the connection's live credentials. Generated
typed clients and native PGlite fixtures share the same handlers and
type mapping. Attributed runtime calls appear in the admin's
recent-calls view.

**Stacked on #217 (`sdk/201-integrations`).** This PR targets that
branch; the earlier runtime, primitive and connection-management work
belongs to the parent stack.

### Validation
- `pnpm lint`
- `pnpm typecheck`
- `pnpm test` — 572 tests across 62 files
- Native Postgres execution regressions, generated-client/PGlite smoke,
and desktop/mobile connections-page checks
- Standards and Spec self-review findings resolved

The unmerged `0006_runtime_baseline` gains the call outcome field and
recent-calls index without a new migration ID. Existing disposable dev
databases need a reset.

Closes #202.

Implemented with GPT-6 Astra in Oh My Pi.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(integrations): the integration definition, connections on /company, credentials and discovery

1 participant