Skip to content

feat(patches): let agents discover company patches and their data definitions - #263

Merged
allisonmahmood merged 2 commits into
mainfrom
portal/250-read-path
Sep 16, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
portal/250-read-path

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Agents can discover shared tables through the catalog, but cannot browse the company's patches or inspect their cumulative data definitions.

Add three machine-token read routes over one openability-gated query: list patches, read patch details, and inspect a table or file store. Reads retain omitted definitions and older-version declarations, distinguish unavailable inventory from empty inventory, and report state mismatches without exposing inaccessible patches. Catalog and the existing inventory route stay unchanged.

Stacked on portal/249-primitive-descriptions; that branch is this PR's base. The diff contains only issue #250's read path, not the preceding lifecycle and primitive-description work.

Closes #250.

Verification:

  • Full offline suite: 781 tests passed across 77 files.
  • Post-review focused suite: 95 tests passed across 5 files.
  • Typecheck and lint passed.
  • Live HTTP smoke checked all three read levels, caching, authorization, state errors, overlong references, and catalog compatibility.
  • Standards and spec review completed; confirmed findings fixed.

Implemented with OpenAI GPT-6 Astra in the Oh My Pi coding harness.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 15, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 049217087e31d198f21bd14061b3f6f0a199cd6c against origin/portal/249-primitive-descriptions at 4b3b9e3dd4537caa3e969e679bdd48e3c9acfa5c, using issue #250 and its referenced spec sections. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings. The shared query, openability predicate and dependant edges are explicitly requested by #250, including their later portal use.

Spec

No merge-blocking intent findings. The three read levels implement the requested visibility and state-resolution rules, cumulative inventory, retained-version reads, declaration hints and primitive metadata. The catalog and existing inventory route remain unchanged; connections and CLI work stay outside this ticket.

Verification: 94 tests passed across Patches.test.ts, PatchesApi.test.ts, schemas.test.ts and ApiGuard.test.ts. Separately confirmed that docs/API.md exactly matches the API schema renderer. No source changes made.

Summary: Standards 0 blockers; Spec 0 blockers. No merge-blocking issue found within either axis.

@allisonmahmood allisonmahmood left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Code review vs #250

#250 asked for the agent discovery API: one openability-gated read in Patches, three machine-token GET levels, company-readable cumulative inventory, retained-version reads, state-aware resolution, catalog left alone. That intent landed. The portal and patchy list were correctly left for later tickets.

The method is “one service function every route calls,” not one SQL query. List and primitive pay for inventory, retained reads, and dependant edges the wire then drops.


Intent vs #250

The ticket’s Done-when list is implemented: unopenable patches are absent and 404; names resolve only among non-deleted patches; retained-version reads and omitted tables survive a later publish; unavailable company database → inventory: null; the three wrong_state 409s name the actual state; purgeAt is deletedAt + 30 days; the guard’s 414 covers :patchRef; tokens only.

Catalog and the owner inventory route are unchanged. Connections hints are not here. Product copy moved Sharing and finding from decided toward built for the API, with patchy list still planned.

Two places the implementation is thicker or blurrier than the ticket’s intent:

  1. The “one read query” also computes live dependant edges for the future portal, then every discovery route runs that query. Detail correctly omits dependants from the wire; list and primitive still do the work.
  2. A source missing from the caller’s openable set is reported as gone with no name — including disabled, unopenable, and foreign patches that still exist. The ticket’s gone rule is about the sweep, not every hidden source.

Method

Verdict: sound with costs. Right shape for two databases and a JS openability predicate; list over-fetch and a second inventory door are the costs.

Patches.read is a company-wide platform SELECT (disabled_at IS NULL only), then in-memory openability / state / mine / name-vs-id resolution, then one withCompany lease and a per-patch Inventory.read (each already takes withPatchLock). Inventory cannot join the platform SELECT (ADR-0009). Openability in JS after the fetch is the right gate for today’s “every company patch is openable” and for alternate-layer tests: unopenable never becomes wrong_state.

State filtering has to stay in JS if the same load is used to annotate reads (retired/deleted sources) and dependants (live readers while listing a retired source). That is why list cannot cheaply push state=live into SQL while still being “the one query.”

Token-only lives at the API/guard, not the service. private, no-store is on all three levels. Portal can call read() as a superset of the wire.

Costs:

  • Inner SqlError on one patch’s inventory becomes null and the loop continues, so a live query/lock fault looks like unknown inventory.
  • companyInventory is the ticket’s openability-gated door (null when unavailable). The owner inventory() route still uses lockOpenable and maps no-placement to empty. Same data, different gates and unavailability. Future narrower sharing will leak through GET /api/patches/:patchId/inventory if that route is not gated the same way.
  • Discovery dependants are live openable readers at patch+table grain, inverted from reads. Lifecycle dependantRows is serving patches, no openability, no table on the refusal body.

YAGNI

Verdict: not simple enough.

The ticket asked for one shared query including dependant edges “shared later by the portal.” That was implemented as a god-function, then every route was wired through it.

companyPatchRows always loads every non-disabled company patch and correlated-jsonb_aggs retained-version uses. read then walks every openable patch for dependants and fans out inventory. PatchesApi.list still passes every matching id. Primitive loads the same graph to pick one table.

Smaller, still honest to the ticket: list = patches ⋈ owners ⋈ current version. Detail = one patch + reads + one inventory. Primitive = resolve, then one inventory. Compute dependants when a portal caller exists. Lifecycle already has dependantRows.

companyInventory has no production caller; handlers use read().inventory. The ticket did ask for that method, so it is not invented — but wrapping companyInventories([id]) and then sending list/primitive through the full read is extra.

Guard PATCH_ROUTES rewrite is the smallest 414 fix: the old :patchId string set cannot match :patchRef + /primitives/:name. Mapping helpers (summary / tableSummary / primitive columns) match three wire types; leave them.


Standards

Effect conventions: no hard violations. Namespace imports, inline Context.Service, yield* in make, Effect.catchTags, no runPromise / constructor-injected services. Openability as Context.Reference matches PatchesConfig.release. canOpen is a pure callback (allowed). Layer.succeed only in tests. No ui-consistency findings.

Judgement calls

packages/patches/src/Patches.ts — Speculative Generality (dual openability)
Openability (L281–284) is never yield*'d by read / companyInventory. Those take ReadAccess.canOpen instead; PatchesApi closes over the Reference (L319, L574). Two injection paths for one policy. Fix: yield* Openability inside read/companyInventory and drop canOpen, or drop the Reference and keep the callback until a second consumer needs a layer override.

Patches.ts companyInventory (L572–575, L1122–1131) — Speculative Generality
Public on Patches; only Patches.test.ts calls it. Handlers use read(), which already returns inventory. Fix: unexport / keep private until a production caller exists. (Ticket #250 did name this method; the smell is that the handlers never use it.)

Patches.ts read (L1133–1211) vs list handler — Speculative Generality (cost of one query)
Product wants one openability-gated read, including dependants for a future portal. List still materializes inventory, retained reads, and dependants, then discards them (PatchesApi.ts L567–587). Acceptable if the shared query is the spec; otherwise parameterize what to load.

PatchesApi.ts L211–220 — Speculative Generality
Discovery WrongState prose: pass --state ${…}. No patchy list yet (ADR-0004 / product: CLI planned). Agents on HTTP see a query state=, not a flag. Fix: repair text for the wire (state=retired|all), keep --state for the CLI ticket.


Spec

Done-when is met in code and tests: alternate Openability hides a patch from the list and 404s by name; names resolve only among non-deleted; retained-version reads and omitted tables survive a later publish; unavailable company DB → inventory: null; retired-name/live, deleted-id without all, live-name/retired → 409 wrong_state with state; purgeAt = deletedAt + 30d; guard 414 covers :patchRef; machine-token only; PrimitiveDetail optionalKey default (schema round-trip keeps explicit null); catalog and connections group untouched.

(a) Missing / partial

None of the ticket’s Done-when items are absent. HTTP tests never assert a gone read row (state: "gone", name omitted); only Patches.read does. Handler passes reads through PatchRead, so the wire path is there, untested at the route.

(b) Scope creep

No connections routes/hints, no patchy list, catalog kept.

The shared query does compute live dependant edges (asked by §13 / the ticket: “the live dependant edges”). They are correctly omitted from PatchDetail (“No versions, no dependants.”).

(c) Implemented, but wrong

1. Nested sources coerced to gone.
§7: reads carry “its name when it still exists” and gone as a source state. Ticket: “A gone source has state gone and no name.”
read maps any source missing from openable to { state: "gone" } with no name — including disabled, unopenable, and foreign patches that still exist. Spec: “only a gone patch ever tells an agent to remove patch from patchy.json.” Foreign names should stay hidden (“never another company’s”); disabled/unopenable in-company sources should not look swept.

2. Dependant edges filtered by the caller’s canOpen.
§13: the one query includes “the dependant edges” for the portal (“which patches read its shared tables”). Visibility 404 applies to listing a patch, not to naming a live dependant of one you can already see. The query drops dependants canOpen rejects (test read-dependant-source / hidden). Today every member can open every company patch, so this only bites later sharing.

3. Glossary vs lifecycle wire.
Dependant now says retire/delete “list these distinct patch-and-table dependencies.” Lifecycle has_dependants is still { patchId, name, owner } with no table (§3: “by patch name and owner”). Discovery’s internal edges have table; the refusal body does not.


Surfaces

Wire, glossary, product, CONTEXT-MAP, and the 414 table were hit. CLI, migrations, served pages, and repo layout correctly untouched. docs/API.md is generated from PatchyApi.

The --state string on wrong_state is the one surface miss: ADR-0002 refusals are { ok: false, error, code, state }; docs/API.md documents ?state=. Copy-ready patchy add shared-table … hints are in-spec; this error string is not.


Tests

Done-when is mostly proven with focused tests at service + HttpApiTest, 414 at the guard. Not slop. Real holes: gone-without-name on the HTTP reads path, and default: null never published through the primitive mapper (schema-only). purgeAt is asserted twice with the same arithmetic.


Standards: 0 hard / 4 judgement — worst: CLI --state copy on the HTTP wrong_state body, plus two injection paths for one openability policy.

Spec: 4 findings — worst: disabled/unopenable/foreign sources coerced to gone.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed the conversation review and Reviews-tab findings in 1f5f321. There were no inline review comments.

Fixed

  • Source lifecycle versus access: retained reads now preserve an existing same-company source's actual lifecycle even when it is disabled or hidden. Names remain redacted, direct access remains 404, and inaccessible sources remain absent from listings. The regression failed before the fix and passes afterward. Sources absent from the company still report gone; discovery does not query foreign-company metadata to distinguish absence from inaccessibility.
  • HTTP state advice: wrong-state errors now recommend ?state=retired or ?state=all, rather than a CLI flag that this ticket does not implement.
  • Dependant vocabulary: corrected the glossary to distinguish lifecycle warnings, which identify distinct patches and owners, from discovery's per-table associations.
  • Swept-source HTTP coverage: extended the retained-read API scenario through deletion, the recovery window, and sweeping. The response preserves the declaration with state: "gone" and no source name.

Kept, with reasons

  • Shared superset query and public companyInventory: both are explicit feat(patches): the read path: GET /api/patches at its three levels over the company-readable inventory #250 requirements. Splitting selectors or adding loading modes without measured need would undermine the shared read path intended for the portal.
  • Openability callback plus HTTP Reference: the Reference supplies the HTTP adapter's policy; the service callback lets other consumers provide their credential-specific policy. These are not separate access rules.
  • Openability-filtered discovery dependants: returning hidden patch names and owners would disclose inaccessible metadata. Lifecycle damage checks still include all live dependants, so hiding a dependant cannot bypass force safeguards.
  • Legacy catalog and /inventory: deliberately unchanged by this ticket's compatibility scope. A future narrower sharing policy must cover those legacy metadata routes before being enabled.
  • Unavailable company inventory as null: this distinguishes an operationally unavailable company database from an empty inventory. Platform query failures remain typed failures; company identity mismatches are not converted into empty results.
  • Null-default codec coverage: publication currently rejects null defaults. Weakening publication or injecting invalid persisted metadata just to exercise that mapper branch would test an unsupported state. The codec still distinguishes absent defaults from explicit null, and the mapper preserves property presence.
  • Service and HTTP purge-time assertions: these exercise separate consumer boundaries; the small arithmetic duplication does not warrant another abstraction.

Verification

  • Affected service/API suites: 72 tests passed.
  • Real HTTP smoke against this checkout's isolated dev instance: a disabled, retired source remained retired in the consumer's retained read without a name; direct access returned 404, listing omitted it, and the response was private, no-store. Wrong-state advice used the HTTP query parameter. The instance was stopped and the temporary smoke script removed.
  • pnpm lint and pnpm typecheck passed.
  • Full offline suite: 781 tests across 77 files passed with pnpm test --maxWorkers=4. The first default-concurrency local run hit the existing 10-second startup-subprocess timeout in one missing-config test. That file passed all 9 tests in isolation, then the complete bounded run passed. No timeout or assertion was relaxed. Both default CI test matrices also passed.
  • Latest CI run succeeded on 1f5f321: test (22), test (24), lint, cli-smoke, clerk-live, dependency-review, and postgres-concurrency; the separate label check passed too. These cover the repository's main-branch required gate set. The current stacked base itself has no branch-specific required checks.

No unresolved review blockers. GitHub reports CLEAN/MERGEABLE. This remains stacked on portal/249-primitive-descriptions; I have not merged it.

@allisonmahmood
allisonmahmood force-pushed the portal/249-primitive-descriptions branch from 4b3b9e3 to 2e93f4d Compare September 16, 2026 16:00
Base automatically changed from portal/249-primitive-descriptions to main September 16, 2026 16:27
Implement #250 with shared openability-gated reads, cumulative inventory, token-only detail routes, and state-aware resolution.
Separate retained source state from discovery openability while keeping inaccessible names and foreign metadata hidden. Use HTTP state query advice, cover swept-source reads over HTTP, and clarify dependant terminology.
@allisonmahmood
allisonmahmood merged commit 208f744 into main Sep 16, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the portal/250-read-path branch September 16, 2026 16:34
allisonmahmood added a commit that referenced this pull request Sep 16, 2026
Agents need to discover company connections and inspect their schemas
without going through the SDK catalog.

Adds member-readable connection routes with connection state,
declaration hints, offered integrations and immutable snapshots. Missing
snapshots return null. Removes the SDK catalog route and keeps the
existing CLI catalog and add commands working against the replacement
reads until the discovery CLI lands.

Stacked on `portal/250-read-path` (#263). This PR targets that branch,
not `main`, and contains only the connections work for #251.

Closes #251.

Verification:
- Typecheck and lint passed.
- Full offline suite passed: 795 tests across 78 files. After review
corrections, all 166 tests across the five affected suites passed.
- Isolated runtime smoke checks covered member-token reads, catalog 404,
and packed CLI shared-table and Postgres declarations.
- Standards and spec re-reviews have no remaining findings.

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

Labels

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(patches): the read path: GET /api/patches at its three levels over the company-readable inventory

1 participant