Skip to content

feat(primitives): let patches look up and assign company members - #449

Merged
allisonmahmood merged 3 commits into
mainfrom
tier2/410-member-directory
Oct 1, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
tier2/410-member-directory

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches need to look up company members and store member assignments without losing historical references when someone becomes inactive.

Adds a declared member directory for tier 1 clients and all tier 2 handler kinds. Candidate searches return active members, while resolution retains inactive members. New or changed assignments require active members; unchanged assignments remain valid. Committed directory changes refresh subscriptions. Includes CLI generation, local dev identities, documentation, and the member skill.

This PR is stacked on tier2/409-staged-uploads and targets that branch. The diff contains only the member-directory implementation.

Closes #410.

Verification

  • pnpm test: 1,553 tests passed across 137 files.
  • PostgreSQL concurrency suites: 27 tests passed.
  • pnpm typecheck and pnpm lint passed.
  • Disposable PostgreSQL/workerd smoke covered tier 1 assignments and tier 2 directory callbacks.
  • Standards review findings fixed and re-reviewed; spec review found no defects.

Implemented with openai-codex/gpt-6-astra using the omp harness.

@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:docs Touches the docs area area:primitives Patch tables and files size:xl Over 1,000 changed lines; review in multiple passes labels Sep 30, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 5c5887a against origin/tier2/409-staged-uploads at e528ba8, using #410 and #384. One pass, no subagents. Only merge-blocking findings below.

Standards

No merge-blocking method or YAGNI findings.

Spec

  1. Blocker: company members cannot read the directory on a public tier 1 patch.

    feat(primitives): the member directory primitive, t.member() and patchy add members #410 requires the directory to be refused to viewers outside the company, explicitly "on a public tier 1 patch, anyone not a member." The directory decision, point 3 confirms that company members retain access.

    The new handlers are registered behind the existing unconditional public-scope refusal. Every members.* call on a public patch returns not_available_on_public before the runtime resolves the viewer. The new product documentation codifies that narrower behavior as "including for signed-in readers," contrary to the issue.

    Verified with an isolated smoke through the real Runtime.make and Members.make, supplying the same company-viewer identity adapter. With company scope, members.list returned the two dev candidates and resolved identity once. Changing only the scope to public returned HTTP-status 403, code not_available_on_public, with zero identity resolutions.

    Admit directory reads for authenticated members of the patch's company on public tier 1 documents, without opening other primitive operations or admitting outsiders. Carry that authority through the broker and subscriptions, align the docs, and cover both the allowed company member and refused outsider.

Standards: 0 blockers. Spec: 1 blocker, the public-patch directory access contract.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/409-staged-uploads...5c5887a against #410, spec #384 §3, §7, §8 and §11, and the member directory decision (#382). Three findings, most severe first.

1. Member column defaults skip the candidate check on backfill. The issue didn't ask for them, and they add a query to every insert. (correctness + YAGNI)

  • packages/api/src/schemas.ts:330 gives member a default through column("member", PostgresText…). t.member().default(id) inherits it, and patchy-members/SKILL.md:13 tells agents to use it.
  • Failure. Add owner: t.member().default("usr_x") to an existing table. The additive planner accepts it; its refusal for a required column without a default says "add an optional or defaulted column instead" (packages/primitives/src/Tables.ts:383-387). Provisioning then runs ALTER TABLE … ADD COLUMN "owner" text NOT NULL DEFAULT 'usr_x' (Tables.ts:582). Postgres backfills every existing row with usr_x and never calls isCandidate, so usr_x can be deactivated, unknown or from another company.
  • This breaks the §11 rule "on insert or change the write path refuses a non-candidate". It is also the path the not-additive message pushes agents toward when they add a required owner column.
  • Cost. Defaults are the only reason tables.insert and tables.insertMany query patchy.columns (TableOperations.ts:133, :517, :539). That query now runs on every insert into every table of every patch, including patches with no member column. Without defaults, an omitted member column is null (optional) or refused (required), and a retained version's omitted column needs no check.
  • Fix. Refuse .default() on member columns in the config types and in ColumnDefinition. Then drop the memberColumns query and take member columns from table.columns, which is what update already does.

2. insertMany checks candidates one row at a time inside the open company transaction. (method)

  • TableOperations.ts:541-544 calls validateMembers for each row, and each call makes one directory.isCandidate platform-database query per member column (:403). All of this runs inside withWriteTable's company-database transaction (:407-411).
  • A 1,000-row batch with one member column makes 1,000 sequential cross-database round trips while the transaction is open. In a tier 2 mutation that eats into the 5 s deadline and holds its SERIALIZABLE transaction open for the whole time.
  • Fix. Collect the distinct assigned ids and check them in one query (isCandidates(companyId, ids) on the port, = ANY in Companies).

3. The skill implies company members can read the directory on a public tier 1 patch. (intent, agent-facing docs)

  • packages/sdk/skills/patchy-members/SKILL.md:42 says: "The directory is refused outside the company, including outsiders opening a public tier 1 patch."
  • The runtime refuses every operation except me on a public version for everyone (packages/runtime/src/Runtime.ts:584-585). docs/product.md ("Public documents grant no directory access, including for signed-in readers") and the CLI README (:267) both say so.
  • An agent reading only the skill will build a public tier 1 page that shows people, and it will fail for insiders too.
  • Fix. Say public documents get no directory access, as product.md does.

Checked, no finding

  • What the directory exposes. Candidates are active same-company users only. Resolution is { id, name, email, admin, active } for any company user, and null for unknown or other-company ids. getMany keeps input order and duplicates and is capped at 1,000. Cursors are bound to company and search. Prefix search escapes %, _ and \.
  • Who can read it. Members.authorize requires the fixed declaration and a same-company identity. Tier 2 pages and lower-tier documents of a tier 2 patch get server_required, both on direct calls and on subscriptions. Gateway callbacks re-check the viewer live through viewerAuthority.
  • Where the code lives. The adapter is in apps/server, and Companies imports neither Runtime nor Primitives.
  • Liveness. The revision trigger ignores unchanged fields and notifies only after the outer transaction commits. Only queries acquire the dependency, and a revision change mid-run refuses the read as recoverable.
  • Write check. An unchanged value passes and a copied id is refused, on both tiers.
  • Other surfaces.
    • Dev lists the same two mounts on both listeners.
    • remove members is refused with a member column, and the members skill is added and removed with the declaration.
    • Migration 0015 is spread with the other migrations and recorded in the ledger and ADR-0003.
    • ADR-0004, README, docs/API.md, both glossaries, CONTEXT-MAP.md and product.md are updated.
    • The skills-lock.json hash matches sha256sum skills/patchy/SKILL.md.

Reviewed by Claude Opus 5.5 via Claude Code.

@github-actions github-actions Bot added the area:integrations Company connections and integration implementations label Sep 30, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed the Astra and Opus reviews.

Fixed

  • Astra: public tier 1 directory reach. Active members of the patch's company can use all four members.* reads and subscriptions. The trusted broker lazily binds a private principal; public HTML carries no viewer identity and public me stays null. Outsiders remain refused. Tables, files, integrations and tier 2 direct access remain gated. Initial stale-cookie refresh, reconnect, account changes and deactivation are covered.
  • Opus 1: member defaults. t.member().default() is refused by config types, config execution and the manifest schema. The additive guidance now says to add an optional member column and backfill explicitly. Removed the default-related patchy.columns reads from inserts.
  • Opus 2: batch candidate checks. Collect distinct changed, non-null member ids and check them with one company-scoped = ANY($2::text[]) query. Invalid batches remain atomic; unchanged assignments to inactive members remain valid.
  • Follow-up Standards review: bootstrap identity is required rather than falling back to ordinary invocation admission. Production runtime calls and streams share the injected StreamAdmission service.
  • Follow-up Spec review: a failed lazy bootstrap can retry on the next member request. A bound public document stops when its viewer is deactivated or moved to another company, even without a subscription.

Kept as-is

Verification

  • pnpm lint and pnpm typecheck; server build passed.
  • Full offline suite: 1,567 tests passed across 137 files (pnpm test).
  • 165 focused API/config/Companies/Primitives/runtime/serving tests passed.
  • All 7 Chromium public-member lifecycle tests passed: private bootstrap, outsider refusal, token refresh, reconnect, account switch, served-tier cutover, failed-bootstrap recovery and call-only authority loss. The three new failure-path regressions failed before the final broker fix and passed afterward.
  • Disposable real-server browser smoke: public me was null, member reads and a live subscription succeeded, deactivating a colleague removed them from the candidate snapshot, and anonymous access was refused. No production or live Clerk data was used.
  • Final real-browser smoke also proved recovery after a dropped bootstrap and the access-loss notice with the patch frame removed after viewer deactivation.

Latest head d85010e6aee4c9a0ed58e3fe1db2b9ba7e7d6b9f: all 9 reported checks pass—Node 22/24 tests, lint/typecheck/format, Postgres concurrency, live Clerk, packed CLI/Preact smoke, dependency review, server image and labels. CI run. GitHub reports no separately required checks for this PR; merge state is CLEAN / MERGEABLE.

Final feedback sweep found no additional conversation feedback, review bodies or inline comments; no Grok review was present. The PR remains open and unmerged against tier2/409-staged-uploads.

Commits: 340ab97 and d85010e.

Implemented with GPT-6 Astra via omp.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus re-review

Reviewed 5c5887a..d85010e (340ab97 and d85010e). No blocking findings.

Resolved

  • Finding 1, member defaults. Defaults are refused in three places:

    • the manifest schema (default: Schema.optionalKey(Schema.Never), packages/api/src/schemas.ts:330-334);
    • the config types and Column.default / toJSON;
    • executeConfig.

    The not-additive fix text for a required member column now says to add it optional and backfill explicitly. Nothing can add a member column that Postgres backfills without the check. The per-insert patchy.columns query is gone, and member columns now come from table.columns.

  • Finding 2, batched checks. validateMembers collects the distinct changed, non-null ids across the whole batch and checks them in one = ANY($2::text[]) query through candidates. It returns early when a table has no member column. Invalid batches still fail before the insert transaction starts. Non-string values are still refused by validateRow.

  • Finding 3. Superseded by the Foreman ruling. The runtime, product.md, the README and both skills now say the same thing: company members can read the directory on a public tier 1 patch; anonymous viewers and outsiders cannot. The skills-lock.json hash matches the new skills/patchy/SKILL.md.

The new public-directory path

  1. Refusals, with no leaks.
    • The principal bootstrap is refused unless the version is public, tier 1 and declares members (Runtime.ts:599-606). Once a tier 2 version is served, it answers server_required.
    • A member op on a public page resolves identity per call. The resolution rules:
      • a signed-out visitor gets session_expired or session_refresh_required;
      • a deactivated user is refused by resolveViewer;
      • a member of another company fails identity.company.id !== version.companyId (:619), and so does the bootstrap.
    • Public HTML adds only a static <template> holding the Clerk publishable key and script tags. No viewer id is rendered, no cookies are set, and the page stays publicly cacheable.
    • Public me stays null even after binding, because the scope === "public" && op === "me" branch skips identity.
    • Runtime replies remain no-store.
    • The bound principal is kept in the broker only. The frame cannot request principal, because it is not in runtimeOperations and so fails the broker's op allowlist.
  2. No reach beyond the four reads. On a public version, every op except me, principal and the four members.* reads fails not_available_on_public before identity is resolved (Runtime.ts:607-613). That covers server.call, tables, files, files.redeem, shared.* and postgres.*. On the stream, checkOperation refuses any non-member op for a public binding. The existing test that closes a table subscription when a patch becomes public still holds.
  3. Deactivation or a company move ends the binding.
    • Each call re-resolves the viewer. Deactivation or a company move turns into access_denied, and the broker now stops the frame with a notice when the principal is bound. An account switch is principal_changed.
    • The stream's recheck also closes on a company or viewer mismatch.

CI is green on d85010e.

Reviewed by Claude Opus 5.5 via Claude Code.

@allisonmahmood
allisonmahmood force-pushed the tier2/409-staged-uploads branch from e528ba8 to fc5197d Compare October 1, 2026 05:46
Base automatically changed from tier2/409-staged-uploads to main October 1, 2026 06:12
@allisonmahmood
allisonmahmood force-pushed the tier2/410-member-directory branch from d85010e to 5a3f3e8 Compare October 1, 2026 06:12
@allisonmahmood
allisonmahmood merged commit 335d476 into main Oct 1, 2026
15 of 16 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/410-member-directory branch October 1, 2026 06:30
allisonmahmood added a commit that referenced this pull request Oct 3, 2026
…y before launch (#503)

Before launch (#416) no database we need to keep exists, yet the
platform record carried 15 migrations, and several tests and code paths
existed only to upgrade databases built by older steps (decision O1 from
the test audit). This squashes each capability into one baseline that
builds exactly today's schema, and deletes the upgrade-only code and
tests with it.

- **One baseline per capability**, ids 1–8 in foreign-key order:
companies, auth, patches, company_database, runtime, integrations,
limits, execution. The names drop `_baseline`, so an old ledger can
never match the new history by name.
- **Faithfulness proof** (run outside the repo, `/tmp/lane-e-proof`):
databases built from main's record and from this record have identical
`pg_dump --schema-only`, identical data apart from the ledger, and an
identical catalog listing (columns, defaults, constraints, indexes,
functions, triggers, grants). That holds for the platform database, a
Postgres company inventory and a PGlite company directory.
- **The ledger guard** (`packages/sql`): `migrate` now refuses a ledger
whose history differs from the record's, up to the lower of the two
highest ids. The Migrator only applies ids above the ledger's highest,
so a pre-squash database would otherwise silently skip the baselines and
every future migration with an id up to 15. Ids above the record's
highest still pass, so an older build can start after a newer one
migrated (the rollback in OPERATIONS.md). The dev runner now writes the
refusal to `dev.log`.
- **Removed upgrade paths:** `Inventory.upgrade` and its calls in both
`ensureReady`s, the mutation-key lookup's missing-table retry (added in
#432 for databases created before mutation keys), and the upgrade-only
tests: `runtime` and `patches` `migrations.test.ts`, the directory
migration block, two inventory-upgrade tests, and an orphan-sweep case
for retained inventories. Docs: DEVELOPMENT.md, `packages/sql` README
and CONTEXT (new **Baseline** term), ADR-0003/0009/0012, product.md,
API.md.

**After this merges:**
- Every existing local dev instance, in every worktree, needs `pnpm dev
reset`, which wipes its local data. An instance that isn't reset refuses
to start and says why in `dev.log`.
- The disposable tier 2 spike database needs recreating before its next
deploy.
- `patchy dev` data in patch repos made by a CLI older than #449 needs
`patchy dev reset`.

Upgrade tests start again with the first migration that has to keep
retained state.

Made by Claude Opus 5.5 via Claude Code

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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:docs Touches the docs area area:integrations Company connections and integration implementations area:primitives Patch tables and files area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(primitives): the member directory primitive, t.member() and patchy add members

1 participant