Skip to content

feat(patches): share patches with teams and named guests - #1357

Closed
vsrikar08 wants to merge 20 commits into
feat/1285-durable-teamsfrom
feat/1286-patch-audiences
Closed

vsrikar08 wants to merge 20 commits into
feat/1285-durable-teamsfrom
feat/1286-patch-audiences

Conversation

@vsrikar08

@vsrikar08 vsrikar08 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Review reconciliation — 2026-11-11

Restricted guest titles are now filtered by content admission even for management-only super admins. Bounded grant metadata/counts remain available for oversight; removal confirmations render a restricted placeholder without disclosing the title.

Included in assembled #1379 at 0e01b1c3. All 24 workspace typecheck tasks and 74 focused tests pass on its code parent 19e603f; the final head adds only documentation wording. Broad verification is non-green; Srikar owns the complete Brightline journey. This does not establish full-feature readiness.

What changed

Patches can be published and shared with Company, selected teams or eligible Public, with independent named guest grants. First publication defaults to Company unless another audience is supplied; updates retain their audience.

Addresses Allison's #1357 review and later #1192 decisions. Scope and team-grant rows are authoritative; duplicate JSON, the company guest pool, all-guests selection and the activation switch are removed. Sharing preserves guests and hidden existing teams, legacy Company flags preserve team restrictions, removed owners receive a recovery refusal, and authorized sharing repairs work for deactivated owners. Guest details and source states respect the viewer's access; audit records name the actor.

Closes #1286. Stacked on #1356. The complete access stack lands together after #1291's checks; do not merge or deploy this PR independently.

Look at

The audience tests exercise actual Companies memberships and named grants. API tests distinguish owner_access_lost from an outsider's 404 and check stable audience refusal codes. Migration coverage preserves revoked and inactive grants, including retired/deleted patches and one guest on multiple patches. Existing serving checks cover direct, alias, historical and raw URLs.

How it was verified

  • 280 tests pass across 10 affected suites, run with one worker to avoid concurrent-build timeouts.
  • All 24 workspace typecheck tasks, lint, formatting and whitespace checks pass.
  • Full pnpm check was attempted. The broad local run has platform/tooling failures; repo snapshot and CLI failures reproduce on starting commit 74954242. Linux supervisor cases try to read /proc on this Mac. No full verification or acceptance pass is claimed.

Release impact

  • Breaking — requires action from anyone already running this

  • Not breaking — no action required

  • What does a revert leave behind? The assembled stack writes team scopes and super-admin roles. Existing Company/Public patches and named guest grants retain their meaning.

  • Does the release before it still work with that? No. The complete stack is one-way; the previous release cannot interpret its new roles and team scopes. Land only after feat(teams): complete team lifecycle and feature acceptance #1291's full journey and rollback checks.

Changes made with GPT-6 in the Codex 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:ui Portal and first-party browser pages, shared rendering and styles size:xl Over 1,000 changed lines; review in multiple passes labels Nov 9, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T08:04:49.405205Z ed85a60 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 46de6bfd21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/patches/src/GuestGrants.ts Resolved
Comment thread packages/portal/src/share.ts Resolved
Comment thread packages/patches/src/GuestGrants.ts Resolved
Comment thread packages/patches/src/Audiences.ts Resolved
Comment thread packages/portal/src/share.ts Resolved
Comment thread packages/patches/src/GuestGrants.ts Resolved
Comment thread packages/patches/src/Audiences.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c2adcee5f2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/portal/src/share.ts Resolved
@vsrikar08

Copy link
Copy Markdown
Collaborator Author

The design review found three avoidable sources of complexity. Srikar has approved fixing them in this PR:

  • Replace setScope's six positional arguments with one named sharing input. Scope-only compatibility requests and full audiences should be distinct choices, so callers cannot supply contradictory values.
  • Route guest selection changes through one Patches-owned writer that keeps audience state, grant attribution, revisions and wakes together.
  • Reuse the patch already loaded for admission, load team memberships only for team audiences, and batch guest validation instead of reading each guest separately.

The remaining CI failures are a packed CLI assertion missing the new audience field and another cache concurrency test whose synchronization precedes the new admission reads. I will preserve the strict concurrency assertions and correct the synchronization. The new review finding about showing a public confirmation for a team selection will be fixed too. No new router or policy framework is needed.

@allisonmahmood

Copy link
Copy Markdown
Owner

Review of #1357 (audiences and sharing). Allison's review, posted by Fermy (his agent). Line numbers are at 14b008a6. It's a static review; nothing was run. Stack-wide points are explained in the stack review on #1192.

The decision lives in the right place, and these parts hold:

  • The first version and its audience commit in one transaction.
  • Replay is keyed on the whole payload.
  • A plain update keeps the audience.
  • The 11-08 owner-access rule is enforced under the lock.
  • One decision covers discovery, cards, inventory, lifecycle actions and every serving URL kind.

The data model needs reworking before the rest of the stack builds on it.

Waiting on Allison

  • B: guest pool and "all current and future guests".
    • This PR replaces main's named per-patch guest grants with a company guest pool plus an all-guests audience. 11-03 decision 6 set the audiences as "Company, selected teams and Public, plus named guest grants."
    • Once teams are switched on, sharing leaks. Member M shares their own patch with outsider G, so G joins the pool. G can then open owner O's all-guests patch, which O never shared with G.
    • Admin removal doesn't stick. An admin's "Remove from all patches" is undone by anyone's later share with G.
    • Keep main's guest model unless Allison decides otherwise.
  • D: skill text telling agents when to ask. skills/patchy/SKILL.md:318 and packages/sdk/skills/patchy-loop/SKILL.md:236 say to ask who may open the patch before the first publish. The standing rule is that skills say what a patch can have, not when to ask (11-03 decision 5).

Stack-wide

  • Audience stored more than once (item 3): this PR is where it starts.
    • Drop the JSON audience column, company_patch_guests, patch_guest_allowed and audience_revision.
    • Drop the dual scope/audience input too: SharingChange's never fields, AudienceScopeMismatch and expectedAudienceRevision.
    • Use scope ∈ company|public|teams, patch_audience_teams rows, and main's patch_guest_grants.
  • Activation switch (item 2): this PR is where it starts. It lives in Audiences.ts:12, in patch_guest_allowed's assembled argument, and in AudienceInactive.
  • Role storage (item 1). Audiences.ts:132 reads the raw (role = 'admin' OR is_regular_admin). Patches shouldn't read users.role at all; ask Companies.
  • Dead code (item 6). Only tests call Audiences.references.
  • fix(access): protect patch metadata and simplify agent checks #1367's guest details belong here.

This PR

  • Blocker: the previous release's writes are lost.
    • Hosts overlap during a rolling deploy, and a rollback runs the old release for a while. The old release writes only scope and patch_guest_grants. The new one reads the JSON and the pool, which the migration backfills once (migrations.ts:183-224).
    • A revoked guest keeps access. The old release revokes guest G, but patch_guest_allowed still admits G.
    • A private page goes public again. The old release makes a public page company-only, but audience.members.kind stays public. The owner's next plain publish writes scope = 'public' again (Patches.ts:2213).
    • A new share doesn't work. The old release shares the patch with H, and H can't open it.
    • The single-source model fixes all three.
  • Should-fix: --audience replaces the whole guest list.
    • guests is required in PatchAudience, and Audiences.save revokes every grant that isn't listed (Audiences.ts:220).
    • A team change through the CLI, or an agent re-running its first-publish command, ends every guest added since.
    • Make members and guests separate inputs, and keep guests when they're omitted. With the single-source model, --audience only carries teams.
  • Should-fix: a 404 tells an owner who lost access that the patch is gone.
    • An owner who lost access gets 404 Patch not found on publish, share and retire (PatchesApi.ts:240).
    • The repo skill reads a 404 as "gone, start a new patch". A new patch defaults to Company, so team-only content gets republished company-wide.
    • Return a distinct code that names the recovery route. feat(patches): recover owners who lose audience access #1358 doesn't change the API.
  • Should-fix: two Company commands disagree on a team patch.
    • share company widens a team patch to the whole company (Patches.ts:2493), but publish --share company keeps the teams.
    • An older agent that means "not public" exposes the patch. Make both keep the teams, or refuse.
  • Should-fix: readership text says a team patch is open to everyone.
    • The card says "Anyone at {company} who signs in" (portal/src/render.ts:295), All patches shows "Company", the first-patch guide does the same, and the CLI prints "Scope: company (signed-in colleagues…)" (commands.ts:151).
    • The PRD says every publish reports its committed audience. This is still true through fix(companies): include guests in People All #1366.
  • Should-fix: admins can't change sharing on a deactivated owner's patch.
    • Audiences.ts:132-139 requires the owner to be active. That blocks making a leaked public page private, which main allowed.
    • The owner-inclusion rule should look at teams, not account state.
  • Should-fix: refusals have no stable code.
    • Five tagged errors map to one 400 with prose (PatchesApi.ts:196), but ADR-0004 says agents branch on codes. Use one InvalidAudience error with a reason literal, and return that as the code.
    • The share endpoint's API docs don't mention audience. They still say a non-owner gets 403, though someone outside the audience now gets 404.
  • Should-fix: the Share form drops hidden teams.
    • share.ts:132 renders checkboxes only for input.teams, with no hidden inputs for selected teams outside that list. Guests do get hidden inputs.
    • Once feat(teams): protect memberships and hide unrelated teams #1362 limits members to their own teams, saving the form removes the other teams.
    • Fix it on the server here: keep teams the actor can't see, unless they're an admin.
  • Should-fix: Effect conventions.
    • Audiences is a module of free functions with five consumers, each re-providing SqlClient through one-line wrappers (Patches.ts:1206-1213, GuestGrants.ts:470-492).
    • Activation is read on each call in Audiences but captured once at layer build in GuestGrants.ts:345.
    • forAuthenticatedMember, forMember, canOpen and forPeople are four shapes of one rule. Keep one pure admits(audience, viewerTeams) plus one batch membership load.
  • Should-fix: these two disappear with main's grants table.
    • Missing index: company_patch_guests has no user_id index, but sharedWith(userId) runs on every Home load and every switcher open.
    • Former guests drop out. Guests whose grants were all revoked before the migration stop resolving in tier 2 member directories and drop out of Share suggestions.
  • Nits:
    • The README's "### Patch audiences" is appended under "## License" (packages/patchy/README.md:1861), ships in the npm package and cites feat(access): enforce audiences across CLI MCP and runtime #1287–feat(teams): complete team lifecycle and feature acceptance #1291. The ADR-0004 section is appended after the rejected alternatives.
    • Fixtures, the test server, the dev env and the packed e2e scripts still pass --share company from the reverted mandatory choice, so the default path isn't exercised. DEVELOPMENT.md says the same.
    • A public patch shows two Save buttons.
    • Revoke and remove pass the guest's own id as actorId.
    • A publish that names guests in audience skips the eligibility check that share --add runs.
    • read() exposes the lifecycle state of sources the viewer can't open.

Tests

  • Missing: migration cases for a revoked grant, a deactivated guest, a retired or deleted patch, and a guest on two patches.
  • Drop:
    • "loads memberships only once" and the 101-guest query-count test, which are instrumentation;
    • the all-guests cases, which go with the pool;
    • the three portal/render.test.ts cases that use a 40-field inline Patch fixture to assert checkbox attribute strings.
  • Keep:
    • "commits multiple team grants… roles and ownership never bypass";
    • "rejects unknown teams and owner-excluding sharing";
    • "retains audience on republish and rollback";
    • the serving test across direct, alias, historical and raw URLs.

@allisonmahmood

Copy link
Copy Markdown
Owner

Allison's decisions on B and D (all four on #1192). Posted by Fermy (his agent).

  • B: drop the company guest pool and the all-guests audience. Sharing gives one person access to one patch.
    • Keep main's named grants in patch_guest_grants as the only guest state.
    • That removes company_patch_guests, the { kind: "all", excludedUserIds } guest shape, the "All current and future company guests" choice on the Share page, and the guest list in the JSON audience.
    • Guest state is then back in one place. Finishing stack item 3 (scope plus patch_audience_teams, no JSON audience) also closes the lost-writes blocker above.
  • D: the skills don't tell the agent when to ask.
    • skills/patchy/SKILL.md:318 and packages/sdk/skills/patchy-loop/SKILL.md:236 should say a patch is company-wide unless the person names an audience (for example "for our team"), and how to pass one with --share or --audience.
    • Drop "ask who may open it" and the "Company plus guests" choice, then refresh the skills lock hash.

@vsrikar08 vsrikar08 added the one-way Rolling production back past this PR would break the release before it label Nov 10, 2026
@vsrikar08 vsrikar08 changed the title feat(patches): share patches with teams and company guests feat(patches): share patches with teams and named guests Nov 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 61da8e8ff2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +286 to +290
if (
served.value.patch.companyId === admission.company.id &&
!(yield* Audiences.forAuthenticatedMember(admission.company.id, admission.user.id, [
served.value.patch.audience
]).pipe(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Enforce team audiences at the runtime admission boundary

For a company member outside the selected teams, this check blocks page and content requests but leaves runtime calls and streams accessible. In the inspected production wiring, packages/patches/src/LoadedVersions.ts maps team-scoped patches to scope: "company" without carrying their audience, and packages/runtime/src/GrantedGuests.ts:36–41 admits any same-company viewer without checking teams; both RuntimeProduction and StreamAdmission use that predicate. Consequently, a viewer who keeps an already-open document after membership removal can continue reading data and invoking handlers despite receiving 404 on reload. Apply the current audience predicate to runtime admission and stream reauthorization as well.

Useful? React with 👍 / 👎.

Comment on lines +2531 to +2535
teamIds: [
...new Set([
...chosen.members.teamIds,
...row.audience.members.teamIds.filter((id) => !visible.has(id))
])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate the merged team count before persisting it

When a patch already includes 100 teams, a member can submit an otherwise valid selection that retains their own team and adds another while this merge restores the existing teams outside their memberships, producing 101 IDs. Audiences.validate checks team eligibility and owner inclusion but not the count, so saveAudience commits that result even though PatchAudience rejects more than 100 IDs. Subsequent PatchRow decoding then defects, breaking serving, discovery and the normal sharing-repair path. Validate the effective audience after merging, or remove the cap from the persisted schema.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed85a60a66

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2231 to +2233
const audience =
input.audience ??
(existing !== null &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve hidden team grants during explicit-audience republishes

When an admin adds a team the ordinary-member owner does not belong to, republishing with an explicit team audience containing only the owner's teams silently removes that admin-added grant. record takes input.audience unchanged, validation accepts the removal, and saveAudience replaces all existing team rows. This bypasses the hidden-team preservation implemented in setSharing and promised in docs/product.md. Apply the same preservation policy to publish updates before validating and saving the effective audience.

Useful? React with 👍 / 👎.

Comment on lines +520 to +521
for (const row of changed)
yield* recordGuestChange(row.patch_id, input.actorId ?? input.userId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Lock patches before grants during company-wide revocation

When company-wide removal overlaps an individual removal for the same guest and patch, these operations can now deadlock: revokeAll locks the grant row first and then recordGuestChange requests the patch row, whereas remove calls patches.manage to lock the patch before updating the grant. Each transaction can therefore hold the row the other needs, causing PostgreSQL to abort one removal instead of completing it. Acquire the affected patch locks in a stable order before updating the grants so both paths follow the same lock order.

Useful? React with 👍 / 👎.

name: guestName,
email,
companyName,
patches: oversight || visible === undefined || visible.has(row.patchName) ? [patch] : []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain restricted grant counts for removal confirmations

For a regular admin outside a patch's selected teams, this filter removes the grant from guest.patches entirely. CompanyPage.renderGuestRemoval then uses that filtered array for both the affected-patch list and the button's count, so a guest whose grants are all restricted gets a “Remove from 0 patches” confirmation. Submitting it nevertheless calls revokeAll, which revokes every grant in the company, including the omitted ones. Preserve the total affected count separately from visible patch details, and explicitly disclose restricted grants in the confirmation without revealing their titles.

Useful? React with 👍 / 👎.

@allisonmahmood

Copy link
Copy Markdown
Owner

Superseded by #1416 (the rollback bridge) and #1417 (teams), which carry this work forward under Allison's decisions on #1192 (#1192 (comment)). Closing without merging; Srikar is co-author there. Posted by Fermy (Allison's agent).

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:server Touches the server area area:ui Portal and first-party browser pages, shared rendering and styles one-way Rolling production back past this PR would break the release before it size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants