Commit Graph
6720 Commits
Author SHA1 Message Date
Waleed 23e1663e71 fix(deps): preserve runtime and canvas behavior (#7366)
* fix(deps): preserve runtime and canvas behavior

* fix(demo): validate Cal embed configuration

* fix(deps): preserve runtime compatibility
2026-09-01 13:43:09 -07:00
Waleed 9acf0f8e33 perf(tests): drop dead upload-context re-exports and unify the CI dummy key (#7369) 2026-09-01 13:16:26 -07:00
Waleed d8ecc5b860 perf(tests): cut per-file import graphs in apps/sim and shard the suite across CI runners (#7367)
* perf(tests): cut per-file import graphs in apps/sim and shard the suite across CI runners

* fix(tests): recheck abort after lazy handler load; list script tests by file
2026-09-01 13:00:36 -07:00
Waleed df833efa06 feat(ashby): expand hiring operations and webhooks (#7341)
* feat(ashby): expand hiring operations and webhooks

* test(ashby): type webhook fixtures

* fix(ashby): harden uploads and pagination

* fix(ashby): correct API contracts and webhook handling
2026-09-01 12:36:00 -07:00
Bill LeoutsakosandBill Leoutsakos f59c69f6b2 fix(confluence): normalize space identifiers (#7324)
* fix(confluence): normalize space identifiers

* fix(confluence): hydrate legacy numeric space selections

---------

Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-09-01 12:24:55 -07:00
Bill LeoutsakosandBill Leoutsakos e7cfef9a2e fix(selectors): paginate HubSpot owner options (#7359)
* fix(selectors): paginate HubSpot owner options

* fix(selectors): preserve hydrated HubSpot owner IDs

---------

Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-09-01 12:18:30 -07:00
Vikhyath MondretiandSim Pi Agent 83e5f5f3de feat(library): Sim: The Open Source Zapier Alternative for AI Agents (#7365)
* feat(library): Sim: The Open Source Zapier Alternative for AI Agents

* Pi Babysit: address PR #7365 feedback

---------

Co-authored-by: Sim Pi Agent <pi@sim.ai>
2026-09-01 12:09:23 -07:00
Waleed 2ce2bec929 chore(api): remove unused and superseded API routes (#7364) 2026-09-01 12:05:11 -07:00
Waleed 4c20ff63ec improvement(audits): eliminate repeated parsing and scans (#7361)
* improvement(audits): eliminate repeated parsing and scans

* fix(audits): resolve local bins under vitest

* fix(audits): include drizzle subpath imports
2026-09-01 11:56:18 -07:00
Bill LeoutsakosandBill Leoutsakos 69d72669a0 fix(selectors): close residual cancellation gaps (#7358)
* fix(selectors): close residual cancellation gaps

* fix(selectors): recheck post-resolution cancellation

---------

Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-09-01 11:56:04 -07:00
Bill LeoutsakosandBill Leoutsakos 9d8d5950c1 fix(cloudwatch): paginate log selectors (#7360)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-09-01 11:45:09 -07:00
Bill LeoutsakosandBill Leoutsakos 11b10fb485 fix(selectors): drain Snowflake result partitions (#7357)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-09-01 11:38:39 -07:00
Waleed 349f40a31b feat(sidebar): live workflow and folder registry updates via workspace-workflows room (#7356)
* feat(sidebar): live workflow and folder registry updates via workspace-workflows room

* fix(sidebar): cover v1 workflow import fan-out and scope folder invalidation per review
2026-09-01 11:18:52 -07:00
Vikhyath MondretiandClaude Opus 5 9c35e18138 fix(tool-input): render every tool param through the canonical sub-block renderer (#7336)
* fix(tool-input): render every tool param through the canonical sub-block renderer

An agent block's tool row had grown a second, lossy copy of the sub-block
renderer and a second value encoding that nothing decoded.

A tool param with no matching sub-block fell into a hand-rolled renderer that
ignored `param.type` and produced a text box — which is why Jira's boolean
`includeAttachments` rendered as free text, where typing `false` enabled it.
~2.7k of ~26k user-facing params took that path.

Separately, `StoredTool.params` stringifies every value while the canonical
`Switch` stores a real boolean, so a switch set to off reached the tool as the
truthy string `'false'` — 409 switches across 99 blocks. The editor lied too:
`Boolean('false')` rendered it back on after every remount.

One producer, one renderer, one type map, one encoding:

- `tools/param-shape.ts` holds the single value-type -> control map and the
  encode/decode pair, as a leaf module with no registry edge. It absorbs
  `subBlockTypeForField`, which answered the same question in a second
  vocabulary.
- `getSubBlocksForToolInput` returns real + synthesized `SubBlockConfig`s, so
  every user-facing param renders through `SubBlock`. Claims are computed from
  the block's full sub-block list, so a param whose sub-block condition fails
  stays hidden instead of reappearing as a text box.
- The decode keys off the SUB-BLOCK, not the tool's declared type. Jira's
  `deleteSubtasks` is a dropdown of 'true'/'false' backing a boolean param, and
  the block compares `=== 'true'`; keying off the tool type would have inverted
  that flag and ~167 like it.
- `buildBlockToolParamsTransform` is shared by the agent block, Pi local tools
  and Human v2, which each previously applied a different subset.

Deleted: `renderParameterInput`, `ParameterWithLabel`, `ToolCredentialSelector`,
`getToolParametersConfig`, `ToolParameterConfig`, `UIComponentConfig`,
`resolveSubBlockForParam`, and the search indexer's parallel branch.
`workflow-input-mapper` became a real sub-block type instead of a hard-coded
`workflow_executor` branch.

checkbox-list was broken on every surface: it wrote each option id as its own
top-level store key, so the serializer dropped them all. Verified against the
real serializer — jina's and pinecone's options never reached their tools, and
asana's reached a `params` fn that tested `Array.isArray` on a boolean. It now
stores one record under its own id and projects onto its option params at both
boundaries; an untouched option is omitted rather than sent as `false`, which
`update_task` depends on.

Human block v2: running notification tools through the full transform changes
what an already-configured tool receives, so it ships as `human_in_the_loop_v2`
with v1 hidden and sunset. The ten sites keyed on the block type now share one
`isHumanInTheLoopBlock` predicate.

A persisted `'false'` now means `false`. Affected workflows have been doing the
opposite of what their editor showed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tool-input): address review — decode MCP structured args and custom-block fields by declared type

Six review findings, all real:

- `getJsonSchemaValueShape` round-tripped through the control it picks, and an
  `object` renders in a code editor whose store value is raw JSON text — so the
  shape came back `string` and MCP object/array args reached the server
  undecoded. It now reads the schema directly.
- `mcp-dynamic-args` picked its control from the normalized union type but still
  read raw `paramSchema.type` for `requiresJsonValue`, the slider step/rounding,
  the numeric check and the array placeholder. A nullable object took the
  non-JSON path; a nullable integer got a fractional step. `jsonSchemaType` is
  exported and every read goes through it.
- A custom block's inputs were not decoded on the executor: the server overlay
  builds its configs with `inputFields: []`, so `blockDef.subBlocks` carries no
  field sub-blocks. The assembler now takes `binding.inputFields`, and the
  resolved-secret projection reads the same list off the provider tool config so
  both copies decode identically. Keyed on the DECLARED field type, since
  `number` and `object` render as controls that store strings.
- Pi local tools failed open when the projection transform threw after the real
  one succeeded, pairing transformed execution params with untransformed
  projected ones. Now marks the registry incomplete and refuses, matching
  `prepareToolExecution`.
- 15 sub-blocks declare no `title`, so removing the formatted-id fallback left
  them unlabelled in a tool row. Restored in the producer.
- `deserializeBlock` now rebuilds a checkbox-list record from its option params,
  the inverse of the serializer projection, so the round trip stays lossless.

Two of my own tests had encoded the first bug and were corrected rather than
kept green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tool-input): address review round 2 — enum shape and legacy MCP arg values

- `getJsonSchemaValueShape` checked the enum branch before the declared type, so
  `{ type: 'integer', enum: [1,2,3] }` was shaped as text. The dropdown it renders
  as stores `String(option)`, so the server received '1' instead of 1. The
  declared type now wins, and an untyped enum is inferred from its members.
- An MCP argument entered before its control was derived from the NORMALIZED
  schema type is stored as a string, so a union-typed boolean's 'false' would
  tick the switch it now renders as. `mcp-dynamic-args` decodes on read; already
  typed values pass through, so it is a no-op thereafter.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tool-input): regenerate icon mapping and guard an empty MCP enum

- `docs:check` failed: adding `human_in_the_loop_v2` (and hiding v1) left the
  generated icon maps stale. Regenerated; the diff is only those entries.
- `enumMemberShape` read an empty enum as numeric, because `every` is vacuously
  true on `[]`. A third-party MCP schema can send one.
- The MCP dropdown's highlight label used a truthiness check, so a falsy member
  (`0`, `false`) rendered blank now that the value is decoded rather than kept
  as a string.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tool-input): address review round 3 — checkbox write race and MCP enum member types

- `CheckboxList` merged onto the value captured at render, so two toggles landing
  before React rerendered both built from the same record and the second write
  dropped the first. Every option in the group now shares one key, so it reads the
  store at write time; the store updates synchronously, so it always sees the
  preceding toggle. The old per-option keys could not hit this.
- The MCP dropdown wrote back the string the combobox works in, so a numeric enum
  sent '1' for 1, 'true' for true and 'null' for null. It now persists the enum
  MEMBER, matched by its stringified form, so nothing downstream has to guess.
- Selection is decided by key presence rather than truthiness, so `0`, `false` and
  a literal `null` member render as selected instead of blank.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(mcp): recover enum members from legacy stringified arguments

The dropdown now persists the enum member, but arguments saved before that
still hold `String(member)` text. Only the member list inverts that encoding —
a value shape cannot tell `'null'` the text from `null` the member, and the
declared-type coercions never see an untyped property.

- `jsonSchemaEnumMember`/`decodeJsonSchemaValue` in `param-shape` own the
  inverse, next to the `buildSubBlocksFromJsonSchema` encoder it undoes.
- `coerceToolArguments` applies it at the MCP execution boundary, which is the
  one place both the MCP block and an agent's MCP tool row pass through, so
  the editor and the server agree on one value.
- `validateToolArguments` accepts a declared member on its own: `enum` is
  narrower than `type`, and a recovered `null` satisfies no type branch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(mcp): read tool schema properties through the shared normalizer

Reading `properties` straight off the wire meant the enum lookup — which runs
before `hasType` so it can recover an untyped or `null` member — dereferenced
whatever the server sent, and `properties: { foo: null }` threw out of
`validateToolArguments`, where nothing catches it.

`jsonSchemaProperties` already answers "what does an untrusted property look
like" for every other reader, so both loops go through it instead of guarding
per call site. That drops the local `isDeclaredEnumMember` copy and the
redundant `inputSchema?.properties` early return: one normalizer, one
`jsonSchemaEnumMembers` accessor, no property access ahead of a guard.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* revert(mcp): drop the enum-member recovery layer

Checked against the prod replica rather than reasoning about it, and every
case this guarded has zero instances:

- `workflow_mcp_tool`: 470 properties, 0 declare an `enum` at all.
- MCP blocks' cached `_toolSchema`: 6 enums, all `type: 'string'` with string
  members. No untyped enum, no `null`/number/boolean member.
- Stored MCP block arguments (179): 0 stringified booleans, 0 stringified
  nulls. Booleans and numbers are already persisted with their real types.
- Agent MCP tool-row params (10,022): 0 stringified booleans, 0 stringified
  nulls, 4 stringified numbers — already covered by the `type: number`
  coercion that predates this branch.

For a string enum `String(member) === value` returns the same string, so the
whole path was a no-op on every row in production while adding a coercion at
an authorized use case plus a validation widening to keep that coercion safe.
The dropdown already persists the member (679325a899), so nothing downstream
has to reverse the encoding.

`enumMemberShape` goes with it — every real enum declares a type, so member
inference never runs. The declared-type-first ordering stays: it is a
precedence fix, not a layer. `getJsonSchemaValueShape` is private again.

`lib/mcp/application/execute-tool.ts` is byte-identical to 679325a899.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(permission-groups): regenerate the block successor map for Human v2

`check:block-successors` arrived with the staging merge and this branch is
what makes it stale: versioning the Human block adds a successor edge the
generated map did not carry.

Not cosmetic — the map is how a permission group that allows `human_in_the_loop`
keeps covering `human_in_the_loop_v2`. Without the edge, an enterprise group
scoped to the old block would deny its replacement.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 11:14:57 -07:00
Waleed 36a4b6a0cb fix(canvas): repair React Flow v12 and dependency upgrade regressions (#7355)
* fix(canvas): repair React Flow v12 and dependency upgrade regressions

* fix(trigger): keep pdfjs-dist external to the worker bundle
2026-09-01 11:00:17 -07:00
Waleed d7b31a85b6 feat(permission-groups): enforce every config key server-side (#7347)
* test(permission-groups): pin config coercion before deriving it

Adds a golden corpus and a seeded fuzz loop over
`parsePermissionGroupConfig`, written against the current hand-written
implementation so a derived one has something to prove itself against.
Every row states what a stored `jsonb` value coerces to today; a row that
changes in a later diff is a decision someone has to defend rather than a
silent regression.

Two properties the corpus pins are easy to break by accident:

- `typeof [] === 'object'`, so an array-valued column coerces to defaults
  rather than throwing. A parser built on `z.object()` throws here unless
  it guards `Array.isArray`.
- An emptied allowlist denies everything while `null` allows everything,
  so the two must never collapse into one another.

It also pins a live defect. `allowedIntegrations` and
`allowedModelProviders` are the only keys that skip element validation, so
a corrupted row coerces to a value `permissionGroupFullConfigSchema` then
refuses — the route reading it fails response validation instead of
returning a usable allowlist. Filtering non-strings on the way in is
fail-closed and removes the class; the test inverts when that lands.

Adds the two coverage guards that were missing: the write schema, the
defaults and the read schema declare the same keys, and every boolean
config key is registered as a platform feature. Neither was asserted, so a
key omitted from the write schema would have made an admin checkbox
silently no-op on save.

Drops the `@/lib/permission-groups/types` mock in the permission-check
suite and its hand-copied `DEFAULT_PERMISSION_GROUP_CONFIG`. That module
imports only zod and a type, so there was nothing to mock, and the mock's
permissive merge was strictly looser than the real parser — those 63 tests
were asserting against a fake that could not reproduce a coercion bug. The
factory also returned two exports, leaving `FILE_SHARE_AUTH_TYPES` and
`PERMISSION_GROUP_CONSTRAINTS` undefined for that module graph.

* refactor(permission-groups): derive the config from one field registry

The config shape was maintained by hand in five parallel places — the write
schema, the `PermissionGroupConfig` interface, the defaults, the tolerant
parser, and the contract's read schema — plus the platform-feature list.
Key order was load-bearing across all of them, because the group editor's
dirty check compares stringified configs, so a key added at a different
index read as an unsaved change forever. Nothing checked that the write
schema had the same keys as the rest, and a key missing there made an
admin checkbox silently no-op on save.

`PERMISSION_GROUP_FIELDS` now declares each key once, carrying its schema,
its default, whether it is server-enforced, and (for a boolean) its editor
descriptor. Everything else is projected from it, so declaration order is
the wire order by construction rather than by agreement.

Two things this could have broken quietly, both pinned by the corpus added
in the previous commit:

- `z.object().parse([])` throws, but `typeof [] === 'object'`, so an
  array-valued jsonb column used to coerce to defaults. The guard keeps
  `Array.isArray` for exactly that row.
- `.catch(default)` is whole-value tolerant while the old parser was
  element-wise. On an allowlist that would have been fail-open: one bad
  member would yield `null`, and `null` means unrestricted. `tolerantArray`
  filters instead, so a corrupt member narrows the allowlist.

One deliberate behavior change. `allowedIntegrations` and
`allowedModelProviders` were the only keys that skipped element
validation, so a corrupted row produced a config the read schema then
refused — the route reading it failed response validation instead of
returning a usable allowlist. They now filter like every other array,
which is fail-closed.

Type-level assertions live in the source rather than a test because
type-check excludes test files; a zod generic degrading to `unknown` would
otherwise be invisible, since the runtime values would still be correct
while every call site lost its narrowing.

* feat(permission-groups): add the capability gate to the authorization funnel

A permission-group key only means something if a server refuses when it is
set. Twelve did not: `hideCopilot`, `hideSecretsTab`, `hideDeployChatbot`
and the rest were read in a sidebar filter and nowhere else, so an
organization that set one had hidden a nav item, not withheld a
capability. The gap was structural — nothing connected "this key is
offered to admins" to "something refuses when it is set" — so this adds
the connection rather than one more check.

Operations already declare their policy as frozen data, so capability
joins it: `defineWorkspaceOperation` takes a capability id, and
`authorizeWorkspaceOperation` refuses when the caller's group withholds
it. One insert covers every surface — internal routes, v2 routes, the
Copilot adapter, trusted tools — because all of them funnel through it,
including the HEAD probe, which has to answer the same question its GET
would or it becomes an existence oracle.

Capability is checked after the role check. `requirePermission` throws the
refusal the v2 surface conceals as a 404, so asking about capability first
would tell a complete outsider which capabilities the organization
withholds. It is also the cheaper check, and it names the remedy the
caller can actually act on.

Two principals pass through, as policy rather than oversight. A workspace
API key authorizes as the workspace and has no user, so no group resolves;
substituting the key's creator would apply a bystander's group to every
caller and break the key when that person left. A deployment run has no
subject either, and denying there would 403 every schedule and webhook in
the organization the moment a group withheld anything — a deployed
workflow runs with the workspace's authority, like any service account,
and what it *does* is still gated by the executor.

Capabilities are ids with a rule registry, not predicates on the
operation: a closure cannot be logged, compared, or read by an audit, and
fifty table operations naming one capability should be fifty strings
rather than fifty identical functions. Rules split on whether the decision
needs a request value; a parameterized one is refused at definition time,
because declared on an operation it would silently never fire.

`check:permission-group-enforcement` is what stops this recurring. It
asserts every capability is reachable, every key claiming capability
enforcement is read by a rule, and no key claiming something weaker is —
so a key cannot reach the admin editor while still documented as
cosmetic. It runs in count-down mode (0/233) until the operations are
annotated, and refuses to report success if its own parsers come back
empty, since an audit that goes quiet when it breaks is worse than none.

Config resolution is memoized per request, keyed on user and workspace and
caching the promise so concurrent callers share one query. The gate
returns before touching the database when the operation declares nothing
or the workspace has no organization, so a personal workspace pays
nothing.

* feat(permission-groups): enforce the twelve UI-only keys on the server

Every capability in the registry now has something that refuses when the
key behind it is set. An organization that hides Tables, Knowledge Bases,
Files, Secrets, Integrations, API keys, the inbox, Chat, or any of the
three deploy surfaces gets a 403 from the API rather than a hidden nav
item.

Most of it is declaration. 163 operations across tables, knowledge, files,
secrets, credentials, workflows, MCP and API keys name their capability,
and the funnel does the rest — the gate added in the previous commit
already covered every surface those operations reach. The table domain
fixes its capability in the factories rather than repeating it at ten call
sites, since every operation in that module is one capability; the audit
reads both that form and the positional one.

Four sites are not workspace operations and are gated where they actually
run:

- Chat is a raw handler, checked after the request parses and before the
  send is claimed. That also settles the resume stream: with no run
  created there is nothing for it to replay.
- `hideTraceSpans` becomes a projection rather than a refusal — the log
  stays readable, its trace spans, block I/O and final output do not.
  Applied before child traces hydrate, so a withheld view does not pay for
  a cross-workspace join it discards, and by deleting rather than omitting,
  because the execution-data schema is a passthrough and would otherwise
  let the fields through.
- The inbox routes are raw handlers with inline queries; a shared guard
  keeps the six of them from drifting.
- The auth-mode and tool-kind capabilities are annotated at the validators
  that already enforce them, which is what lets the audit prove every
  capability is reachable rather than assuming it.

The audit now reports no pending enforcement: nothing can reach the admin
editor claiming a restriction it does not apply. 120 operations remain
unannotated and are counted, not enforced — they are the domains whose
capabilities land with the creation-versus-invocation work.

Three test files fail to load on this branch (`create-credential-connection`,
`add-workspace-files`, `upload-sessions`); they fail identically on the
base commit, and are unrelated to this change.

* fix(permission-groups): close the legacy-block and enrichment bypasses

Two controls were configured and applied to nothing.

**Legacy blocks defeated the integration allowlist.** Any block marked
`hideFromToolbar` was exempt from access control, which covered 44 blocks
— including fully functional superseded versions of Slack, GitHub, Notion,
SharePoint and Google Sheets. Legacy `slack` talks to Slack exactly as
`slack_v2` does, so an allowlist naming `slack_v2` was satisfied by
`slack`, reachable through workflow import, the API, or a Copilot-built
workflow. The admin editor filtered out exactly those blocks, so the hole
was invisible to the person configuring the allowlist.

A superseded block is now judged as the successor its `sunset.replacedBy`
names, transitively, so allowing or denying an integration covers every
version of it and the editor's single row means what it appears to. The
exemption narrows to what it was for: the universal entry point, and a
retired block with no successor — that one has no row to be permitted on
and nothing to be permitted *as*, so denying it would break older
workflows an admin could not rescue.

**Enrichments sent row data with the tool denylist not applied.** The
per-tool gate keys off the acting user and skips entirely when a call
carries none; enrichment runs passed only a workspace. So `deniedTools`
blocked a provider when a workflow called it and not when a table
enrichment did — the same tool, the same row data, one path governed.

The user is now threaded from all three callers, each of which already had
one: the table run resolves it for billing attribution, the internal tool
surface validated it and then dropped it, and the Copilot tool context
carries it. `EnrichmentRunContext.userId` documents why it is load-bearing
rather than attribution, since an omission fails open and silently.

* feat(permission-groups): govern personal API keys per group

`allowPersonalApiKeys` was a workspace column and nothing else, so the
policy was all-or-nothing for the whole workspace: an organization could
not let one team hold personal keys while another could not.
`disablePersonalApiKeys` adds that, and the two combine with AND rather
than one overriding the other. The column stays the coarse switch every
workspace has, including the ones no group governs; the group key narrows
it for one cohort inside an enterprise organization. Either saying no is a
no, which is also why the column is checked first — it costs nothing and
skips the group lookup entirely.

It is not declarable on an operation, and the capability registry says so.
Every other capability withholds something about a resource, so an
operation opts into it; this one refuses a *principal kind*, and applies
to every operation a personal key could reach. It is asserted in the
funnel's personal-key branch instead, annotated so the audit can still
prove the key is enforced.

v1 authorizes in its own middleware rather than through the funnel, so the
check is repeated there. Without it the same key v2 refused would keep
working against v1 — which is the shape of the coverage gap this whole
change exists to remove, so leaving it would have been the same mistake in
a smaller place.

The settings toggle now reads both layers, so the UI never offers a key
type the server will refuse. The key is appended last in the field
registry: declaration order is the wire order, and moving an existing key
would read as an unsaved change in every open group editor.

* feat(permission-groups): govern log export

The CSV export hands over every execution log the workspace ever recorded,
including a column holding the full trace spans, to any member with read
access. It was the widest read in the product and the only one with no
control of its own — an organization could withhold a single log's trace
spans in the UI and still have the whole history downloaded in bulk.

`disableLogExport` withholds the export separately from reading a log,
because those are different exposures: one payload someone is looking at,
versus the entire history in a file. The export also applies the same
trace-span projection the detail view does, so the two agree — a group
that withholds spans no longer discloses them here.

Checked inline rather than through an application use case: this route
queries the log tables directly and predates that boundary. Migrating it
is worth doing on its own, and is not a reason to leave the export
ungoverned until then.

* chore(docs): publish the permission-group 403 code

`FORBIDDEN_DETAIL_CODES` generates the v2 `403` description, so the new
code has to reach the OpenAPI documents or `check:openapi` fails. That
coupling is the point: a refusal a caller can branch on is published
rather than left to be discovered by matching on prose.

* feat(permission-groups): declare the remaining governed capabilities

Adds the thirteen keys the coverage audit found missing, and the rules
that give each one meaning. Nothing enforces them yet — the enforcement
audit lists all thirteen as pending, which is the point: the registry
cannot quietly ship a key that refuses nothing.

They divide into the two exposures the audit kept turning up. Extraction:
table export, bulk file download, execution cost. Provenance and scope:
which connectors may pull an external corpus in, whether a member may
create a knowledge base or a table rather than only use one, whether they
may attach personal credentials, approve a CLI login, or create a
workspace that no existing group would govern.

`allowedKnowledgeConnectors` is parameterized on the connector id, which
required widening the parameterized rule from an auth mode to any request
value. That is the right shape for it: an organization that sanctions
Drive rarely sanctions the other sixty, and a connector is the one
integration that copies a whole external corpus into the workspace.

`maxLoopIterations` is deliberately not here. It is a resource ceiling
rather than an access control — nothing is withheld from anyone — so it
needs a numeric control the group editor has no affordance for, and
folding it in as a boolean would misrepresent it.

* fix(permission-groups): gate the MCP route that bypasses its use case

`POST /api/mcp/workflow-servers` calls `performCreateWorkflowMcpServer`
directly rather than going through `createWorkflowDeploymentServer`, so
the `deploy.mcp` capability declared on that operation never fired here. A
group that hid MCP deployment stopped the v2 route and not this one.

Gating both is what keeps the two doors agreeing. Migrating this handler
onto the use case is the better end state and is worth doing on its own;
it is not a reason to leave the second door open until then.

* fix(permission-groups): gate API-key management, closing the workspace-key escape

The key CRUD routes are raw handlers with inline queries, so `hideApiKeysTab`
hid the settings tab while `POST /api/workspaces/{id}/api-keys` and
`POST /api/users/me/api-keys` still minted keys.

This is also the mitigation the capability gate's design depends on. A
workspace API key authorizes as the workspace and resolves no permission
group, so the funnel's capability check does not apply to it — deliberately,
since substituting the key's creator would apply a bystander's group to every
caller and break the key when that person left. That leaves one escape: a
governed member minting themselves a workspace key that outranks their own
group. Gating the minting closes it at the door.

Keys that already exist keep working. Revoking those is an admin decision,
not something a policy change should do silently to live integrations.

Personal keys are user-global and belong to no workspace, so they resolve the
organization's default group — the same resolution invitations already use for
an organization-level action.

* feat(permission-groups): declare capabilities on the remaining resource operations

Annotates 71 `defineWorkspaceOperation` declarations across eleven domains so
the permission-group audit can tell an unreviewed operation from a deliberately
ungoverned one.

Capability mappings:
  mcp_servers.*                  mcp_tools.use   registering an MCP server and
                                                 storing its credentials was a
                                                 side door around the key that
                                                 blocks calling MCP tools
  mcp_servers.workflow_*         deploy.mcp      reads included, so a group with
                                                 the surface hidden is not still
                                                 told what is published on it
  skills.*                       skills.use
  custom_tools.*                 custom_tools.use
  chat_deployments.*             deploy.chat
  chat.send                      copilot.use
  catalog.connector_types.list   knowledge.use   it enumerates knowledge-base
                                                 connectors and nothing else

Declared `'none'` with a reason: the block and tool catalogs (the set the editor
renders at all), memory and function execution (the executor's own per-run work,
where a gate fails runs the group permits rather than withholding anything),
credential groups (an admin-only, entitlement-gated section no key names), the
BYOK inherited-status read, and platform context.

Adds funnel-level refusal tests for MCP, skills, and the catalog split, so a
capability cannot be declared on an operation and then read by nothing.

* feat(permission-groups): enforce workspace.create, member directory and CLI access

Three capabilities reached the admin editor with a checkbox, a hint, and no
server gate: an organization that set `disableWorkspaceCreation`,
`hideOrgMemberDirectory` or `disableCliAccess` believed it had withheld
something while every route still answered. None is workspace-operation
shaped, so each is wired at an annotated call site rather than through the
declarative funnel.

workspace.create — extended `getWorkspaceCreationPolicy` rather than the POST
route, so forking and the sidebar's "can I create?" signal are covered by the
same decision with no route changes. A new workspace carries no
`permissionGroupWorkspace` row, so a scoped-group member creating one lands
outside every group targeting them — the cleanest escape from the regime
today. The gate resolves the caller's organization even when the resulting
workspace would be personal, because a personal workspace is precisely that
escape. `blockedReasonCode` gains `'permission-group-denied'`; the one caller
that switches on it (`app/workspace/page.tsx`) gets matching copy, since the
existing organization branch would have told a blocked member to ask for
workspace access they already have.

organization.member_directory — `/api/organizations/[id]/members` and
`/api/organizations/[id]/roster` gated on bare organization membership, so
every member could list every colleague's name and email. Both now consult the
organization's default group. No role exemption: the default group governs
owners and admins for every other capability, and carving one out here would
make this the only key whose meaning depended on who was asking.

cli.use — gated at `/api/cli/auth/approve`, the only moment a human is present
in the device-auth handoff. The poll route that redeems the approval for an
API key is deliberately unauthenticated and is left alone: it has no session
to resolve a group against, and re-deciding there would duplicate this check
while racing a config change between the two calls. `workspaceId` is set only
for platform scope, so a personal-scope login falls back to the organization's
default group instead of being the unguarded path.

The workspace-level member list (`/api/workspaces/[id]/members`) is
deliberately NOT gated. It returns id, name and image for people who already
share a workspace with the caller — identities the collaboration surfaces
publish continuously anyway (presence cursors, canvas avatars, log actors,
the sharing dialog), and it exposes no email at all. Hiding it would blank
those surfaces while disclosing the same names over the realtime channel, so
the restriction would read as breakage rather than policy. An organization-wide
roster of colleagues with their email addresses is a materially different
disclosure from "who is in this room with me", and that is what the capability
is named for.

* feat(permission-groups): enforce the knowledge capabilities

`knowledge.create`, `knowledge.upload` and `knowledge.connectors` shipped as
declared capabilities with nothing reading them, so an admin who set the
matching keys got a checkbox and no refusal.

- knowledge.create governs the one operation that opens a knowledge base, so a
  group may query, populate and organize the bases it has without creating new
  ones.
- knowledge.upload governs every path carrying caller-supplied bytes: the
  single-request document upload and the four upload-session operations. The
  connector sync path is untouched — a connector's documents are the sanctioned
  source, which is the point of the key.
- Both rules also read `hideKnowledgeBaseTab`. An operation declares exactly one
  capability, so moving these off `knowledge.use` would otherwise have let a
  group that withheld the whole module still reach them through the API.
- knowledge.connectors is parameterized on the connector id, which the
  authorization funnel never sees, so it is asserted inside
  `createKnowledgeConnector` ahead of the write, through `CAPABILITY_RULES`.
  Update is not gated: it cannot change a connector's type, and re-asserting
  would strand an existing connector the moment an admin narrowed the allowlist.
- The admin editor grows a nested connector picker under Knowledge Base, keyed
  off the client-safe connector meta registry.

* feat(permission-groups): enforce tables.create, tables.export and files.bulk_download

Three capabilities shipped with an admin checkbox and no server gate: an
organization that set disableTableCreation, disableTableExport or
disableBulkFileDownload believed it had withheld something while every path
still answered.

tables.create
  The table operation factories that mint more than one kind of operation now
  take the capability as an argument with no default — a default would let a
  new operation inherit tables.use without anyone deciding it should, which is
  the unreviewed omission this gate exists to prevent. tables.create and the
  copilot create-from-workspace-file import declare it.

  An import targeting `new` also creates a table, but one targeting `existing`
  only fills one and the operation cannot tell them apart: the target is
  request input the funnel never sees. Asserted inside the use case instead.

tables.export
  Declared on createExport and downloadExport. Generating the file is the
  extraction and handing over its bytes completes it; readExport carries no
  rows and cancelExport stops an extraction rather than performing one, so
  gating either would strand a member with an export they can neither watch
  nor stop after the group changed.

  Both raw export routes — the synchronous CSV/JSON stream and the async job —
  bypass the use case entirely and query directly, so they gate inline after
  their existing access check and before any data moves.

files.bulk_download
  files.download serves both a single file and a zipped folder tree, so
  declaring the capability on the operation would also take away saving one
  file, which is not what the key means. The use case asserts it only when the
  request is actually bulk, reusing the same single-file predicate the resource
  authorization already resolved so the two cannot drift.

Every gate decides through CAPABILITY_RULES rather than a config key spelled
out at the call site, so a renamed key cannot silently stop denying anything.

* feat(permission-groups): annotate workflow operations and close the persist-time block bypass

Every `defineWorkspaceOperation` in the workflow registry now declares what a
permission group withholds, so an unfilled field can no longer be mistaken for
an unreviewed one. Most workflow CRUD is honestly `'none'` — the workflow
module has no hide key, and its reads and writes are governed by workspace role
— and each of those carries a reason naming why. `workflows.versions.activate`
gains `deploy.api`: activating a different deployed version changes what the
deployed API serves, so a group that withholds API deployment must withhold it
too. `workflows.public_api.update` stays exempt on purpose: `public_api.use` is
asserted inside the use case and only for the enabling direction, because a
group that withholds public execution must still let an admin withdraw
execution a workflow already has.

Closes a real bypass on the two paths that persist a whole graph. Import and
the graph replace never went through the editing operations, so a member could
save or import a workflow containing a block their group's `allowedIntegrations`
denies; the allowlist was then a property of one authoring route rather than of
what is stored, and the block was refused only by the executor mid-run — after
the workflow had been saved, shared, and possibly deployed. Both paths now
resolve the caller's permission config and refuse with 403 before anything is
written, so there is nothing to roll back, and `importErrorCode` maps 403 to
`forbidden` instead of letting a refusal surface as a 500.

* feat(permission-groups): enforce the four declared-but-unwired capabilities

logs.cost, credentials.personal, triggers.webhook and
copilot.tool_auto_approval each shipped with an admin checkbox and no
server check, so an organization that set one believed it had withheld a
capability while every surface still answered.

logs.cost is a projection rather than a refusal, following the
logs.trace_spans precedent: the log stays readable and its spend does
not. Applied to the detail (run total, itemized ledger, per-block and
per-span cost and tokens), to the list summaries, and to the export CSV
— a hidden detail cost still printed in the list or downloaded in bulk
withholds nothing. The withheld detail still satisfies the wire
contract: `cost` is nullable and `costLedger` optional.

credentials.personal is operation-shaped for the three OAuth connection
operations, which can only ever produce a personal account-linked grant,
and request-shaped for `credentials.create`, whose `type` decides scope —
so that one asserts inside the use case through the capability rule
rather than reimplementing the predicate.

triggers.webhook gates creation only. An already-created webhook must
keep firing: inbound delivery has no session to resolve a group against,
and refusing there would silently break live integrations.

copilot.tool_auto_approval is honoured at read time as well as at write
time, so a stored auto-allow saved before the key was set stops
silencing the prompt immediately rather than only for new entries.

* chore(permission-groups): re-record the settings page module baseline

* feat(permission-groups): require a capability on every workspace operation

All 287 operations now declare one, so the field becomes required and
omitting it is a compile error rather than an unreviewed gap. That is the
whole point: an absent field could not be told apart from an operation
nobody had looked at, which is how twelve config keys shipped with an
admin checkbox and no server gate.

The last seven are logs reads and the public-API workspace reads, all
`'none'` with reasons. The logs ones say the thing worth remembering: a
group withholds *fields* inside a run — trace spans, cost — not the fact
that it ran, so refusing the read would be a different restriction from
the one the admin set.

Also made the connector allowlist actorless-safe. It required a human
subject, so a scheduled sync would have hit a 500 instead of a refusal;
it now passes through with no user, exactly as the funnel treats an
actorless caller. `check:actorless-executor-operations` caught that — one
audit catching the other's blind spot is the argument for having both.

* refactor(permission-groups): one way to ask whether a capability is withheld

Four had accumulated: the authorization funnel, a separate assertions
module, five bespoke per-domain helpers, and raw config-key reads at call
sites. Two of them resolved the config through different helpers, so the
assertions module silently bypassed the per-request memo the funnel uses,
and the two refusal messages were built independently and could drift.

`capability-assertions.ts` is now the single API — workspace-scoped and
organization-scoped, throwing and non-throwing — and the funnel delegates
to it. Everything reads `CAPABILITY_RULES` rather than a config key spelled
out locally, so a renamed key cannot quietly stop denying anything.

`resolvePermissionGroupConfig` takes an optional organization id: a caller
that already loaded the workspace passes it, a raw route omits it, and both
share one memo keyed on user and workspace. Previously the second case had
no memo at all.

`PermissionGroupCapabilityError` moved into the permission-groups module.
The assertions need to throw it and the funnel needs to call them, so
leaving it beside the funnel made the two import each other.

The personal-API-key check now reads its rule instead of the config key
directly, so it cannot disagree with the capability of the same name.

* docs(skills): add add-permission-group-item and validate-permission-group-item

Two skills for the enterprise permission-group system: the end-to-end
procedure for wiring a new governed item (field registry -> capability
rule -> operation declaration or use-case assertion -> golden corpus),
and the procedure for auditing an existing one by proving the refusal
rather than assuming it.

* refactor(permission-groups): remove the count-down mode and settle the module's wording

`capability` became a required field, so the audit's count-down mode could no
longer be reached by an operation that had simply not been annotated yet — and
while it lingered, an un-annotated `capability: 'none'` silently suppressed the
check that every declared capability is enforced. Both causes now fail:

  - a capability the parsers cannot read, which the type system guarantees is a
    declaration form this text-based audit does not follow, not an omission
  - `'none'` without a `permission-group-exempt:` reason

The unreached-capability assertion runs unconditionally as a result.

Also collapses `capabilityRefusalMessage` into its only caller, drops the
callerless `isStaticCapability`, un-exports the compile-time assertion aliases
in `fields.ts` and `capabilities.ts` (the constraint is checked at the
declaration; the export implied a consumer that never existed), and moves the
`logs.trace_spans` rule into `CAPABILITY_IDS` order.

Wording, all of it user- or admin-facing:

  - sixteen capability `describe` strings now agree with the verb in the shared
    refusal sentence ("Knowledge bases is not available" -> "The Knowledge Base
    module is not available"; "Skills" -> "Loading skills")
  - five field hints stated what stayed permitted rather than what the key
    withholds, which reads backwards where the same string is reported as an
    active restriction

* perf(permission-groups): hoist the block-allowlist check out of the save loop

An unrestricted group is the common case, so every workflow save in every
ungoverned workspace was paying two registry lookups per block to reach an
answer that could not change. The allowlist becomes a Set via the existing
`toAllowedIntegrationTypes`, and the null case returns before the loop.

Also corrects `isBlockTypeAllowed`'s doc, which restated its signature and
had gone stale: it asks two questions, and the second — deployment
visibility — is exactly why the persist-time guard cannot reuse it.

* refactor(permission-groups): one API for every capability gate

Five bespoke gates and eleven inline config-key reads all answered the same
question in their own vocabulary, so a renamed key would have silently stopped
denying anything at each of them and the refusal wording drifted per surface.
Every one now asks through `capability-assertions`, which reads
`CAPABILITY_RULES`.

Deleted:
  - `inboxWithheldResponse` (`lib/mothership/inbox/access.ts`)
  - `apiKeyManagementWithheldResponse` and
    `personalApiKeyManagementWithheldResponse` (`lib/api-key/access.ts`)
  - `isOrgMemberDirectoryHidden` and `isCliAccessDisabled`
    (`ee/access-control/utils/permission-check.ts`)

Routes that render their own response shape use
`isWorkspaceCapabilityWithheld`/`isOrganizationCapabilityWithheld` and build
their own 403 from `capabilityRefusal`; the projections that strip fields out
of a log response keep reading the config but ask `capabilityDeniedBy` rather
than naming the key. Every `permission-group-enforced:` annotation moved with
its decision.

* fix(permission-groups): stop capabilities refusing workflow runs

A delegated executor principal usually carries a user subject — the
subject resolver recurses into the delegation context — so a run was
getting the triggering member's capabilities as well as their role. That
turned every capability on an executor-reachable operation into a runtime
kill-switch: ticking "hide the Knowledge Base module from the sidebar"
made retrieval 403 mid-run, "hide Tables" broke Table blocks, "hide the
Files settings tab" broke `/api/files/serve` and with it every rendered
image and PDF, and "hide the Integrations settings tab" failed every OAuth
block in the workspace, including credentials an admin had shared
deliberately.

A capability names what a *person* may reach in the product. A run reaches
those resources because a block in the graph does, and what a run may do is
governed separately by `assertPermissionsAllowed`, which gates every block,
tool and model against the same group. So an executor delegation now
carries the triggering user's role but not their capabilities — the same
reasoning already documented for a subject-less deployment run, which was
only ever half the case.

Copilot is deliberately not exempt: it acts as the person, so it must not
reach what the person may not. Tested both ways.

Found by an adversarial review of the branch, not by a failing test — the
existing test pinned the broken behavior as if it were intended, which is
why it is now inverted with the reasoning written down.

* refactor(permission-groups): keep only the validators that outlive the rules

`permission-check.ts` predates `CAPABILITY_RULES`, so several of its
`validate*Allowed` helpers restated a config key the rule registry already
names, and two of its error classes existed only to be caught one frame later
and rethrown as the `ForbiddenOperationError` the rule would have raised.

Collapsed:

  - `validateMcpToolsAllowed`, `validateCustomToolsAllowed` and
    `validateSkillsAllowed` were `assertPermissionsAllowed`'s `toolKind` branch
    spelled out three more times. Their four call sites now pass `toolKind`
    directly, which keeps the `ExecutionContext` config memo and the same error
    classes. Their enforcement annotations move to `assertPermissionsAllowed`.
  - `ChatDeployAuthNotAllowedError` and `PublicFileSharingNotAllowedError` were
    each thrown from one place and immediately translated by every caller into
    `ForbiddenOperationError` with the very detail code their rule declares.
    Both gates now raise `PermissionGroupCapabilityError` once, and the five
    try/catch translations are gone.

`validatePublicFileSharing`, `validateChatDeployAuth`,
`validateInvitationsAllowed` and `validatePublicApiAllowed` stay: the first two
decide on a request auth mode the authorization funnel never sees, and the last
two OR a permission group against a deployment-wide env flag. All four now read
`CAPABILITY_RULES` rather than a config key, so a renamed key breaks the build
instead of silently ceasing to deny anything. `assertPermissionsAllowed` stays
for the same reason it always existed — it governs what a run may do, not what
an operation is — with its tool-kind branch driven off the rules.

The refusal wording for a blocked chat auth mode and a blocked file share now
matches the funnel's sentence ("... is not available under your organization's
permission group"). HTTP status and detail code are unchanged.

* fix(permission-groups): close the defects an adversarial review found

`disableTableExport` withheld nothing. `tableOperations.downloadExport` was
gated, but a second raw route handed back a presigned URL for a finished
export behind workspace-read alone, and the workspace job listing named
every colleague's `jobId`. List, take one, download. Both are gated now —
the listing withholds as an empty list rather than an error, because the
caller has no exports to act on and erroring the tray would report a
failure where the honest answer is that there is nothing to show.

`tables.create` and `tables.export` now subsume `hideTablesTab`, the way
the knowledge rules already did. An operation declares exactly one
capability, so a narrower one replacing a broader one lets the broader key
through: a group that hid the whole Tables module could still create and
export tables.

`triggers.webhook` gated creation but not reactivation, which is the act
the key names. Only `false → true`: deactivating stays open, or a policy
change would strand a member with a live webhook they cannot turn off.

Enrichment ran under the workspace's billing owner. For a system-triggered
cell the billing attribution names the payer, and running a member's tool
denylist against a bystander is wrong both ways — it fails cells nobody
meant to govern, and skips the denylist for whoever actually triggered
one. It now names the triggering user or nobody, which is the documented
behavior for an actorless run and what CLAUDE.md requires.

Two projection leaks: the CSV export filled its message column from
`finalOutput`, which the detail view deletes for that same viewer, and
`stripSpanCosts` cleared `cost` but not `tokens` — the same spend in
another unit, recoverable by anyone who knows the model's rate.

Organization admins are exempt from the member-directory capability. The
response is the only source for the team-management page and its seat
snapshot, so withholding it took away the page an admin would use to
change the setting.

Workspace API-key revocation is no longer gated. Withholding key
management must not withhold key revocation — an admin unable to revoke a
leaked credential turns a policy into a security hazard. The personal-key
delete route was already ungated for that reason.

Also: the logs list and detail resolve through the per-request memo with
the organization id they already hold. The list is polled, its operation
declares no capability, so this was a net-new workspace query and plan
check on every request including for personal workspaces that can never be
governed.

* refactor(permission-groups): route every config read through the request memo

Eighteen sites resolved a permission-group config by calling
`getUserPermissionConfig` directly, so a request that authorized several
operations paid one lookup per site instead of sharing the per-request
memo the funnel already establishes.

Capability gates now go through the canonical assertion helpers, so the
decision reads CAPABILITY_RULES rather than a config the call site then
tests itself. Projection sites — the copilot catalogs, the VFS, the
integration allowlists — still read the config, but obtain it from
`resolvePermissionGroupConfig` so they share the same memo.

`lib/workspaces/policy.ts` uses `isOrganizationCapabilityWithheld`: no
workspace exists yet, so the org-scoped form is the one that applies.

Also merges a stacked TSDoc pair on `assertConnectorTypeAllowed`, where
the first block sat orphaned above the second.

* test(permission-groups): cover the inbox, workflow-MCP, and Chat capability gates

Three capability gates shipped without a test. Each now asserts both
directions — refused when the group withholds the capability, and allowed
both when a group governs the user but withholds nothing and when no group
governs at all, which is every personal workspace and non-enterprise org.

Extracts the config-scope mock the eight existing permission-group tests
each hand-rolled into permissionGroupScopeMock in @sim/testing. The shared
version exports withPermissionGroupScope as a real passthrough, which a
route-level test needs: withRouteHandler wraps every handler in it, so a
factory exporting only resolvePermissionGroupConfig turns the gate under
test into an unrelated 500.

* docs(permission-groups): tell admins what they are actually revoking

Twelve `hide*` keys are now server-enforced, but their admin copy still
described the cosmetic behavior they used to have. A hint reading "Hide the
Tables module from the sidebar" tells an admin they are tidying a nav bar
while they are revoking a module — and the same string is read a second time
by `getActivePermissionGroupRestrictions` as the prose for an active
restriction, where "hide" is simply false.

Rewrite every misleading label and hint to name the access withheld, and
re-file the categories: `Sidebar`, `Settings Tabs`, `Deploy Tabs` and
`Workflow Panel` named UI chrome that no longer decides anything.

Also deduplicate the model and block-type gates that `assertPermissionsAllowed`
copied verbatim from `validateModelProvider` / `validateBlockType`, drop four
dead exports from the access-control hooks, and correct the two
permission-group skills against the current code.

* refactor(permission-groups): remove indirection and close the audit's silent-drop hole

Deletes what no longer earns its keep in the permission-groups module and the
application-operation boundary, and hardens the enforcement audit against
parses that go quiet.

Removals, each proven unused by a whole-worktree grep:
- `assertOrganizationCapability` — no caller anywhere.
- `authModeDeniedBy` and the `ShareAuthMode` alias — the same predicate
  `allowlistDenies` already expressed, spelled with different words.
- `capabilityRefusal` was defined twice, in two files each documented as "the
  one sentence every capability refusal uses". It now has one definition beside
  `CAPABILITY_RULES`, which `refuseCapability` also uses.
- The `schema` member on every field entry: `readSchema` already carried each
  key's wire type, and the config type now derives from it.
- Re-export shims for `PrincipalKind` and `PermissionGroupCapabilityError`; the
  barrel names their real modules.
- The duplicated restriction shape in `queries.ts`, now the exported type.

The audit no longer drops operations in silence. A `defineWorkspaceOperation`
call whose id it cannot read — a const reference, or a wrapper written as an
arrow const rather than a `function` — is a finding rather than an absence, and
a file that calls the builder and yields nothing is reported too. Both forms
previously took the count from 287 to less with a passing tick.

`resolvePermissionGroupConfig` keeps its key: `organizationId` is a function of
`workspaceId`, so adding it would split the cache and double the queries. Said
so in TSDoc and pinned it with a test.

* refactor(permission-groups): drop the types.ts re-export shim

CLAUDE.md forbids re-exporting from a non-barrel file. types.ts re-exported
six names that live in fields.ts, so importers had two paths to the same
symbol. Repoint them at the source.

What was left held no types: two DB constraint-name maps, now constraints.ts,
and permissionGroupConfigSchema, which joins the other derivations in
fields.ts. types.test.ts covers the derived parser, so it becomes
fields.test.ts.

* fix(permission-groups): enforce tables.use on the raw internal table routes

`hideTablesTab` declares `booleanRestriction('capability', …)`, and
`tables.use` is declared on the 20 table operations that govern
`/api/v2/tables/**` and the Copilot table tools. Sixteen internal routes
under `/api/table/**` never became operations: they authorize with
`checkAccess`, which did `getUserEntityPermissions` + `permissionSatisfies`
and nothing else, then called the table service directly. A member of a
group denied Tables could still add a TTL column, import, export, delete,
restore, and read every row through them; the only other guard was a
client-side redirect.

`checkAccess` is the choke point all sixteen share, so the gate goes there
— one place to forget rather than sixteen, and a route added later inherits
it. Three more routes name a workspace rather than a table (`import-csv`,
the root `import-async`, `restore`) and assert inline through the same
shared refusal response.

Capability runs strictly after the 404 and the role check, matching
`authorizeWorkspaceOperation`: a role failure conceals whether the table
exists, and refusing on capability first would tell a non-member which
modules the organization withholds. The denial variant of `AccessResult`
carries the capability so `accessError` can raise the shared refusal
sentence and `PERMISSION_GROUP_CAPABILITY_BLOCKED` rather than the role
message it is not.

* test(permission-groups): make every operation fixture declare its capability

`capability` is a required field, but `apps/sim/tsconfig.json` excludes test
files and `check-permission-group-enforcement.ts` walks past them, so 22 of the
26 `defineWorkspaceOperation` fixtures across these seven suites omitted it and
nothing complained. Each now names the capability it is actually modelling —
`files.use` and `integrations.manage` where the fixture stands for a real file
or credential operation, `'none'` where the operation is scaffolding for an
assertion about roles, principal kinds, audit, or resource policy.

The guard in `defineWorkspaceOperation` is kept and tightened rather than
removed as unreachable. It previously skipped an `undefined` capability instead
of refusing it, so a capability-less operation defined cleanly and then threw
`Cannot read properties of undefined` from `capabilityDeniedBy` — but only for
a caller whose organization has a permission group, meaning it passed every
personal workspace and every non-enterprise test and failed exactly in the
tenants that bought the feature. It now refuses at definition time, its TSDoc
says why it survives a required field, and two tests hold it to that.

* refactor(permission-groups): share the memo, the refusal sentence, and the contract

Route validatePublicFileSharing, validateChatDeployAuth, validatePublicApiAllowed
and validateInvitationsAllowed through resolvePermissionGroupConfig so a request
that authorizes an operation and then asserts one of these resolves the group
once. Outside a scope the resolver degrades to a direct call, so the executor and
job paths are unaffected.

Raise the knowledge-connector allowlist refusal through refuseCapability instead
of a hand-written copy of the shared sentence. PermissionGroupCapabilityError is
a ForbiddenOperationError carrying the same detail code, so the status and error
contract are unchanged.

Make resolveUserAccessControlContext module-private — it had no consumer outside
its own file, every caller elsewhere already holds the organization id — and move
its context-shape coverage onto the verified variant that callers actually use,
keeping the workspace-lookup behavior covered through getUserPermissionConfig.

Export the permission-group request type aliases from the contract and consume
them in the hook, replacing four hand-written wire types.

* test(knowledge): assert the shared connector refusal sentence

The refusal now comes from refuseCapability, so it reads like every other
capability refusal and no longer names the connector — matching its two
sibling parameterized capabilities, which already say 'This chat
authentication mode' and 'This file-share authentication mode'.

* fix(permission-groups): enforce declared capabilities on the v1 public API

`app/api/v1/middleware.ts` authorizes in its own middleware rather than
through `authorizeWorkspaceOperation`, so none of the capabilities the
funnel applies reached it. It asserted exactly one — `personal_api_key.use`
— and nothing else. A member of a group that withholds Tables was correctly
refused on `/api/v2/tables/**` and on every internal `/api/table/**` route,
and could still list, create and write tables through `/api/v1/tables/**`
with a personal API key; the same held for Knowledge Base and Files, and for
deploying a workflow through `/api/v1/workflows/[id]/deploy`. That left
`hideTablesTab` and its siblings bypassable by the very credential the
branch exists to gate.

The declaration is threaded through the middleware rather than hand-asserted
per handler: `validateWorkspaceAccess` takes a required `V1RouteCapability`,
and the two shared resolvers routes compose it through —
`resolveKnowledgeBase` and `resolveV1DeploymentWorkflow` — take one too.
Required, and `'none'` spelled out rather than omitted, for the same reason
`capability` is required on `defineWorkspaceOperation`: an absent
declaration cannot be told apart from an unreviewed one. Every value is the
capability the route's v2 or internal counterpart already declares; v1 gets
no mapping of its own.

Three invariants are preserved. The check runs strictly after the key-scope
and workspace-role checks, matching `authorizeWorkspaceOperation`, so a
capability refusal never reaches a non-member who would learn from it that
the workspace exists and which modules the organization withholds. A
workspace API key passes through ungated — it has no user and so no group,
and its `rateLimit.userId` is the key's *creator*, a bystander whose group
must not govern every caller of a shared credential. And no execution route
is gated: `/api/v1` contains none, and the deployment routes gate
`deploy.api` exactly as `workflows.deploy` and `workflows.versions.activate`
already do, which changes who may deploy without touching a workflow already
running.

* refactor(permission-groups): keep the authorization funnel's module graph light

`capability-assertions.ts` and `config-scope.server.ts` sit under
`@/lib/core/application`, which ~24 domain `operations.ts` modules import, and
both reached into `ee/access-control/utils/permission-check.ts`. That module
also holds the model, block and tool gates, so every authorization decision
transitively loaded the provider registry, the block registry and the billing
barrel — and through them `lib/workflows/**` and `lib/uploads/**`.

Nothing reported the edge. The only symptom was two knowledge use-case suites
failing on a partial mock of `@/lib/uploads/utils/validation`, a module they
never meant to load.

Move the resolution layer — `mergeEnvAllowlist`, group resolution, and the
config readers — into `lib/permission-groups/resolve.server.ts`, where the
funnel can reach it without the gates. `permission-check.ts` re-exports them,
so the surfaces that read every validator from one module are unchanged, and
its enterprise-plan check, `isHosted`/`isAccessControlEnabled` short-circuit
and env-allowlist merge keep their exact semantics and ordering. This also
breaks the import cycle the two modules had formed.

`check:application-graph` fails the build if the edge returns, walking runtime
`import`/`export … from` specifiers from the funnel's roots. It joins
`check:audits` by living in the `check:*` namespace.

* refactor(permission-groups): keep the universal route wrapper's graph light

`withRouteHandler` wraps every API route in the app, so anything it reaches
at runtime is loaded by every route and every route test. It imported
`withPermissionGroupScope` from `config-scope.server.ts`, which imports the
resolver at module scope, which reaches `lib/billing/types` — so every route
eagerly loaded the billing graph to get an AsyncLocalStorage wrapper it may
never use. The visible symptom was `app/api/chat/[identifier]/otp/route.test.ts`
failing with `z.coerce.number is not a function` on its own partial `zod` mock.

Splits the import-free scope wrapper into `request-scope.server.ts`, leaving
`config-scope.server.ts` as the resolver the gate call sites already import
heavy things to use. The guarded require of `node:async_hooks`, the React
`cache()` fallback outside a scope, promise-caching, negative caching, and the
`userId:workspaceId` key semantics are unchanged.

Extends `check-application-graph.ts` so the roots each carry their own
forbidden list: the route wrapper is now a guarded root, and additionally may
not reach `lib/billing/`, the permission-group resolver, auth, copilot or
knowledge. Those stay allowed for the funnel roots, where `resolve.server.ts`
legitimately reads a subscription to decide enterprise gating.

* fix(permission-groups): keep a workspace API key out of its creator's group

`checkAccess` gained a `tables.use` gate for the raw `/api/table/**` routes,
which authenticate with `checkSessionOrInternalAuth` and so only ever serve a
real person. `/api/v1/tables/[tableId]/**` shares the same helper and passes
`rateLimit.userId`, which for a WORKSPACE key is the key's creator — so a shared
credential started failing whenever the bystander who minted it sat in a group
that withholds Tables.

`checkAccess` now takes a required `TableAccessPrincipal` discriminated union
instead of a bare user id. A caller cannot reach the gated behavior by passing a
string, and the only way to skip the gate is to name the `workspace_api_key`
kind explicitly. v1 builds the principal through `tableAccessPrincipal`, which
reads `keyType` through the one shared `capabilityGovernedUserId` helper that
`resolveCapabilityRefusal` now uses too. The internal routes keep the gate.

Separately, `logs.trace_spans` and `logs.cost` are projections rather than
gates, so the v1 logs routes correctly declare `capability: 'none'` and still
have to withhold the fields themselves — which they did not, handing a governed
member trace spans, block payloads, the final output and every cost figure via
`?details=full&includeTraceSpans=true`. The flags and the field-stripping now
live in `lib/logs/log-projection.ts`, which `readLogDetail`'s caller resolves
through as well, so there is one copy of the redaction rule.

* fix(permission-groups): make the key-creator substitution structurally impossible in v1

The sweep across every remaining /api/v1 domain (knowledge, files, workflows,
logs, audit-logs, copilot, tables) found no route deciding a permission-group
capability from an API key's creator: every capability decision already funnels
through `capabilityGovernedUserId`, either via `validateWorkspaceAccess` /
`resolveKnowledgeBase` / `resolveV1DeploymentWorkflow`, via `tableAccessPrincipal`,
or directly at the three log-projection call sites.

What was left was the shape the bug takes rather than the bug. `resolveCapabilityRefusal`
guarded on `capabilityGovernedUserId(rateLimit)` and then asserted against a
*different* variable — the `userId` the role check uses. The two agreed, but
nothing made them agree. It now takes no caller-supplied id at all and asserts
against the guard's own return value, and `resolveWorkspaceScope`'s
`personal_api_key.use` check reads the same helper instead of `rateLimit.userId`.

`check:capability-subject` is what stops the next route. It asserts that no v1
file outside the middleware imports the permission-group modules, that every
capability sink's subject argument came from `capabilityGovernedUserId`, and
that it found at least one such call — so a refactor into a form it cannot read
fails loudly instead of passing vacuously. It joins `check:audits` by name.

Tests cover the two v1 capability paths the gate suite did not reach: the
`personal_api_key.use` key-kind refusal and the `logs.cost` field projection,
each asserting that a workspace key passes where its creator's group would deny
and that a personal key is still refused.

* docs(skills): realign add-permission-group-item with the refactored code

types.ts is gone (fields.ts + constraints.ts), group resolution moved out of
ee/ into resolve.server.ts, the request scope split in two, and
assertOrganizationCapability was deleted. Adds the definition-time capability
guard and why it exists given tsconfig excludes tests, the satisfies rule, the
Array.isArray parser guard, the executor/Copilot principal split, the v1 and
table-route capability subjects, the log-projection distinction, and the two
new audits.

* docs(permission-groups): state what the executor exemption actually does

The exemption's rationale claimed a deployed workflow runs with the
workspace's authority rather than any member's group. It does not. For an
actorless run the actor falls back to the billing owner, so the block, tool
and model gates resolve the payer's group — which is both a bypass (schedule
a run to escape a denial) and a wrong denial (the payer's group narrows every
unattended run). That predates this branch, but justifying the exemption with
a premise that does not hold is our doing.

* docs(skills): realign validate-permission-group-item with the refactored code

Drops the stale standing finding that assertConnectorTypeAllowed writes its own
refusal sentence (it calls refuseCapability now), repoints types.test.ts at
fields.test.ts and the deleted assertOrganizationCapability at
isOrganizationCapabilityWithheld, and adds the projection-vs-gate case, the
subject audit for v1 and the table routes, the executor/Copilot split, the
Array.isArray and satisfies guards, and the two new audits.

* fix(permission-groups): enforce secrets.manage and integrations.manage where they were only claimed

The workspace environment route is raw `withRouteHandler` and never reaches
the `secrets.*` operations, so `hideSecretsTab` restricted nothing on the one
route the Secrets UI actually calls. Gate GET/PUT/DELETE on `secrets.manage`,
after the workspace role check so a non-member still learns only that the
workspace is out of reach.

`defineCredentialUserOperation` mints operations without calling
`defineWorkspaceOperation`, so neither that builder's definition-time guard nor
`check:permission-group-enforcement` ever read them, and all five shipped with
no capability at all. Give the interface a required `capability`, name
`integrations.manage` on each, and apply it in
`defineAuthorizedCredentialUserUseCase` — org-scoped, since a user's own OAuth
connections belong to no workspace.

* test(permission-groups): pin the secrets.manage gate on the environment route

Projects the refusal off the canonical PermissionGroupCapabilityError rather
than rebuilding the sentence, so the message and the
PERMISSION_GROUP_CAPABILITY_BLOCKED detail code match every other surface.

Without the gate the read and the delete both answer 200 — the read hands back
every stored workspace secret the tab would show.

* fix(permission-groups): gate the CLI key mint on api_keys.manage

The CLI handoff minted a workspace API key with no capability check. An
admin denied `api_keys.manage` was refused by
`/api/workspaces/[id]/api-keys` and got the identical key from
`sim login --workspace`.

That is worse than one missing gate. A `workspace_api_key` principal
resolves no user and therefore no permission group, so the authorization
funnel's capability gate never applies to it. That pass-through is
deliberate — substituting the key's creator would apply a bystander's
group to every caller of a shared key — and its entire safety argument,
stated in `workspace-authorization.ts`, `app/api/table/utils.ts` and
`app/api/v1/middleware.ts`, is that minting such a key is itself
capability-gated. With the terminal ungated, a governed member could mint
a key that escaped every capability their group withheld.

Gated at approve, not poll. The poll is unauthenticated by necessity, so
it has no session to check anything against; approve is the only moment a
human is present. The approval record is already the sole carrier of the
decision — the poll body is a request id and a secret, and cannot assert a
scope, a workspace, or a binding — so a refusal writes no record and a
poll driven directly answers `pending` forever.

Resolved from the key's own scope: a bound key belongs to its workspace,
an unbound personal key belongs to none and falls back to the
organization's default group, matching `/api/users/me/api-keys`. Runs
after the role check, so a non-admin still learns nothing about the group.
The copilot scope mints from a separate key space the API-keys surface
does not manage, so `cli.use` remains its whole gate.

Also makes two admin hints honest. `disableWorkspaceCreation` and
`disableCliAccess` gate actions that name no workspace, so both are read
from the organization's default group and neither can be denied by a
group scoped to specific workspaces — correct, since a member may be
governed by different groups in different workspaces and there is no one
scoped group to pick. The editor offers both checkboxes on such a group
regardless, and the hints said nothing about it.

* test(permission-groups): pin the integrations.manage gate on current-user credential operations

Without the gate all three routes answer 200: a member whose group revokes
Integrations can enumerate every OAuth connection and disconnect any of them.

* fix(permission-groups): close the cost oracle and two capability-before-role inversions

`logs.cost` is a projection: the field is blanked, the row still comes back.
That is only a withholding if the query surface cannot select on the number
either. It could — `sortBy=cost` and `costOperator`/`costValue` reach the same
indexed `cost_total` column on the first-party list, the dashboard stats read,
and the CSV export, so a member whose group hides spend recovered every run's
cost by bisecting `cost > X` and reading which rows (or how many, with
`includeTotal`) came back.

`assertLogCostQueryAllowed` in `log-projection.ts` refuses those queries rather
than dropping the clause: a list of every run under a `cost > 5` chip, in an
order nobody asked for, is a wrong answer presented as the right one, and the
refusal discloses nothing — the workspace role check has already passed, so the
caller is a member being told about their own group. `logs.trace_spans` needs no
counterpart; nothing it withholds is filterable or sortable on any log surface.

Two capability checks also ran ahead of their role check, inverting the
concealment ordering the rest of the branch keeps. The funnel asserted the
group's `personal_api_key.use` before resolving the caller's workspace
permission, and `prepareWorkspaceInvitationContext` asserted `invitations.send`
before `hasWorkspaceAdminAccess`. Both now follow the role check, so a caller
with no reach into the workspace gets the concealed refusal instead of a 403
naming how the organization configured a cohort. The workspace-level
`allowPersonalApiKeys` column keeps its fail-fast: it is a property of the
workspace, not of a group.

Three tests could not fail without the gate they named. The `logs.export` 403
fired in no test at all; the MCP operation refusals selected their subjects with
`operation.capability === x`, a filter over the field under test, so dropping
the capability from `mcp_servers.create` just removed it from the filter and
left the suite green. Both are pinned now, along with the new refusals and a
first test file for the stats route.

* fix(permission-groups): make an operation the audit cannot read a failure

`check:permission-group-enforcement` found operations by scanning for
`defineWorkspaceOperation(` call sites, so a domain that minted operations
through a builder of its own was invisible — and invisibly so: the file was
scanned, some other operation in it was counted, and the audit printed a tick
while the rest went unread. A silent undercount reads exactly like success,
which is how five OAuth-connection operations shipped with no capability and
`hideIntegrationsTab` stayed bypassable.

Twenty-eight operations across eight registries were in that blind spot, not
five: audit logs, organization BYOK keys, billing reads, organization usage,
credential-group enrollment, `/api/v2/meta`, the session-scoped knowledge entry
points, and account self-service — the last two minted from bare object literals
with no builder at all.

Both halves of the fix, because neither alone is enough:

  - the type. `capability` moves from `WorkspaceOperation` to the base
    `ApplicationOperation`, so an operation that answers the question nowhere
    does not compile, and every builder shares one `assertOperationCapability`
    guard. `apps/sim/tsconfig.json` excludes test files, so this narrows the
    blast radius rather than closing it.

  - the audit. It now follows the whole `define*Operation` family, and asserts
    that every member of an exported `*Operations` registry was actually read.
    That second check asks the only question whose answer distinguishes a clean
    file from one the parsers walked past, and it is what surfaced the two
    registries no builder touched.

The file-level skip is gone with it: a module is examined when it mints an
operation *or* exports a registry, rather than only when it names one builder.

Every newly visible operation declares `'none'` with a reason — each is
organization-scoped, account-scoped, or delegates to a workspace operation that
already carries the capability. Count goes 287 -> 315.

* fix(permission-groups): gate the session arm of the OAuth credentials read

`GET /api/auth/oauth/credentials` lists a user's OAuth credentials for a
provider and had no capability reference at all, so `hideIntegrationsTab`
withheld the Integrations module everywhere except the endpoint that hands out
its credentials.

It could not simply be gated. The route authenticates through
`checkSessionOrInternalAuth`, so one handler answers both a person opening the
credential selector and the executor resolving a credential for a running
workflow. Refusing both would 403 a deployed workflow the group permits — a run
failing hours after an admin ticked a box, with nothing on the surface
connecting the two.

So the callers are split, the way `principalUserId` splits a workspace API key
from a user: the session arm is gated on `integrations.manage`, the internal
arm is not. A permission group describes what a person may reach, and the
executor is not that person.

Two call sites, because the query can carry a workspace or only a
`credentialId`. The `credentialId` path is asked after each branch's own access
check, never before, so a caller who may not reach the credential at all cannot
learn from the refusal wording that its workspace is one their group governs.

* fix(permission-groups): project logs on the v2 surface and close its cost oracle

`/api/v2/logs` and `/api/v2/logs/{runId}` applied no field projection at all.
A personal API key carries a user and therefore a group, so an enterprise
member whose group sets `hideCostInfo` or `hideTraceSpans` read the run total,
the itemized ledger, and the whole trace in full through v2 — while the same
person was withheld all of it on the internal and v1 surfaces. The keys claimed
an enforcement they did not have.

Applied in the two application use cases rather than in the presenters, so the
withholding travels with the read instead of with one surface's rendering:

- `listPublicLogs` resolves the shared `resolveLogFieldProjection`, blanks the
  row's spend (`costTotal` for a workflow run, `cost` for a job run), runs
  `projectExecutionData` over the materialized payload, and turns off the
  `includeTraceSpans`/`includeFinalOutput` render flags. The flags matter: the
  presenter reads `executionData.traceSpans ?? []`, so a deleted array would
  come back as an empty one rather than as an absent field.
- `getPublicLog` does the same and drops the cost ledger, which itemizes the
  very total it blanks.

Both resolve their subject through `resolvePrincipalSubjectUserId`, the helper
the sibling internal use cases already use: a workspace API key represents no
user, resolves to `undefined`, and reads whole rather than borrowing the key
creator's group.

`listPublicLogs` then refuses `sortBy=cost` and `minCost`/`maxCost` for a group
that withholds spend, and `/api/v1/logs` — which projected the value but still
passed the bounds into `buildLogFilters` — gains the same refusal. Blanking the
figure while answering a filter over it leaves a bisection oracle: one request
per probe, with the page as the answer. Refused rather than dropped, after the
workspace access check, so the caller is a member being told about their own
group.

`provider-catalog.test.ts` was vacuous: its env allowlist was the narrower half,
so the intersection was `['salesforce']` whether or not the permission group was
read at all. The fixture is inverted so dropping the group half makes Trello
visible and the assertion goes red.

* test(oauth): mock the organization lookup the new capability gate makes

The current-user credential gate resolves the acting user's organization to
find the group that governs them. These two suites mock `@sim/db` with their
own factory for the route's inline queries, so the unmocked lookup threw and
every assertion saw a 500. Resolve no organization — the ungoverned case; the
governed one is covered by credentials/application/capability-gate.test.ts.

* fix(permission-groups): project run cost on the v2 workflow-runs listing

This listing carried the same per-run total hideCostInfo withholds on every
other log surface, and applied none of it — an enterprise member whose group
hides spend read it in full through a personal API key.

Projected in the use case rather than the presenter, so the withholding
travels with the read. A workspace API key represents no user and therefore
no group; it reads whole, and the key's creator is never substituted.

* test(permission-groups): share the v1 ambient request-admission mocks

Three new v1 gate suites each carried a byte-identical 15-line block of
subscription, rate-limiter, and rate-limit-context pass-through factories.
None of them steers those seams — they only need admission to succeed — so
the block moves to `packages/testing` beside the v2 equivalent.

* refactor(permission-groups): one builder for the internal capability-refusal 403

* test(permission-groups): drop the duplicated v1 log-projection gate tests, tidy the late patches

`v1/capability-gate.test.ts` re-asserted the `/api/v1/logs` cost projection
that `v1/logs/projection.test.ts` already covers on the same route through the
same `projectCostTotal` call, and more strongly — the workspace-key direction
there pins spans as well as cost. The gate suite now says so in its header
instead.

The oauth patches arranged their mocks above `vi.clearAllMocks()` and, in the
disconnect suite, declared a `vi.mock` from inside a test body; both now read
like the rest of their file. The `integrations.manage` block repeated its own
beforeEach in three of four tests.

* docs(skills): trim the permission-group-item skills to their load-bearing facts

Both skills were re-audited against the final code and are accurate, but they
grew through three correction rounds into narrative. Cut history, duplicated
explanations of the same invariant, and prose walkthroughs of code; kept every
invariant, and moved enumerations (helper choice, principal rules, audits,
forbidden graph edges) into tables.

add-* now owns the procedure and the rationale; validate-* owns the checklist
and cross-references it rather than restating it.

Corrected against the code while trimming: the enforcement audit's success line
reads 315 operations, not 287, and the audit's completeness half — the exported
`*Operations` registry cross-check and the `define<Domain>Operation` family
match — was missing from add-*.

* test(v1): make the mocked middleware helpers mirror the real ones

`tables/[tableId]/route.test.ts` re-implemented `tableAccessPrincipal`
branching on `keyType === 'workspace'`; production branches on
`=== 'personal'`, so the stub disagreed with it for any other keyType and
would have quietly authorized the wrong principal the moment a caller stopped
setting one. Both stubs now name the helper they mirror and say why the branch
reads `keyType` rather than the presence of a user id.

* refactor(permission-groups): converge the workspace-else-organization capability fallback

* refactor(table): delete the dead ungated table access checks

* refactor(permission-groups): fold the single-caller unverified context resolver

* docs(permission-groups): correct the organization-scope call-site claim

* chore(permission-groups): apply the /cleanup pass findings

React Query: the api-keys policy read now fails closed while its query is
pending or errored instead of treating an unanswered question as an
unrestricted answer, and the admin switch binds to the stored workspace
column it edits rather than the combined policy — a group's
disablePersonalApiKeys no longer renders the stored setting as off with a
toggle that mutates successfully and changes nothing visible.

Comments: relocate one misattached TSDoc block, drop test-file restatements
of rationale the route files canonically own, drop one-liners restating the
adjacent type composition, and convert the one non-TSDoc comment block to
TSDoc. The machine-read enforcement annotations and every invariant comment
stay.

* docs(skills): patch six omissions in the permission-group skills

The trim round left gaps where the remaining text reads as exhaustive:
the gate-helper enumeration, the raw-route 403 example, the executor
enforcement path, the personal_api_key.use classification, where the
capability field is required, and the org-null test short-circuit.

* fix(permission-groups): say where hideOrgMemberDirectory is read from

The member directory is an organization-scoped read with no workspace for
the funnel to authorize, so both call sites resolve the organization's
default group. An admin who ticks the box on a workspace-scoped group gets
nothing, and the hint said nothing about it — the same silence
disableWorkspaceCreation and disableCliAccess were given wording for.

Extends the pinning test that covers those two siblings.

* fix(logs): project cost and execution payloads on the run-detail and snapshot reads

The run-detail family (getWorkflowExecutionStatus, its v2 use case and the
internal executions route) and the execution-snapshot read returned cost,
finalOutput and blockOutputs whole, so a member whose group withholds spend or
execution detail on the list and log-detail surfaces read them one click deeper.
Copilot's @log mention context did the same with the run total and every span's
own cost.

Projection now lives in the shared reads, resolved through the one helper the
v1 and internal log paths already read.

* fix(permission-groups): let the fail-closed api-keys policy heal

`permissionPolicyReady` withholds the create button until the permission
config read succeeds, which is right — offering a key type the server would
refuse is the failure worth avoiding. But the app's query defaults give an
errored read no way back: retry once on the web, never on remount, and no
focus refetch outside the desktop app. One transient failure disabled the
button for the rest of the session with nothing to say why.

Raises the retry count on this query and lets a remount retry, stopping
short of retrying a 4xx, which asking again cannot change. The comment at
the call site claimed a personal scope that does not exist — the component
ships only as scope='combined' under the workspace settings route — so it
now says what is actually true about the `!workspaceId` arm.

* fix(v1): run the personal-key group check behind the role check

`resolveWorkspaceScope` asked `personal_api_key.use` inline, and
`resolveWorkspaceAccess` calls it before `getUserEntityPermissions` — so a
caller with no reach into the workspace at all was answered with a refusal
naming how the organization had configured one of its cohorts, instead of
the concealed role failure. `resolveCapabilityRefusal` states the invariant
the other way round: never call a group key before the workspace role check.

Splits the group half out of the scope check. The workspace COLUMN stays
early — it names no group, needs no query, and is the answer whatever the
role turns out to be, which is the split `authorizeWorkspaceOperation`
makes. The group half answers only after the role, and takes the id whose
role a caller already verified rather than a boolean, so a caller that
checked some other subject cannot vouch for this one; `checkWorkspaceScope`
passes none and resolves the role itself, since the table routes' own role
check runs later in `checkAccess` and gates the module, not the key kind.

* fix(audits): close the user-scope gap in check:capability-subject

Assertion B lists the modules a v1 route may not import, and
`user-scope.server` was missing from it. That module answers a capability
for a caller who names no workspace by falling back to the organization's
default group, and takes a bare `userId` like every other sink — so a route
reaching for `isCapabilityWithheldForUser` directly was one property access
away from the key creator with nothing in between.

Splits the script's procedural body into `auditSource` and
`auditMiddlewareExport` so the assertions can be probed without a tree on
disk, and adds the probe suite (wired into `bun run test`, which
check:script-tests requires).

Also records on `parseEnforcedAnnotations` why its bare scan is left as it
is: both cheap shapes that would require a gate beneath an annotation were
measured against the tree and each misses seven live sites, all of the same
kind — an annotation over a call to a domain helper that enforces the group
elsewhere.

* test(logs): cover the run-detail, snapshot and @log-mention projections

Each door gets: hidden-cost member withheld spend, hidden-spans member withheld
execution payloads, ungoverned member reads whole, and the subjectless caller
reachable on that door reads whole without ever resolving a group.

* feat(permission-groups): declare capabilities on the operations staging added

The merge brought three new operations, which the required capability field
and the enforcement audit both refused until answered: files.search_content
takes files.use like every sibling; the paused-execution read is exempt (its
detail is pause points and resume state, never the fields logs.cost or
logs.trace_spans withhold); SSO JIT admission runs before any membership
exists, so no group can govern it yet.

* feat(permission-groups): declare a capability on the unified selector operation

selectors.execute is exempt with its reason on record: credential access is
authorized per credential, and per-integration denial is the parameterized
allowedIntegrations key, enforced at workflow save and execution. Gating the
picker itself needs a selector-key-to-block-type mapping — a follow-up, not
something to claim silently here.

* fix(permission-groups): gate copilot.use on the workspace a chat lands in

Three cubic findings on the copilot surfaces.

/api/v2/chat is a raw special route: `admitV2Request` authenticates and
rate-limits but never authorizes, so the `copilot.use` capability declared
on `chat.send` was never applied there. Gate it explicitly after workspace
access — read off the operation, so the route and the funnel cannot name
different capabilities — and project it as a 403 carrying
PERMISSION_GROUP_CAPABILITY_BLOCKED.

The unified chat send gated on `body.workspaceId`, but `resolveBranch`
resolves a `workflowId` to the workflow's own workspace and ignores any
`workspaceId` beside it. Sending only `workflowId` skipped the gate; pairing
it with an unrestricted workspace aimed the gate elsewhere. Move the check
after branch resolution and gate on the workspace the turn actually lands
in — still ahead of the chat, the stream lock and the run, with the send
claim released by the handler's `finally`.

The tool-permission endpoint claims the decision row before reading
`copilot.tool_auto_approval`. A rejected lookup answered 500 with the
decision unpublished, and the retry lands on the already-answered branch,
which does not republish — leaving the turn to wait out its permission
timeout. Read a failed lookup as withheld: fail-closed for the capability,
and the human's one-time answer still reaches the waiter.

Also records why the per-turn `autoAllowPermitted` snapshot is not re-read
mid-turn: `resolvePermissionGroupConfig` memoizes per request scope, so a
re-read would answer with the value the turn opened with.

* fix(permission-groups): close reactivation and creation gaps in the capability gates

- POST /api/webhooks gated creation only, but its upsert always writes
  `isActive: true`, so re-saving a dormant webhook reactivated it under a group
  with `disableWebhookTriggers`. Gate creation and reactivation, matching the
  transition `PATCH /api/webhooks/[id]` already refuses; re-saving an
  already-active webhook stays open.
- The two raw table import routes gated `tables.use`, so a group setting only
  `disableTableCreation` could still create a table by importing one. Gate
  `tables.create`, whose rule is denied by `disableTableCreation` OR
  `hideTablesTab` and so loses nothing.
- `completeTableImportUseCase` authorized `tables.use` only, so an upload
  started before the group withheld creation still landed a table when it
  completed. Re-assert `tables.create` under the claimed session when the
  target is `new`.
- `lockWorkspaceCreationContext` revalidated membership and entitlement but not
  `workspace.create`, so a create in flight when the group changed still
  committed. Re-read it under the lock and refuse with a distinct
  `WorkspaceCreationCapabilityWithheldError`, which the create route answers
  403 rather than 409.

* fix(permission-groups): exempt retired entry points and normalize allowlist ids

A legacy starter block (`starter`, `manual_trigger`, `api_trigger`,
`chat_trigger`) resolves to `start_trigger`, which the Access Control editor
never offers as an allowlist row, so every active allowlist refused every saved
workflow still carrying one. Exempt a retired block whose successor is the
universal entry point.

The policy list was compared raw against a successor-resolved block type, so a
deployment whose `ALLOWED_INTEGRATIONS` names a retired id — the hand-written
`slack` — refused every `slack_v2` in it. `toAccessControlAllowlist`
normalizes the policy side the same way, and replaces
`toAllowedIntegrationTypes` at every comparison site.

* fix(workflows): judge an import's blocks against the caller's own group

A workspace API key has no user, so no permission group governs it, but the
import pipeline read the allowlist from its attribution field — the billing
owner on the application path, the key's creator on v1. Either is a bystander
whose group would refuse an import `workflows.import` allows, and would break a
shared key the moment that person's group changed.

`capabilityUserId` carries the governed person separately from the attribution
field, from the one funnel rule (`capabilityGovernedPrincipalUserId`, which
mirrors `authorizeWorkspaceOperation` including its executor exemption).

* fix(credentials): assert the personal-credential gate on the branch that is personal

A connection operation takes a target, not a scope: `providerId` connects a
personal account, `credentialId` re-authorizes a credential the workspace
already holds. Declaring `credentials.personal` on the operation refused both,
so `disablePersonalCredentials` — which leaves members "only workspace-shared
ones" — withheld the shared credentials it exists to mandate. And because an
operation declares one capability, it replaced `integrations.manage`: a group
that hid the whole Integrations module could still connect.

The operations now declare `integrations.manage` like every other credential
operation, and the narrower key is asserted on the connect branch — the same
arrangement `credentials.create` already uses for its personal types.

* fix(billing): apply the group's personal-key refusal to workspace billing reads

The billing reads resolve their own workspace scope instead of running through
`authorizeWorkspaceOperation`, and reproduced only the workspace column — so a
personal key whose group sets `disablePersonalApiKeys` still read a workspace's
plan, status and ledger through v2. `requirePersonalApiKeysAllowed` is now
shared with the funnel rather than copied, and runs where the funnel runs it:
after the role check.

Also gates the OAuth credentials route on the credential's own workspace
unconditionally. The asserted `workspaceId` is the caller's to choose, so
gating on it alone let a caller who reaches two workspaces pair an ungoverned
one with a credential from a workspace whose group withholds Integrations.

* fix(permission-groups): close the spend leaks the log projections left open

`withheldSpendData` stripped the spans and block executions but not the run's
own roll-up. Every completed run carries `tokens` and `models` at the root of
`execution_data`, and `models` is the per-model DOLLAR breakdown — finer-grained
than the total the projection blanks — so a member whose group withholds spend
read the itemization next to a nulled figure. Dropped with `cost`, which older
rows carry inline.

The same class one level down: `providerTiming.segments[*]` carry their own
`cost` and `tokens`, the itemization behind a span's roll-up. Neither
`stripSpanCosts` (which is what stands between a joined cross-workspace child
run and the parent's reader) nor the display projection's `withoutSpend` reached
them.

`?minCost=` reached the v1 contract as `''`, `Number('')` is `0`, and the
parameter arrived as a real zero — which read as a cost SELECTOR and refused an
innocent request from a withheld member, while `maxCost=` silently narrowed the
page to free runs. `optionalNumberQuerySchema` normalizes an empty value to
omitted and preserves an explicit `0`.

`checkWorkspaceScope` asked `personal_api_key.use` after verifying the caller's
role at `read`, whatever the route went on to demand. The funnel asks it after
`requireCurrentHumanRole(operation.minimumRole)`, so a read-only member on a
write route is refused on role there; here the same person was told instead how
their organization configured personal keys. The level is now the route's own.
That refusal also carries its detail code, which is what separates it from the
workspace-column refusal it shares a sentence with.

The table-export and logs-stats refusals now render through
`capabilityRefusalResponse`, so every capability 403 carries the same code.

`listPublicLogs` materialized and secret-projected a whole page of payloads it
was about to discard, when the group withholding execution detail had already
turned both render flags off. It now skips the column read entirely.

The checkpoint-revert route discarded the state write's status and reported
every refusal as a 500, so a member whose group withholds a block type in the
checkpoint was told the revert had crashed.

* fix(permission-groups): align the resource-level capability sites with the funnel

- workspace-files: the bulk-download assertion read its subject straight off the
  principal, re-applying to a delegated executor exactly the capability
  `authorizeWorkspaceOperation` exempts a subject-bearing executor from. It now
  reads the funnel's own rule, and passes the organization the context loaded.
- enrichments: `userId` is required and explicitly nullable. Omitting it
  skipped the per-tool `deniedTools` gate silently; the one genuinely actorless
  caller — a system-triggered table dispatch — now states that rather than
  falling into it by leaving a field off.
- apply-workflow-operations: pass the loaded `workspaceOrganizationId` instead
  of `undefined`, which re-queried the workspace for every edit batch.

* fix(access-control): correct three affordance and documentation defects

- An empty allow-list denies every option, but the multi-select's default empty
  label reads 'All' — the opposite of what the server enforces.
- The policy-read retry predicate excluded only 4xx, so a 2xx body that fails
  contract validation (an `ApiClientError` carrying status 200) was asked three
  more times for the same deterministic answer.
- Two comments stated the opposite of the code: `audit_logs.list` declares
  `capability: 'none'` rather than omitting the field, and `ApiKeys` does ship
  outside the workspace panel — the account plane renders it as
  `scope='personal'`, which is what the `!workspaceId` arm covers.
- The skill's leak grep excluded the directory holding `capabilities.ts`,
  hiding the authoritative `CAPABILITY_RULES`/`deniedBy` reads it asks for.

* fix(audits): close two renames that made the graph and subject audits no-ops

check-application-graph walked past `import '@/lib/x'` entirely — its pattern
required a `from` — so the heaviest edge of all, a module loaded purely to run,
was invisible to the guard. The clause pattern is also narrowed to non-quote
characters so it cannot swallow a preceding side-effect import and report one
edge for two.

check-capability-subject followed neither rename that defeats a source-text
match: an import alias left the sink's own name on the import line and nowhere
else, and a local `capabilityGovernedUserId` made every governed subject
unverifiable. Aliases are folded into the sink table; a local of that name is
refused.

* fix(enrichments): state the actorless dispatch's null subject explicitly

* test(v1): teach the import suite's middleware mock the governed-subject helper

The import route now resolves its capability subject through
capabilityGovernedUserId; a module-factory mock omitting a newly-used export
yields undefined and a 500 on every test. The stub mirrors the real helper's
keyType branch — only a personal key carries a governed subject.

* feat(permission-groups): declare a capability on the organization billing summary read

The merge brought one new operation; the required field refused it until
answered. It is an organization-admin surface — admins and owners sit above
every group — so it is exempt with its reason on record, and its factory now
carries the same definition-time guard the other operation factories do.

* fix(permission-groups): gate selector execution on allowedIntegrations, apply the personal-key policy on v2 chat

Three cubic findings on the enforcement PR.

`POST /api/selectors/execute` reaches a provider's API with the caller's
credential, so it is a use of the integration and not a neutral picker. The
authorization funnel cannot apply `allowedIntegrations` because it never sees
which integration a selector key stands for, so the decision is asserted from
the use case, after credential binding and ahead of the provider call. The
integration identity comes from the selector attachment's declared OAuth
services, narrowed by the resolved credential's provider id so a two-service
selector is judged as the half the caller actually reaches.

`/api/v2/chat` only ever runs for a personal API key, and `admitV2Request`
authenticates without authorizing, so neither half of the funnel's personal-key
policy applied there. Both now run after the workspace access check, the group
half through the shared `requirePersonalApiKeysAllowed`.

The raw copilot chat route's `copilot.use` refusal now renders through
`capabilityRefusalResponse`, so it carries the same detail code as every other
capability refusal.

* fix(permission-groups): key the table-import capability re-check on the governed subject

`resolvePrincipalSubjectUserId` answers with the subject of an executor
delegation too, so the create- and completion-time `tables.create` assertions
re-applied a capability the authorization funnel deliberately exempts runs
from. `capabilityGovernedPrincipalUserId` is the canonical statement of that
rule: null for an executor delegation, still the subject for a copilot one,
which is the intended asymmetry.

* fix(permission-groups): gate table enrichments on the acting person, not the billing owner

`triggeredByUserId` is an attribution: for a workspace-API-key run it names
the workspace billed account, so passing it as the enrichment gate ran a
bystander's tool denylist against an actorless request — failing cells nobody
meant to govern, and skipping the denylist for whoever actually triggered one.

The dispatch now carries the governed subject alongside the trigger actor and
the worker gates on that. `insertDispatch` defaults it to the trigger actor so
producers that cannot tell an acting person from an attribution fallback keep
today's behavior; the use cases holding a principal pass it explicitly, null
included. The column is nullable and purely additive — existing rows read
null, which is the answer those runs already get.

* fix(v1): attribute a workspace-key table delete to the system actor

A workspace key names no human, so `rateLimit.userId` is the key's creator and
audit/analytics recorded the deletion against a bystander.
`resolveWorkspaceRequestActor` is the established primitive — the row routes on
this same table already use it — and substitutes the billed account as the
explicit system actor while keeping a personal key's owner.

* fix(permission-groups): carry the capability detail code on the workspace.create race refusal

The insert-time refusal rendered a bare message, so a client could not tell a
permission-group block from any other 403. `capabilityRefusalResponse` is the
one builder for that body and reads the detail code off the rule.

* fix(permission-groups): canonicalize each integration policy before intersecting them

`intersectIntegrationAllowlists` case-folds but does not successor-resolve, so
a group naming `slack` and an env allowlist naming `slack_v2` intersected to
nothing textually and the hook hid an integration both policies allow.
Resolving each side first puts them in one vocabulary before the intersection.

* docs(skills): chain the permission-group verification commands after one cd

Run as one block, the first `cd apps/sim` persisted and the second command
targeted `apps/sim/apps/sim`, so Vitest never ran.

* fix(access-control): normalize block-type casing before resolving its successor

Registry keys are lowercase, so `getBlock('Slack')` misses and the successor
lookup answers `Slack` — compared as `slack` against an allowlist holding
`slack_v2`, refusing a block both policies allow. `blockType` reaches here from
persisted workflow state and from an agent block's `tool.type`, neither
case-normalized upstream; the pre-existing check lowercased it for this reason.

* perf(logs): resolve the permission-group config only for cost-selective stats queries

The lookup re-reads workspace and organization/group state on every stats
request, including unfiltered dashboard loads that can never be refused.
Gating it behind `logQuerySelectsCost` is behavior-identical — the refusal
already required both conditions.

* refactor(permission-groups): name the canonicalize-then-intersect rule once

The hook built the resolved intersection inline, where the ordering that makes
it correct was invisible and untestable. `intersectAccessControlAllowlists`
states it in the module that owns the vocabulary, next to the canonicalizer it
composes, and is pinned against the retired-id-versus-successor case.

* test(permission-groups): pin block-type casing and the stats config-lookup gate

Both fail against the prior implementations: the casing case resolves before
folding and refuses a permitted successor, and the stats case consults the
group on a read that can never be refused.

* docs(db): state the deploy-window semantics of the governed-subject column honestly

* fix(permission-groups): require the governed subject on every table dispatch producer

Making `capabilityGovernedUserId` optional on `insertDispatch` let it fall back
to `triggeredByUserId` — the attribution that names the workspace billed
account when the credential names no human — for any producer that had not been
taught the distinction. That is the bystander substitution the column exists to
remove, reintroduced by omission.

The field is now required with an explicit `null` (the shape the secret-
provenance write already uses) on `insertDispatch`, `runWorkflowColumn`, and
every row-write and group-write payload that can auto-fire one, so a producer
cannot land the wrong subject by forgetting the field. Surfaces that hold a
principal thread `capabilityGovernedPrincipalUserId`; v1 routes thread the
`keyType`-derived helper; auto-fire and internal state patches pass `null`.

* fix(permission-groups): stop a deleted account's table runs instead of un-gating them

`capability_governed_user_id` is `ON DELETE SET NULL`, so deleting the governed
user turned every dispatch they still had queued actorless — and the worker reads
an actorless dispatch as "no per-tool gate applies". The two cases are
indistinguishable at read time, and the in-process dispatcher has no time
ceiling, so a surviving dispatch could keep running ungated for as long as its
scope took.

`deleteUserAccount` now cancels the account's pending/dispatching rows in the
same transaction that removes the user, so the nulled subject is only ever
observed on a terminal row. `RESTRICT` was the alternative and is worse: it
blocks account deletion behind background work, the way the billed-account
foreign key already does.

* test(permission-groups): pin the governed subject end to end

Four seams, each mutation-verified against the fallback it replaces:
`insertDispatch` and `runWorkflowColumn` store and forward the subject
verbatim (an explicit null survives a non-null attribution); the enrichment cell
gates on the payload subject, so a workspace-key dispatch runs ungated and a
pre-0315-shaped payload — subject null, attribution intact — stays ungated
rather than reconstructing a gate from the payer; and `deleteUserAccount`
cancels the account's non-terminal dispatches ahead of the user delete.

The 0315 backfill itself is SQL and is covered by review, not by a test.

* docs(skills): fix two checklist semantics bugs in the permission-group item skill

The featureExtras rule falsely flagged top-level lists — allowedIntegrations,
allowedModelProviders, deniedModels and deniedTools render from dedicated
Providers and Blocks sections, not from featureExtras, so the check reported
missing admin UI for every one of them. Restrict it to nested platform-feature
controls and point the reader at the sections those lists actually use.

The picker rule applied allowlist semantics to denylists. Refusing an empty
selection and collapsing a full one back to null are allowlist behaviours; a
denylist must let an admin clear every entry, which is how it denies nothing.

* feat(permission-groups): generate the access-control successor map from the block registry

The successor question — which block type is an allowlist decision about this
id really made against — was answerable only through getBlock, and
scripts/check-application-graph.ts forbids lib/permission-groups/ from
importing blocks/: the authorization funnel would pull every block definition
into every surface that authorizes anything. So mergeEnvAllowlist intersected
the group allowlist with ALLOWED_INTEGRATIONS textually.

Project the registry into a checked-in Record<string, string> instead. Entries
are flattened to the terminal successor, reproducing the transitive walk the
runtime performed and both of its stopping rules: a cycle stops at the last id
visited, and an edge naming an unregistered block is not followed. The
generator refuses to emit a map that is not closed, and check:block-successors
fails when the map drifts from the registry in either direction.

* fix(permission-groups): canonicalize both policy layers before intersecting them

The group allowlist and ALLOWED_INTEGRATIONS are written independently — the
editor only offers current ids, the env list is hand-written against whatever
ids its author knew — so they routinely name the same integration by different
vintages. Intersecting them textually made slack against slack_v2 disjoint, so
the merged allowlist was empty and every consumer refused an integration both
policies allow: the client hook, the server catalog, the block gate and the new
selector gate each disagreed with the others depending on where in the pipeline
the successor resolution happened.

Move resolveAccessControlBlockType, toAccessControlAllowlist and the two
intersect helpers into integration-allowlist.ts, backed by the generated
successor map, so the module under the authorization funnel can canonicalize
without reaching the block registry. block-access.ts re-exports them and keeps
only the exemption rule, which genuinely needs hideFromToolbar.

intersectIntegrationAllowlists now resolves each side before intersecting, so
every caller of the merged config gets one vocabulary. The copilot surfaces
that tested a raw block id against that list now resolve the checked side too,
which is what the block path always did.

* fix(selectors): gate a selector on the resource it reaches, not the credentials it accepts

serviceIds names which credentials a selector accepts, which is a different
question from which resource it reads, and the two diverge whenever one
provider API is reachable with several sibling connections. google.drive
accepts a Drive, Docs, Sheets or Forms credential because all four carry Drive
scope, and sharepoint.sites accepts a SharePoint or an Excel one. The gate
asked whether ANY accepted service was allowed, so a group that permitted
google_sheets_v2 and excluded google_drive could still read Drive through
google.drive.

The declaration now names its own resource, and that is what the allowlist
judges. resourceServiceId is required whenever serviceIds names more than one
service and must be one of them; manifest.test.ts pins both, so a new
multi-service selector cannot reintroduce the fan-out. The bound credential's
provider id is no longer consulted: it describes the key, not the API the
selector calls, and narrowing by it is what gated Drive reads on whether a
Sheets connection was permitted.

* refactor(copilot): read the chat capability off its operation declaration

The raw chat handler restated copilot.use in both the assertion and the
refusal, so changing chatOperations.send's policy would leave the route
over- or under-gated and answering the wrong refusal code. Read the
declaration once instead, including its 'none' case, where a declarative
surface asserts nothing and so does this.

* fix(api): answer an unresolvable workspace actor and a denied workspace creation with controlled bodies

resolveWorkspaceRequestActor returns null for a reachable request about an
unreachable workspace: an authenticated workspace key whose workspace has been
archived has no billed account to stand in as its system actor. All five v1
table call sites threw on that, which the routes' catch-all reported as a
generic 500. requireWorkspaceRequestActor projects it onto the 400 those routes
already use for a workspace mismatch, from one place rather than five copies.

POST /api/workspaces refused a permission-group denial with two different
bodies. The revocation race the insert detects carried
details.code PERMISSION_GROUP_CAPABILITY_BLOCKED; the far more common preflight
denial answered a bare { error }, so a client keying off the code saw the
capability refusal only in the rarer case. Both now render through
capabilityRefusalResponse.

* test(v1): pin the workspace-actor projection

requireWorkspaceRequestActor is the only place the 'no billed account for this
workspace' case is turned into a response, and the table route tests mock the
middleware wholesale, so the projection itself needs its own pin.

* fix(permission-groups): read the successor map by its own keys only

* fix(table): govern CSV-import auto-fire by the person the route already gated

A synchronous CSV import passed an explicit null governed subject, so the
workflow and enrichment cells the appended rows auto-fire ran with no
per-tool gate — including when a session member with a restricting
permission group started the import. The subject now comes from the same
`TableAccessPrincipal` `checkAccess` gated `tables.use` against, so a
route cannot gate one subject and dispatch under another.

* fix(access-control): keep superseded blocks out of the editor's allowlist universe

* fix(table): carry the acting person into the backfill's downstream cascade

An output backfill writes cells that satisfy downstream groups' deps, and
`batchUpdateRows` starts those groups. The write passed an explicit null
governed subject, so a cascade started by a person's schema change ran its
tools ungated. The subject now rides the backfill payload beside
`actorUserId` — a billing attribution that names the workspace billed
account when the change carried no human.

* fix(copilot): capture prompt telemetry only once the turn is allowed to run

* fix(table): stop a queued cell whose dispatch was cancelled

Cancelling a dispatch row stops the next window, not the one already
queued — the dispatcher blocks on a whole window at a time. Account
deletion cancels the departing account's dispatches and then deletes the
user row, so those in-flight cells kept invoking tools and writing results
under a subject that no longer existed. The cell now reads its owning
dispatch before executing and terminalizes itself as cancelled; there is
no per-cell alternative, since table_row_executions carries no dispatch
column.

* fix(selectors): gate raw-context and api-key selectors on their integration

* fix(table): run a drained pre-stamp under the subject that stamped it

A dispatcher pre-stamp outlives the worker that wrote it: a cell task that
finds the row's cascade lock held bails, and the lock owner drains the
marker under its own payload. With two dispatches overlapping on one row
that ran another dispatch's request against the wrong person's tool
denylist — or, when the owner was an actorless auto-fire, against none.
The marker now carries its governed subject and the drain reads it back;
0316 also adds the partial index account deletion's cancel filter needs
and repeats 0315's backfill to close its rolling-deploy window.

* test(table): pin the governed subject at the import route, the deletion filter, and the mock

The shared schemaMock lacked `capability_governed_user_id`, so the
account-deletion cancellation ran its filter against `undefined` and the
test could not tell the governed subject from the billing attribution it
replaced. Adds both columns to the mock and asserts the filter names the
subject and only the two live statuses.

* Merge remote-tracking branch 'origin/staging' into feat/permission-groups-coverage

The block-successors map regenerates with one new entry from staging's
table sunset; the check that failed in CI compares against the merge ref,
which is exactly the drift it exists to catch.

* fix(db): make 0316's pre-COMMIT section replay-safe

The file ends in post-COMMIT CONCURRENTLY steps, so a failed concurrent build replays it from the top. The column add, the FK, and the VALIDATE now all survive a second run.

* fix(table): require the governed subject on the add-output payload

An omitted subject and a deliberately actorless one read identically at the call site, and the omitted form ran the backfill's downstream cells with no gate. Matches the add/update group payloads.

* fix(table): derive the CSV import governed subject from the auth type

Both import routes accept an internal JWT, whose user id is the run's actor. Reading a governed subject off it gated and dispatched under a bystander's permission group; an executor call now names nobody.

* test(background): warm the cascade loop's dynamic imports outside per-test budgets

Under a loaded parallel run the loop's dynamic imports can take whole
seconds; one test timed out mid-loop and its continuation spilled calls
into the next, which is what made these two files flaky in 2 of 4 full
runs. A beforeAll pays the import cost once, outside any test's budget.

* test(background): pay the cascade loop's whole lazy-import graph in beforeAll

The first loop invocation lazily imports the executor graph; under a loaded
parallel run that cost blew the first test's budget, and a timed-out test's
continuation spilled calls into its successors — the flake in 2 of 4 full
runs. Warming every dynamic import (executor included) and stubbing the
pacing RateLimiter moves the cost outside test budgets; each test now runs
in milliseconds.

* refactor(selectors): one home for the selector integration-identity rules

selectorResourceServiceIds had no caller outside its own module, and its
TSDoc restated the resource-vs-credential rule that SelectorCredentialPolicy
already owns; the integrationBlockTypes rationale was spelled out a third
time on selectorIntegrationBlockTypes and a fourth on the assertion. Point
at the declarations instead.

The selectors.execute permission-group-exempt annotation still described the
credential-narrowing design that was removed: the gate judges the selector's
own resource, deliberately not the bound credential's provider.

* refactor(permission-groups): drop block-access's re-export of the moved allowlist helpers

integration-allowlist.ts was split out of block-access.ts, and the
re-export kept behind for the move left consumers importing the same three
pure functions from two different modules. block-access.ts imports
@/blocks/registry, so the re-export also made a registry-free helper look
like it came from the registry-bearing module. Every consumer now imports
from the source, matching what use-permission-config.ts already did.

Also: capability-error.ts still claimed one detail code covered every
capability. Four of the thirty-five carry a remedy-specific code, which is
why the constructor takes one.

* docs(permission-groups): one home for the capability-governed subject rule

capabilityGovernedPrincipalUserId already declares itself THE statement of
which principals a permission group governs, but five rounds each restated
the workspace-key-creator reasoning in full at their own helper. Each site
now keeps only what is specific to its input type — TableAccessPrincipal's
type-system argument, capabilityGovernedAuthUserId's internal-JWT case,
v1's keyType signal and its audit-script coupling — and links the rule.

No decision changes: workspace key and executor stay null, session,
personal key and Copilot delegation stay governed.

* refactor(scripts): tidy the permission-group audits

check-permission-group-enforcement: the header listed assertions A-E while
the body has an F (every exported registry member was read) documented only
inline; lineAt was defined twice inside the file; the annotation count in
parseEnforcedAnnotations' measurement note had drifted from 50-odd to 70-odd.

check-capability-subject: the per-file sink table was named sinks_.

generate-block-successors: the header restated flattenSuccessors' walk and
stopping rules verbatim.

322 operations / 35 capabilities and 5 governed v1 subjects unchanged.

* docs(skills): re-audit permission-group skills against current code

Fixes drift (operation count 315 -> 322, workspace-authorization.ts:171 ->
:204, stale capabilityRefusalResponse exemplars, a warning about a deleted
assertOrganizationCapability) and adds the two mechanisms an author or
auditor now gets wrong without: the governed-subject helper family with the
required `string | null` producer rule, and canonical-before-intersection
integration allowlist semantics over the generated successor map.

* docs(table): one home for the capability-governed payload rule

The same six-line paragraph — the gate subject is not the attribution field
beside it, and it is required with an explicit null — was restated on
fourteen payload fields across types.ts, dispatcher.ts, workflow-columns.ts,
orchestration/import.ts, application/groups.ts and workflow-groups/service.ts,
including two byte-identical copies in one file. Three of them claimed to be
the canonical statement.

InsertRowData.capabilityGovernedUserId now carries the whole rule, absorbing
insertDispatch's sharper why-required argument, and links onward to
capabilityGovernedPrincipalUserId for which principals a group governs. The
rest keep their site-specific sentence and point at it, matching the
{@link InsertRowData.secretProvenance} convention already in the file.

* test(harness): share the v1 personal/workspace key credential factories

The three v1 suites that steer a permission group through the public API
— the module gate, the tables gate, and the logs projection — each carried
byte-identical `personalKey()` and `workspaceKey()` builders. The workspace
one encodes the trap all three exist to pin (the key reports its CREATOR's
user id), so it belongs beside the other v1 admission mocks rather than in
three copies that can drift apart.

`governedBy()` stays per-file: moving it would mean injecting
DEFAULT_PERMISSION_GROUP_CONFIG from apps/sim, which packages/testing may
not import, and the call site would grow past the six lines it saves.

* refactor(permission-groups): use the assertions module's own refusal re-export

capability-assertions.ts re-exports capabilityRefusal so a route that gates
inline reaches the sentence and the assertion through one module. The one
route that gates inline against a workspace capability was importing the two
halves from two modules instead.

* test(workflows): keep one home for readWorkflowRun selector resolution

Two rounds pinned the same gate at the same altitude under different
names. `workflow-runs.test.ts` had 'refuses a selector that is not headed
by a block id' and 'allows a block id that produced no output on this
run'; `read-workflow-run.test.ts` has the same two directions plus the two
this pair never covered — a run whose output projection is not recorded
yet, which is the regression that motivated the check.

Keep the four-direction suite, and carry the only assertion the deleted
pair made that it did not: the semantic `code: 'validation'`, folded onto
the message assertion so both survive.

* test(core): one describe for the defineWorkspaceOperation capability guard

Two files carried a `defineWorkspaceOperation capability policy` describe
under the same name — half the guard's directions in the builder's own
suite, half in `workspace-authorization.test.ts`, whose subject is
`authorizeWorkspaceOperation` rather than the builder. Move the
parameterized and opt-out cases onto the builder suite so all four
directions read together.

* test(table): warm the pre-stamp suite's lazy cell-task import

Its one test measured 2952ms in isolation and carried a 20s budget to
absorb it. The cost is not the pre-stamp: `buildEnqueueItems` resolves the
cell task with a dynamic import of `@/background/workflow-column-execution`,
which no mock in this file intercepts, and paying that inside a test's own
budget is the shape that already made two background suites flaky.

Warm it in `beforeAll` like those two, and drop the inflated budget: the
test now runs in 3ms and fits the default.

* refactor(auth): give the AuthResult capability derivation one home

capabilityGovernedAuthUserId moves to lib/auth/hybrid, where AuthResult and
AuthType live — both routes that shared it from table utils and the workflows
executions route that had spelled out a verbatim twin (importing the table
graph for six lines was the only reason it existed) now read one function.
The global hybrid mock carries the real derivation rather than a vi.fn():
it is a pure branch on fields tests already control, and a stub returning
undefined would silently un-gate every consumer.

* chore(permission-groups): apply the surviving comment-pass findings

The dedicated simplification pass covered most of the 25 findings; what
survived was narrative history in two middleware TSDoc blocks (the live rule
stays, the story goes), one drifted count, and one projection-rationale
restatement now a link.

* fix(db): give 0315/0316 real transaction boundaries under the batching runner

* audit(capability-subject): refuse a fallback welded to the governed subject

* fix(logs): withhold a run's file list on the same terms as its output

* fix(permission-groups): fail closed when the entitlement read fails

* test(permission-groups): cover the fail-closed entitlement policy

* docs(logs): state why logs.export has no admin exemption, and pin it

* audit(application-graph): report a deferred import into a forbidden tree

* fix(billing): gate the account-scoped read on personal_api_key.use

* audit(permission-groups): refuse a factory that admits a Partial operation override

* docs(table): state the gate-vs-dispatch subject model once

* feat(access-control): mark organization-scoped keys and render them inert off the default group

* fix(table): carry the governed subject across a cell pause

A workflow group that pauses mid-run resumes through the resume worker,
whose payload carries the resumer and the payer but no gate: the row
marker it was stamped with is long claimed, and no dispatch is in scope.
The post-resume cascade therefore ran with a null subject, so a tool the
requester's permission group denies executed once a wait block had been
crossed.

The pause snapshot is `paused_executions.metadata`, a jsonb document, so
the subject rides it with no schema change; a stash written before the
field existed reads back as the ungated run it was. `CellResumeContext`
and `WorkflowGroupCellPayload` both take it as required, matching every
sibling in `@/lib/table/types` — an omitted key and a deliberate `null`
mean the same thing to the gate, so the compiler is what makes a call
site say which one it means.

* refactor(chat): take the v2 refusal detail code off the capability rule

* fix(workflows): enforce the block allowlist on the shared persistence primitive

findWithheldBlockType ran at two of the three doors that store a whole
graph. PUT /api/v2/workflows/{id}/state reached
replaceWorkflowNormalizedState directly and the Copilot materialize
import reached saveWorkflowToNormalizedTables directly, so an
organization that excluded an integration was refused in the canvas, the
internal save and the import and still had it stored through either.

The check now lives on saveWorkflowToNormalizedTables, the one primitive
every normalized-table write funnels through, and every caller states
whose grants judge it through a required governance argument. A null
subject is how an actorless write declares itself -- an executor revert,
a fork copy, workspace creation, the platform-admin imports -- so a run
persisting its own graph is not blocked by the triggering member's group.

workflows.state.replace's exemption cited the persist-time guard as its
justification while not being covered by it; it now is.

* fix(table): gate the workflow half of a cell on its governed subject, not its payer

`ExecutionMetadata.userId` is the run's billing/rate actor and its
credential subject, and the permission gate read it as the person too. On
a workspace-API-key table run that id is the workspace's billing owner —
a bystander — so the tool denylist ran against someone who did not ask
and skipped the one belonging to whoever did. The enrichment half of this
same worker was already fixed; this closes the workflow half.

The two ids are now separate: `capabilityGovernedUserId` on the run
metadata is the gate, `userId` stays the meter and the credential
subject, untouched. It is tri-state — absent means the surface has
exactly one person and the actor remains the subject, so every other
trigger is unchanged; a declared `null` is the actorless run and applies
no group gate. Resolving it in `assertPermissionsAllowed` puts the
decision in one place for every gate a run reaches, and the metadata is
spread onto the pause snapshot, so it survives a resume.

* fix(invitations): gate resend on invitations.send

* fix(api-keys): gate the workspace key rename on api_keys.manage

* fix(users): stop the deleted account's pre-stamped cell markers too

Account deletion cancelled the departing account's `table_run_dispatches`
rows and stopped there. The cells those dispatches had already pre-stamped
on `table_row_executions` survived: a marker is drained by whichever
worker holds the row's cascade lock, and that worker's dispatch-cancel
guard consults its OWN dispatch id, so an unrelated still-active sibling
dispatch drained the deleted person's marker. By then the subject
reference has been `SET NULL`, which reads exactly like a legitimately
actorless request — the drain ran with no per-tool gate at all.

Terminalizes those markers with the canonical cancel state, in the same
transaction and ahead of the user delete, scoped to the subject and to
`pending`/`queued` — the states a marker sits in before a worker claims
it. Every drain path already refuses a cancelled cell.

* refactor(logs): require the projection flags on the shared log reads

* fix(mcp): gate every raw MCP management route on its declared capability

deploy.mcp was enforced at one of the thirteen routes behind
validateMcpAuth -- the workflow-server create handler, which grew an
inline check. Its siblings had none, so an organization setting
hideDeployMcp got a 403 from the v2 twin and from create, while POST
.../tools still published a workflow over MCP and PATCH isPublic:true
still stripped authentication from everything that server publishes.

withMcpAuth now takes the capability as a required argument and applies
it after the role check, with capabilityGovernedAuthUserId as the
subject so the executor's internal JWT passes ungated the way every
other surface treats it. Each route declares the capability its
mcpServerOperations twin already declares.

* docs(permission-groups): record the data-drain policy and make the cost hint honest

Data drains are an organization-admin instrument, deliberately above member
permission groups like the audit-log surface — the reader of a drained
record is the organization, not a member. Recorded on the drain access gate
so the next auditor finds a decision, not a gap. The hideCostInfo hint no
longer promises that ALL exports omit spend.

* test(v1): pin the persistence primitive's governance argument on import

The primitive gained a required governance parameter; these assertions pinned
the old arity. Asserting the value rather than anything() also pins that a
keyType-less v1 credential imports ungoverned, matching the real helper.

* fix(permission-groups): render the raw inbox and table export refusals through the shared builder

* fix(operations): carve the principal-wide capability out of the operation-declarable union

* fix(contracts): treat a null numeric query value as omitted, not zero

* docs(v1): name the explicit capability declaration in the exemption comments

* fix(v1/logs): keep the group refusal's detail, project period spend, skip withheld materialization

* fix(api-keys): seed the create-key form when the modal opens, not at page mount

* fix(capabilities): gate the raw table and webhook routes on the governed subject

An internal executor JWT carries the run actor's id, so reading auth.userId
bare at a capability gate applies that person's permission group to a
delegation the executor exemption deliberately passes ungated. Derive the
subject with capabilityGovernedAuthUserId and skip when it names nobody.

* fix(copilot): read a failed auto-approval lookup as withheld, not as a turn abort

The capability lookup that seeds the per-request tool-permission state was
awaited bare, so a transient resolution failure rejected out of
runCopilotLifecycle before any permission card could be drawn — an interactive
turn died over a database hiccup.

Reads as withheld instead, matching the decision endpoint: no stored
always-allow is loaded, nothing durable is remembered, and every gated call
still asks its one-time question.

* fix(knowledge): gate a manual connector sync on the persisted connector type

Removing a connector type from the allowlist stopped new connectors of that
type but left every existing one manually re-syncable, so the withdrawn source
kept being pulled in on demand.

A manual sync is a fresh act by a person, so it now asserts knowledge.connectors
against the type stored on the connector. Pausing and deleting stay ungated for
the reason the update use case records — nothing here strands a connector — and
the scheduled continuation, which runs executeSync directly and never reaches
this use case, is untouched.

* fix(credentials): project the user-global membership listing per credential workspace

Every credential names a workspace, and credentials.list withholds those rows
inside it under integrations.manage. The user-global memberships endpoint names
no workspace, so its own gate reads the caller's organization default group and
returned rows the workspace-scoped listing hides.

Each row is now projected against the group governing this same user in the
workspace holding the credential — the person's own group, not a bystander's.
Leaving a membership stays ungoverned by it: that revokes the caller's own
access and grants nothing, so gating it would strand them inside the share.

* fix(invitations): check the organization scope on an organization-kind resend too

An organization-kind invitation always admits the invitee to its stamped
organization, whichever workspaces it also grants. The resend gate checked only
the granted workspaces whenever the invitation carried any, so an explicit
workspace group permitting invitations carried a member into an organization
whose default group withheld them.

The organization scope is now checked as well as, not instead of, the grants for
that kind. A workspace-kind invitation admits nobody to the organization by
itself and keeps the per-grant check, falling back to the organization when it
has no grants.

* fix(logs): decide every log projection about the governed subject

resolvePrincipalSubjectUserId returns an executor delegation's subjectUserId,
so the six principal-holding log surfaces applied the run actor's logs.cost and
logs.trace_spans group to a delegation the authorization funnel had already
passed ungated - and assertLogCostQueryAllowed turned that into an outright
refusal of a cost-sorted read. State the rule once as
logProjectionSubjectUserId and derive every projection subject from it;
attribution ids are left alone.

* fix(logs): stop the migration erasing legacy runs' token counts

stripSpanCosts also runs inside backfill-trace-spans.ts, which stores what it
returns, so extending it to clear tokens turned a read-time projection into
permanent data loss for every authorized reader of a migrated run. Split the
two: stripSpanCosts keeps its persistence contract (dollars live in the ledger,
spans keep structure, timing and tokens), and the joined cross-workspace child
projection gets stripJoinedChildTraceSpend, which is never written back.

* test: cover the converged refusals, the log projections, and the modal seeding

* fix(executor): keep the gate subject across pause, drain and the run cache

Three ways a run's governed subject was lost after being resolved correctly
once:

- serializePauseSnapshot enumerates the metadata it rebuilds and did not list
  capabilityGovernedUserId, so a paused run resumed gating on the billing actor
  (governedSubjectUserId reads absence as 'not declared').
- continueCascadeAfterResume carried the paused cell's subject into the next
  group even when that group held another dispatch's unclaimed pre-stamp, which
  both drain points in workflow-column-execution already read off the stamp.
- getPermissionConfig memoizes on the ExecutionContext with no subject key,
  while validateModelProvider/validateBlockType passed the actor positionally -
  so the agent handler's model check cached the billing actor's group and every
  later assertPermissionsAllowed silently reused it. Derive the subject inside
  getPermissionConfig so the memo is correct by construction.

* fix(users): close the pre-stamp race in account deletion, and announce what it stopped

A dispatcher that passed its status read could stamp a new cell marker after
the bulk cancel and before the user delete; ON DELETE SET NULL then made it
indistinguishable from an actorless request and a sibling worker drained it
with no per-tool gate. Take FOR UPDATE on the departing user's row first: the
foreign key a stamp checks needs FOR KEY SHARE on that same row, so every
concurrent stamp either commits where the marker cancel still sees it, or
blocks and is refused.

Both cancels also bypassed the ordinary cancel path and so published nothing,
leaving collaborators watching a dispatch that will never advance. Return what
each stopped and publish the same terminal dispatch and cell events after the
commit.

* docs(table): state the backfill legacy-payload tradeoff honestly

A payload enqueued before capabilityGovernedUserId existed does not simply
reproduce the pre-existing behavior: before the field, the cascaded cells gated
on actorUserId. Record what null actually costs (one deploy's worth of
in-flight jobs, loosened for a session-made change) and why the alternatives
are worse - actorUserId is the billed account for a workspace-key change and
indistinguishable from a human on the payload, and failing closed abandons the
writes the schema change promised.

* fix(invitations): gate the resend on what the invitation admits to, not its kind

A workspace-kind invitation whose granted workspace belongs to an
organization joins the invitee to that organization exactly as an
organization-kind one does — acceptance derives the member row from the
workspace's LIVE organization — so keying the organization capability
check on `kind === 'organization'` left every organization-backed
workspace invitation performing an ungated organization admission.

`resolveInvitationAdmissionOrganizationId` answers the question the gate
actually has, from acceptance's own derivation: the live organization of
the granted workspace for a workspace invitation, the stamped one
otherwise, and nobody at all for an external intent or an escalation the
stamped organization refuses — the three cases where acceptance creates
no member row. Acceptance and the accept-screen preview now read the join
target through the same helper, so the gate cannot drift from what the
accept does.

The refusal converges on `capabilityRefusalResponse('invitations.send')`
so a client sees the same sentence and `details.code` as every other
withheld capability instead of bare prose.

* fix(table): key the export-download gate to the governed subject

The last raw `/api/table/**` capability gate still reading `authResult.userId`
bare. An internal executor JWT presents the run's actor, not somebody asking
for a file, so this refused a delegation the executor exemption passes
ungated — and refused the download of an export the same run was allowed to
start (`export-async`) and to list (`jobs`), both of which already derive
`capabilityGovernedAuthUserId`. The role check is untouched: it still runs on
the id the credential presents.

* fix(logs): stop the completion write persisting per-segment dollars

`copyTraceSpansWithoutCosts` dropped the span's own `cost` and nothing
else, so every completed run persisted the same dollars itemized
underneath it in `providerTiming.segments` — the duplicate the ledger
owns, and exactly what the legacy backfill had already learned to clear.

Both writers now run one removal rule: the copy isolates the nodes the
strip writes to (span, children, providerTiming, its segments) and hands
them to `stripSpanCosts`, so persistence and backfill cannot answer
differently about what a stored span may carry. Tokens survive on both
paths — they are trace detail, not dollars.

* style: restore biome 2.0.6 formatting the merge reverted

Five files staging reformatted under the upgraded biome came back to their
pre-upgrade bytes in the merge; all five hunks are formatting only (ASI-guard
blank lines, CSS font-family wrapping). Without this, format:check fails on
the merge commit.
2026-09-01 10:33:08 -07:00
Theodore Li 358af425cc fix(docker): allow pruned lockfile normalization (#7350) 2026-09-01 06:20:15 -04:00
Theodore Li 3de31cbed2 feat(slack): list DMs for managed credentials (#7349)
* feat(slack): list DMs for managed credentials

* fix(slack): default unresolved channel limits
2026-09-01 05:40:00 -04:00
Theodore Li 4941c73819 feat(streaming): support nested workflow outputs (#7346)
* feat(streaming): support nested workflow outputs

* fix(streaming): reset stale output drilldowns

* fix(streaming): validate nested output selectors

* fix(slack): use public output selectors

* fix(streaming): scope nested outputs by workflow

* fix(cli): align streaming selector help test
2026-09-01 05:37:07 -04:00
Waleed fd061f5045 improvement(deps): harden dependency graph (#7343)
* improvement(deps): harden dependency graph

* chore(deps): simplify dependency upkeep

* fix(sidebar): preserve cookie whitespace matching

* fix(deps): address review edge cases
2026-09-01 00:54:49 -07:00
Waleed b4bc9b98ec fix(sailpoint): complete integration validation (#7345)
* fix(sailpoint): complete integration validation

* fix(sailpoint): align account contract fixtures

* fix(sailpoint): update integration icon
2026-09-01 00:37:05 -07:00
Justin BlumencranzandVikhyath Mondreti 48f72a2109 feat(copilot): let Run agent cancel workflow runs (#7151)
* feat(copilot): execute workflow run cancellations

* fix(copilot): route run cancellations through internal API

* fix(copilot): share workflow cancellation boundary

* fix(copilot): honor aborts before cancellation commit

* fix(copilot): reconcile failed cancellation rollbacks

* fix(copilot): honor workflow group cancellation commit

* test(copilot): include workflow cancellation approval

* improvement(copilot): simplify cancellation lifecycle

* improvement(workflows): unify run cancellation

* fix(workflows): preserve v2 terminal cancellation responses

* fix(workflows): align cancellation adapter test

* fix(workflows): reconcile replacement resume cancellation

* fix(workflows): confirm every active resume stop

* fix(copilot): require workflow id for cancellation

* fix(workflows): validate cancellation terminal writes

* fix(workflows): cancel runs by execution id

* fix(workflows): reconcile failed abort rollbacks

* fix(workflows): restore rejected cancellation staging

* fix(workflows): preserve terminal runs during cancellation

* fix(execution): stop terminal-race resumes before cleanup

---------

Co-authored-by: Vikhyath Mondreti <vikhyath@simstudio.ai>
2026-08-31 21:09:17 -07:00
Theodore Li 1404e65a42 fix(slack): restore assistant operation compatibility (#7339)
* fix(slack): restore assistant operation compatibility

* fix(slack): split assistant and agent prompts
2026-08-31 23:50:42 -04:00
Waleed 694c34b212 improvement(integrations): refine Slack AEO content (#7344) 2026-08-31 20:47:44 -07:00
Waleed beef0ea401 improvement(oauth): resolve credential tokens in-process instead of hopping the token route (#7340)
* refactor(oauth): extract the token route's dispatch into resolveCredentialAccessToken

* feat(credentials): bind executor managed-OAuth delegations in-process

* improvement(executor): resolve credential tokens in-process instead of hopping the oauth token route

* docs(rules): correct the app/worker boundary guidance after inlining credential-token resolution

* fix(tools): keep dropping falsy impersonation subjects and surface refresh-failure causes

* refactor(oauth): apply simplify-pass cleanups to the inlined token resolution

* chore(executor): trim changelog narration from the resolver TSDoc

* test(oauth): expect the credentialType field the token payload now carries

* chore(tools): drop the orphaned wire-payload type and delegation-mint test vestiges
2026-08-31 20:37:13 -07:00
Waleed b1b5de72af improvement(integrations): add Twilio SMS AEO content (#7342)
* improvement(integrations): add Twilio SMS AEO content

* fix(integrations): align Twilio SMS content and imports
2026-08-31 20:29:16 -07:00
Bill LeoutsakosandBill Leoutsakos 27734f5f6b fix(webflow): paginate collection item selectors (#7337)
* fix(webflow): paginate collection item selectors

* fix(webflow): handle optional pagination metadata

---------

Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 20:12:12 -07:00
Vikhyath MondretiandClaude Opus 5 f2e20aaab3 fix(execution): stop treating the workflow owner as a live execution identity (#7330)
* fix(execution): stop treating the workflow owner as a live execution identity

A background run acts as the workspace billing account; `workflow.userId` is
only the personal-variable fallback. Several surfaces treated that stored
pointer as a live permission, so each broke when its owner left the workspace.

Deployed chat read `chat.userId` — the person who clicked "Deploy as chat" —
where every other trigger reads `workflow.userId`. Org member removal reassigns
`workflow.userId` to keep it an active workspace identity and has no equivalent
for the chat row, so the same transaction repaired the pointer every other
trigger reads and broke the only one chat read. Chat now passes the owner.

`getExecutionEnvironment` already tolerated a stale actor but not a stale
personal identity. Both are stored pointers, so a personal identity that cannot
reach the workspace now contributes no personal namespace — the judgment already
applied to an anonymous public-API run, and it stops lending a removed member's
secrets to their former organization. Only "neither identity reachable" raises.

The public API gated `validatePublicApiAllowed` and the workflow read on the
owner, though an anonymous call acts as the billing account and resolves no
personal variables at all. Both now use `getWorkspaceBilledAccountUserId`. The
enable-time gate, which checks the acting user, is unchanged.

Custom-block children and webhook provider-config resolved both environment
slices as the owner. They now split the two identities like any deployed run,
which also closes a silent inconsistency: a custom block saw a narrower
workspace-secret selection than a schedule on the very same workflow.

The ban gate no longer blocks on the workflow owner — banning one member should
not take down the schedules, webhooks, and chats their teammates depend on.

Logs gain a run-level `executedByEmail`, joined from the immutable per-run
attribution rather than from a workflow row that ownership transfer rewrites.
`workflow.ownerEmail` stays as a deprecated field, fed by its own aliased join,
because it is required in the published v2 schema.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(execution): suspend personal secrets for banned owners, and gate the ban candidate correctly

Review round 1 (Greptile P1 security, cubic P1 + P2).

Removing the workflow owner from the ban gate let a suspended account's personal
secrets keep flowing into background runs: a ban revokes neither workspace
membership nor the pointer naming that person, so the run continued on their own
keys. `getExecutionEnvironment` now drops the personal namespace when that
identity is suspended, the same answer it already gives a departed one — the run
survives, their credentials do not. Placing it in the shared resolver rather than
in `execution-core` covers the webhook and custom-block paths too, and keeps the
ban module out of the executor's import graph.

The ban candidate itself was also inconsistent: callers overload `userId`, so it
is an authenticated caller on a manual run but a stored pointer everywhere else —
the workflow owner from `checkWebhookPreprocessing`, the chat's creator from the
deployed-chat route, `'unknown'` from a schedule. Reading it unconditionally
meant the same ban suspended a webhook while the schedule beside it kept running.
It is now gated on `useAuthenticatedUserAsActor`, which is exactly the flag that
distinguishes the two — `workflow-column-execution` toggles them together.

Also corrects the custom-block authority TSDoc, which still claimed the owner
supplies both environment slices after this branch split them.

Regenerates the CLI API client for the v2 log contract change, which CI's
`check:cli-api` audit caught.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(execution): enforce suspension on every personal-secret path, and align webhook cleanup

Review round 2 (Greptile P1 security, cubic P0 — both found the same gap).

The suspension check sat next to the split-identity access lookups, so it was
skipped by the single-identity shortcut above it. That shortcut is taken whenever
the two identities coincide — which is exactly what happens when a custom-block
publisher is also their workspace's billing account. The check now runs before
the shortcut, unconditionally.

Round 1's placement rested on "admission already cleared this identity", and that
is not true everywhere: a custom-block child is admitted by
`admitCustomBlockChildExecution`, which checks usage limits and nothing else, and
a provider URL-validation challenge resolves its secret with no admission at all.
Neither path has ever had a ban gate.

Only the personal namespace is withheld. Workspace variables belong to the
workspace rather than to a person, so they keep resolving and a suspended
member's teammates keep working — the reason admission stopped blocking on this
identity to begin with.

Webhook cleanup now resolves through the same two-identity reader as delivery.
Reading both slices as the owner let cleanup see a narrower selection than the
delivery that created the subscription: a non-admin owner without a credential
grant left `{{VAR}}` unresolved, the provider was handed the literal reference as
its credential, and the non-fatal catch silently orphaned the subscription.

`resolveBackgroundWebhookEnv` imports the billing reader statically. The dynamic
import bought nothing — every boundary audit passes without it — and made each
worker pay a cold module load on the first webhook resolution.

Restores the `@sim/testing` mock-shape test, which pins that the default snapshot
carries every field of the real one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(webhooks): route every background env resolution through the identity resolver

Review round 3 (cubic P1).

`resolveBackgroundWebhookEnv` short-circuited to `getEffectiveDecryptedEnv` for
the two cases with no second identity — a legacy workspaceless webhook, and a
workspace with no billing account — which read the owner's variables without
passing the resolver's suspension check. cubic flagged the first; the second was
the same bypass one line down. Both now name the owner as both identities and go
through the resolver, which produces the identical resolution while putting them
behind the same gate.

Also corrects `provider-subscriptions.test.ts`, which still asserted cleanup
resolves via `getEffectiveDecryptedEnv`. That assertion was passing
intermittently rather than failing outright: `mockGetEffectiveDecryptedEnv` is a
shared singleton on `environmentUtilsMockFns`, so whether it had been called
depended on which other files shared the worker. It now asserts the two-identity
call, with the billing reader mocked so the split is actually exercised.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(execution): make the suspension gate fail closed on an undeclared userId

Review round 4 (Greptile P1 security).

Round 2 keyed the ban candidate on `useAuthenticatedUserAsActor`, assuming that
flag separates a live caller from a stored reference. It does not. The
interactive resume route reads `access.auth?.userId` and passes that live
resumer as `userId` while leaving the flag false on purpose — attribution is
captured before the pause and must not move — so a suspended user could resume a
paused run whose persisted attribution named a different, unsuspended actor.

The distinction is per-caller and cannot be inferred, so it is now declared.
`userIdIsStoredReference` defaults to false, which means an undeclared call site
keeps blocking; only the three that genuinely pass a stored reference opt out:
the webhook processor (the workflow owner), the deployed-chat route (the chat's
creator), and table-cell dispatch (the owner, but only when nothing triggered
it). Resume, manual, API, and async paths are candidates again.

Withholding a suspended account's personal variables stays where it was, in
`getExecutionEnvironment`, so the two concerns remain separable: a suspended
stored reference does not block the run, and does not lend its credentials
either.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 20:08:35 -07:00
Bill LeoutsakosandBill Leoutsakos 1c197c1257 fix(selectors): paginate BigQuery resources (#7334)
* fix(selectors): paginate BigQuery resources

* fix(selectors): support legacy BigQuery project ids

---------

Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 20:00:08 -07:00
mzxchandraandWaleed Latif dcaaf8e355 feat(sailpoint): add SailPoint (IGA) integration (#6092)
* feat(sailpoint): add SailPoint (IGA) integration

Add a SailPoint Identity Security Cloud integration with 27 tools spanning
identity-governance reads (search + count + aggregate, identities, accounts,
entitlements, roles, access profiles, sources, account activities, campaigns,
certifications, and entitlement expansion), the access-request write path
(request, cancel, status), and CSV account/entitlement aggregation.

Auth uses a service-identity Personal Access Token via the OAuth2
client-credentials grant against the per-tenant host
(https://{tenant}.api.identitynow.com), resolved server-side in two internal
routes (/api/tools/sailpoint/query and /load) with in-process token caching
and Retry-After 429 backoff. The block enumerates the exact PAT scopes and the
service-identity caveat. Access-request constraints (revoke one identity + one
item, grant 25-entitlement / 10-identity caps, comment-on-revoke) are enforced
pre-submission, and empty userAuth reads surface a permission-gap diagnostic.

* fix(sailpoint): address review - SSRF host allowlist, working aggregate, retry/count fixes

- Restrict tenant host resolution to *.api.identitynow.com / *.api.identitynowgov.com
  (or a bare tenant subdomain) so the client-credentials request can never post the PAT
  secret to an attacker-controlled or internal host. Throws on any other host.
- Make search_aggregate functional: add an aggregationsDsl input (tool/contract/route/block)
  and preserve the AggregationResult object instead of dropping it through the list handler.
- Retry the token exchange on 429 with Retry-After backoff, matching sailpointFetch.
- Rebuild the multipart FormData per attempt so 401/429 retries never reuse a consumed body.
- Expose an "Include Total Count" toggle so totalCount is reachable from the block UI.
- Regenerate docs. Add route tests for the SSRF guard and aggregate object preservation.

* fix(sailpoint): require aggregations for aggregate, expose searchAfter, fix review-item filters

- Require aggregationsDsl on search_aggregate (contract + tool) and send aggregationType: DSL so
  /search/aggregate always receives a valid aggregations definition.
- Coerce searchAfter cursor elements to strings instead of dropping non-string values, and expose
  a searchAfter input on the block so deep pagination past 10k is reachable from the UI.
- Correct the certification review-item filter fields (entitlements / access profiles / roles) to
  comma-separated ID filters instead of true/false placeholders.

* fix(sailpoint): bind the token cache to the client secret

Include a hash of client_secret in the token cache key so a caller with a matching
tenant/clientId but the wrong secret cannot reuse another principal's cached bearer token -
a mismatched secret now misses the cache and fails the token exchange. Regression test added.

* fix(sailpoint): adaptive token TTL buffer and honest search-count on missing header

- Cap the token cache expiry buffer at the smaller of 60s and 10% of the lifetime so a short-lived
  token still caches instead of expiring immediately.
- Return an error for search_count when SailPoint provides no X-Total-Count (and no numeric body)
  instead of reporting a misleading total of 0. Tests added for both count paths.

* fix(sailpoint): align integration with current api

* chore(docs): refresh generated manifest

* fix(sailpoint): reject empty aggregation definitions

* fix(docs): render SailPoint tenant placeholder

* fix(docs): source safe SailPoint tenant URL

---------

Co-authored-by: Waleed Latif <walif6@gmail.com>
2026-08-31 19:53:48 -07:00
Bill LeoutsakosandBill Leoutsakos 507663f5a5 fix(selectors): paginate SharePoint sites and lists (#7335)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 19:49:57 -07:00
Waleed 2598f4457a fix(workflows): preserve contrast on gradient tiles (#7332)
* fix(workflows): preserve contrast on gradient tiles

* fix(workflows): validate gradient color stops
2026-08-31 19:33:25 -07:00
mzxchandraandcubic-dev-ai[bot] 8430f0fdc0 fix(tables): make the agent tool picker version-aware and enrich the v2 query (#7328)
* fix(tables): make the agent tool picker version-aware and enrich the v2 query

The Agent block's tool picker gated on a hardcoded `CORE_AGENT_TOOL_TYPES`
set naming `'table'` with no version resolution. Both Table blocks are
`category: 'blocks'`, so that set is their only route into the picker —
meaning `table_v2` would never appear there, even once it ships and the
toolbar has moved to it. Store base types and match after stripping the
`_vN` suffix so a cutover never has to re-list a block here. The existing
`hideFromToolbar` guard already excludes superseded versions (file v1-v4)
and unrevealed preview blocks, so broadening `file_v5` to `file` admits
nothing new. `BUILT_IN_TOOL_TYPES` had the same gap and would have filed
v2 under Integrations.

`table_query_rows_v2` also shipped with no `toolEnrichment` while all seven
other table tools have one, so an agent using it never saw the table's
column names and had to guess field values. The enrichment module only knew
v1's MongoDB grammar, so adding the id to the existing sets would have
taught the wrong syntax — v2 gets its own branch emitting predicate
examples, `order` rather than `sort`, and cursor paging guidance.

Unlike v1, a v2 query with no filter is valid and returns every row, so the
new branch deliberately does not push `filter` into `required`.

The shared bulk tools stay on `$eq`: the rows route accepts either grammar
via `resolveBulkFilter`, and enrichment is keyed on tool id alone, so it
cannot tell which block invoked it.

* fix(tables): add ncontains to the v2 operator lists and guard the enrichment wiring

Review findings.

The operator list the v2 surfaces advertise omitted `ncontains`, which
`FILTER_OPS` declares and `sql.ts` compiles to a negated ILIKE. An agent
reading the tool schema therefore never knew the operator existed. The list
is spelled out verbatim in several places and had already drifted from its
source of truth on arrival; deriving it from `FILTER_OPS` is the real fix
and is left as follow-up.

The `toolEnrichment` block this branch adds had no test, which is the same
gap that let v2 ship without enrichment in the first place — a refactor
could silently drop it again, and a typo in the tool-id literal degrades to
the generic description with no failure. Pin both halves: the tool declares
the wiring, and the enricher answers in predicate grammar with `filter`
left optional.

Also cover the two `v2PredicateExample` arms an all-numeric or all-text
table takes, and assert the empty-order case the previous test only
executed without checking.

* fix(tables): teach the v2 enrichment which operators a select column accepts

Greptile and cubic both flagged this independently, and they were right.

A select column accepts only a subset of the filter operators — eq/ne/in/nin
when single, contains/ncontains when multi — and `buildFilterConditions`
THROWS on anything else rather than returning no rows. The new v2 enrichment
advertised the full operator list for every column and, worse, asserted
"there are no array columns - for substring matching use ilike with *x*".
A multi-select cell holds a list, so that sentence is false and it steers
the model straight into a rejected query on exactly the columns it describes.

The enricher could not tell single from multi because `readTableSchemaAsExecutor`
dropped `multiple` when projecting the summary. Carry it through — for select
columns only, where it means something — and annotate each select column in
the description with the operators it actually takes.

The block's bestPractices carried the same false claim, so the model reached
it a second way even when enrichment was absent. Corrected there too.

Also regenerate the tool metadata bundle, which is what CI was failing on:
the ncontains commit changed the v2 tool description without regenerating
the derived artifact.

* fix(tables): derive select operator guidance from the validator's own sets

Round 2 review. Both bots were right, and the second finding corrected me.

The first fix annotated the column list but left the `filter` PARAMETER
description advertising every operator for every column. That description is
what a model reads when deciding the filter's shape, so the restriction has
to appear there too — it now names the restricted columns inline.

More importantly, the annotation itself was wrong: I omitted isNull and
isNotNull. I had traced the v2 grammar through `predicateToFilter` to the
`$`-prefixed sets in `column-types/select.ts`, which genuinely lack them —
but the v2 query path never goes through that conversion. It compiles
predicates directly in `fieldPredicate`, which gates on a SEPARATE pair of
`FilterOp` sets that do allow both.

Two allowlists for one concept is what made a hand-copied list wrong, so the
v2 sets move next to their v1 siblings in the column-type registry — where
per-type knowledge belongs — and the enrichment now derives its text from
the exact sets the validator gates on. It can no longer drift.

Same correction applied to the block's bestPractices, which carried the
short list too.

* feat(tables): GA table_v2 and mark the v1 Table block legacy

Follows the gmail_v2 / github_v2 / confluence_v2 / cursor_v2 cutovers: v1
is renamed "(Legacy)", hidden from discovery, and points at its successor;
v2 drops the preview gate. Both edits must land together — the registry
check fails a sunset block whose replacedBy is still preview, verified by
splitting them locally.

v1's `triggers.enabled` deliberately stays true. Webhook execution gates
on it at runtime rather than on discovery, so flipping it would break every
deployed v1 table-trigger workflow. Both versions host the same
`table_new_row` trigger and dispatch is provider-keyed, so hiding v1
changes nothing for triggers.

No BLOCK_META_REGISTRY entry is needed — meta coverage is required only for
`category: 'tools'` blocks and both Table blocks are `category: 'blocks'`.

Docs regenerate from v2 now that v1 is skipped as a source, so the
generated page moves to the predicate grammar and cursor pagination. The
hand-written regions did not, and are updated here: the operator reference
and combining examples, the workflow guide's field walkthrough, and the
pagination advice — which previously told readers to advance an offset
while looping on nextCursor, mixing both versions.

Verified in the browser: the toolbar yields a `table_v2` block whose Query
Rows shows Cursor/Order; the Agent tool picker stores
`type: table_v2, toolId: table_query_rows_v2` and groups it under built-ins;
and a pre-existing v1 block still renders its own Offset/Sort fields behind
an amber legacy badge.

* fix(tables): restore the docs hero and correct the operator reference

Review findings, all consequences of v2 becoming the docs source.

`BlockPreview` looks the block type up in a hand-maintained map and renders
nothing when it misses, so pointing the trigger page at `table_v2` silently
deleted its hero. Move the entry to the new type; the trigger config it
displays is identical across both versions.

The docs generator extracts `longDescription` with a single-literal regex,
so v2's `+`-concatenated string published as its first fragment alone — the
page lost every mention of the predicate grammar and cursor pagination.
Join it into one literal. v1's was a single literal, which is why this only
surfaced now.

The hand-written operator table called `contains` case-sensitive. It
compiles to ILIKE, as do `startsWith` and `endsWith`; the pre-cutover page
had this right, so the rewrite regressed it. Restore the qualifiers and
document `ncontains` alongside `contains`.

Drop `'table'` from BUILT_IN_TOOL_TYPES: it now only ever reaches blocks
that already passed `isAgentToolBlock`, which excludes hidden ones, so the
entry is dead. Matches the `file`/`file_v5` precedent the sibling test
already asserts.

* docs(tables): finish the v2 cutover's documentation trail

Regenerate the two artifacts the `ncontains` commit left stale: the tool
metadata bundle and the generated Table integration page both still published
the operator list without it, so `bun run tool-metadata:check` failed at HEAD.

Point the remaining docs previews at `table_v2`. `BLOCK_DISPLAY_WORKFLOWS`
already moved, but the two hand-written table example workflows and the
OutputBundle on the workflows guide still named the v1 type, so every table
example in the docs described the block the toolbar no longer yields. They
render identically today only because both types share an icon-map entry.

The workflows guide told readers the log shows "the filter and sort it sent";
v2 sends `order`.

Document the `sunset` step in the three skills that describe the v1 -> v2
cutover. All three stopped at `(Legacy)` + `hideFromToolbar`, but
`check-block-registry` fails a legacy block with no `replacedBy`, and the
amber badge and its click-to-upgrade action read from that field - following
the procedure verbatim produced a build failure. Also record the ordering
constraint this cutover hit: the v1 `sunset` edit and the v2 `preview` removal
must land together, since the check rejects a `replacedBy` that is still
preview.

Left alone: the academy video previews still show v1 labels. They mirror
recorded footage, so correcting the label without a re-record would only make
the still disagree with the video it claims to depict.

* docs(tables): restore the select-operator reference lost in the rebase

The regenerated page reverted to the "there are no array columns" claim that
the select-operator fix corrected. Restore the allowed-operator table.

* fix(tables): address review on the cutover

Greptile: convert the v1 lifecycle comment to TSDoc. The repo rule is
TSDoc-only, and none of the four reference cutover blocks comment here at
all, so the `//` form was not following a local convention either. The note
is worth keeping as declaration documentation — it records why
`triggers.enabled` must stay true.

Cubic: fix a link to `#tips`, an anchor that does not exist on the page.
The pagination guidance lives under Variations.

* docs(skills): require a GA target before adding sunset replacedBy

Review finding. The add-integration cutover steps said to add
`sunset.replacedBy` without stating the precondition, so an author following
them while v2 was still preview-gated would get a `check-block-registry`
failure — the exact constraint this cutover hit.

The sibling add-block and add-block-preview skills already spell this out;
this brings the third in line.

* fix(tables): name a real column in the wildcard example

Review finding. Instruction 5 hardcoded `{"field":"name",...}` while every
other example in the block is derived from the table's own columns. An
unknown field is rejected outright — `Unknown filter column "name". It is
not a column on this table.` — so on a table without that column the
example invited the model to write a query that cannot run.

Derived from a real text column now, and dropped entirely when the table
has none rather than falling back to a placeholder.

* fix(tables): drop the (Legacy) name suffix from the v1 block

The amber legacy badge and its click-to-upgrade action already mark a
sunset block in the UI, so the suffix restated it — a placed v1 block
rendered a "Table (Legacy)" type tag next to a "legacy" badge saying the
same thing.

The four earlier cutovers (gmail, github, confluence, cursor) carry the
suffix, but the most recent one does not: the slack_v2 GA left v1 named
"Slack" and leaned on the badge. Following that.

* fix(tables): cover all four pattern operators and make the filter optional

Review findings, both in the instruction text.

The wildcard rule named only like/ilike, but nlike and nilike route through
the same `buildPatternClause`. That matters more than an omission: the
builder ESCAPES `%` before translating `*`, so a model reaching for `%` on a
negative pattern gets a literal-percent match and silently wrong rows rather
than an error. The rule now names all four and says never to use `%`.

Instructions 1 and 11 together pushed the model to invent a predicate for a
question that carries no condition — "the 5 most recent rows" is answered
with order and limit, and v2 accepts an omitted filter. Both now say so.

* Update apps/sim/lib/table/llm/enrichment.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update apps/sim/lib/table/llm/enrichment.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-08-31 19:31:15 -07:00
Theodore Li fde8cf9236 fix(cron): derive async job retention cutoffs from one clock read (#7333) 2026-08-31 22:29:57 -04:00
Theodore Li 2173a70f5c feat(slack): add agent sessions and streaming (#7296)
* feat(slack): add agent sessions and streaming

* fix(slack): preserve agent workflow compatibility

* fix(slack): enforce agent API compatibility

* feat(slack): stream trigger responses to agent sessions

* fix(slack): polish trigger response streaming

* fix(slack): finalize agent session streaming

* feat(slack): add slash command triggers
2026-08-31 22:07:03 -04:00
Waleed e5e67b3f06 feat(circleback): add API tools, expanded block, and knowledge base connector (#7331)
* feat(circleback): add API tools, expanded block, and knowledge base connector

* improvement(circleback): resolve relative pagination links against the API base

* fix(docs-generator): drop circleback from the spread-only subBlocks fixture

* improvement(circleback): address review findings on output schemas, assignee validation, and connector indexing

* fix(circleback): reject unlimited-coercing sync caps and correct the block id output type

* fix(circleback): scope dual-purpose action-item and search inputs per operation

* fix(circleback): reject a zero sync cap that would coerce to unlimited
2026-08-31 18:37:09 -07:00
Vikhyath Mondreti e100c5af41 fix(files): bound YAML expansion and buffered reads on the file-serve path (#7319)
* fix(files): bound YAML expansion and buffered reads on the file-serve path

Two unbounded resource paths reachable from the anonymous public share routes.

YAML alias expansion: the page compiler parsed sim: fence payloads with no
ceiling on what the parsed value expands to. Aliases are shared references, so
`columns: &c [...]` plus a row list of aliases to it renders N^2 cells from ~13N
source bytes — 25 KB of source cost 3.6s of CPU and 38 MB of HTML per request.
The expansion guard already in the file parser is now a shared primitive taking
caller-supplied limits, and the compiler charges every fence and the frontmatter
to one per-compile budget so splitting across blocks buys no extra rendering.

Buffered reads: the Files-module serve path already capped reads at
MAX_BUFFERED_TRANSFER_BYTES via fetchWorkspaceFileBuffer, but five sibling paths
serving the same objects did not, including both unauthenticated share routes.
A workspace object is admitted at 5 GB, so a share link was the one way to make
an anonymous request hold gigabytes resident in the shared process.

* fix(files): check transformed bytes against the ceiling and bound the guard's own walk

Review round 1.

Bounding the source read did not bound the response: every branch that replaces
the source — a compiled document artifact fetched separately, a page with its
images inlined, a transcoded image derivative — could turn a source under the
ceiling into a response over it, on the anonymous share route included. The check
now sits where those branches converge rather than on the page branch alone.

The local read enforced its ceiling on a size measured before the read, so it
described the file only as of the stat. It now reads through the same bounded
stream reader the S3/Blob/GCS downloads use.

The expansion guard held one stack frame per pending node, so proving a wide
document too large allocated in proportion to the width it was rejecting. It now
holds one frame per level of nesting and consumes each container through a lazy
generator, bounding its own working set by depth. A double serializes to up to 24
characters, so numbers are charged their serialized length rather than the flat
16-byte allowance they could outgrow.

* fix(files): route the raw serve branch through the same response ceiling

The `raw=1` branch returned before the check, so the ceiling held for the
branches that transform bytes but not for the one that returns them unchanged.
Those bytes are already bounded by the read that produced them, so this changes
no behavior — it makes the guarantee hold for everything the resolver returns
rather than for every branch someone remembered to cover.

* fix(files): bound the artifact and local reads at the read, not at the response

Review round 2.

The response-level ceiling rejected an oversized compiled artifact only after the
whole thing was resident, which is the allocation it exists to prevent. The
artifact read is bounded at its own funnel instead, and a size breach is rethrown
rather than folded into the "not built yet" null — that answer tells callers to
retry, which an oversized artifact would never stop doing. The cached image
derivative is bounded the same way, but keeps swallowing the breach, because a
miss there re-transcodes from an already-bounded source.

The local storage branch enforced its ceiling with stat-then-read, so it described
the file only as of the stat. It now reads through the same bounded-stream reader
the cloud branches use — this is the anonymous share path on a self-hosted
deployment, and the route helper was already fixed while the storage service it
sits next to was not.

The default js-yaml schema turns a timestamp into a Date, which serializes to a
26-character quoted string; charging it the 16-byte flat allowance let a document
of them exceed the byte cap.

* fix(files): bound the shared artifact reads at the widest consumer ceiling

Review round 3.

The previous round bounded the compiled-artifact and cached-derivative reads at
the rendered-document ceiling, which is half what the serving routes will return.
That made the bound a policy rather than a backstop: an artifact between the two
figures was refused even though the route accepts a response that size, and a
derivative in that band read as a cache miss on every preview and re-transcoded
the original each time.

Both funnels now bound at the widest ceiling any of their consumers allows. A
consumer that permits less still enforces its own limit on what it got back — the
workspace download path continues to hold artifacts to the rendered-document
ceiling.
2026-08-31 18:26:48 -07:00
Bill LeoutsakosandBill Leoutsakos 616d5e919d fix(selectors): paginate HubSpot list options (#7327)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 17:45:09 -07:00
Vikhyath MondretiandSim Pi Agent f4f185045e feat(library): Sim vs. Dedicated Chatbot Builders (#7325)
Co-authored-by: Sim Pi Agent <pi@sim.ai>
2026-08-31 17:33:49 -07:00
Waleed 898ecdb036 chore(analytics): remove Profound request tracking (#7326) 2026-08-31 17:32:46 -07:00
Bill LeoutsakosandBill Leoutsakos 04f7cd275d fix(notion): resolve custom page title properties (#7323)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 17:28:37 -07:00
Bill LeoutsakosandBill Leoutsakos bd7995e20f fix(selectors): normalize Bitbucket workspace UUIDs (#7320)
Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local>
2026-08-31 17:27:22 -07:00
Waleed bd75254d95 feat(workspace): support GIF logos (#7322) 2026-08-31 17:04:03 -07:00
Justin Blumencranz 8309ad5f83 chore(copilot): sync mothership contracts (#7316) 2026-08-31 16:47:27 -07:00
Waleed 19e4570a7f chore(security): add proxy rate-limit regression coverage (#7318) 2026-08-31 16:46:32 -07:00
Waleed d8a6b6bf87 improvement(desktop): harden browser agent (#7311)
* improvement(desktop): harden browser agent

* fix(desktop): close browser review gaps
2026-08-31 16:38:57 -07:00
Waleed b64a1383df fix(settings): restore SSO recovery and lifecycle test isolation (#7317)
* fix(settings): restore recovery and test isolation

* fix(settings): scope SSO retry state to failed queries
2026-08-31 16:38:40 -07:00
Vikhyath MondretiandClaude Opus 5 8e9aeb956e fix(executor): stop resolved data from breaking out of generated condition and function code (#7300)
* fix(executor): stop resolved data from breaking out of generated code

A Condition expression is compiled by inlining each resolved reference as
source text, and the literal that gets emitted only ever anticipated the
quoting it chose itself. The author's quoting decides the real context, so
`"<start.input>".includes('urgent')` — a shape that works correctly with
benign data — let webhook, chat, or form data close the author's string and
run as JavaScript in the condition sandbox, which receives the workspace's
whole decrypted environment as the `environmentVariables` global. Template
literals, regex literals, and a crafted object key reached the same place.

Both condition formatters now escape every terminator of every JavaScript
string context rather than the one they open. `\"`, `` \` ``, `\$` and `\/`
are identity escapes, so a condition compares exactly what it compared
before; only its ability to parse as anything but data changes. A quoted
object reference additionally escapes its JSON, the only reading of that
shape that was not already a syntax error.

Function blocks bind block outputs as context variables but inlined the
remaining resolved values as literals, so a workflow variable a Variables
block had assigned from trigger data, or a loop item, could close the
string it landed in. Those bind now too. Numbers, booleans, null, and
strings that name an environment variable stay inline: the first three
cannot terminate a literal, and the last has to stay in source because the
placeholder — never the secret — is what is inlined, and the
execution-boundary compiler binds it downstream.

Condition evaluation also stops shipping the full secret map to the
sandbox: it mounts only the names its script references, so a future defect
in this path reaches nothing the condition did not already name.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): parse condition objects instead of splicing their JSON

Escaping a quoted object's JSON left the quote scanner load-bearing for
injection: it does not track regex literals, so a quote inside one
desynchronizes it and a later object reference is reported as unquoted,
which put raw attacker-shaped JSON back into source. A reference inside a
regex literal reached the same place through its unescaped slashes.

Objects outside a string are now parsed at runtime from a fully escaped
literal. The value is identical to the object literal it replaces, and the
emitted form carries no quote, slash, backtick or `${`, so it stays inert
whichever context the scanner reports.

Scoping now reads the expressions for a direct `environmentVariables`
access rather than the whole generated script, so a source block's output
containing that word can no longer widen the mounted secret set. The
placeholder scan still reads the built script, which is the text the
execution-boundary compiler substitutes over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): widen the condition environment read to any mention

A member-access pattern decides whether a condition keeps the full secret
map, and every shape it fails to anticipate — `environmentVariables?.FLAG`,
a read through `Object.keys` — silently narrows what that expression can
see and routes the run down a branch the author did not write. Matching the
bare identifier inside the expressions costs only the narrowing, and never
mounts more than this path mounted before it existed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): teach the code scanner about regex literals

A regex body is the one place a lone quote is not a string delimiter, and
the scanner did not track regex literals at all: `/['"]/` left it believing
everything after it sat inside a string. Every later reference was then
formatted for a context it was not in — a quoted object reference stayed
raw source, and after the previous commit a bare one was emitted as escaped
JSON, which cannot parse, so a valid condition threw instead of routing.

The scan now enters regex mode where a `/` can only be a regex — division
always follows a value, so the preceding token decides — and tracks escapes
and character classes until the closing delimiter. A reference inside a
regex reports its own context, so its JSON is escaped as pattern text
rather than spliced with delimiters the data could forge.

The same scanner decides how function-block references are spliced, so this
also repairs quoting for code that matches on a quote-bearing pattern.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): keep resolved data out of the condition secret decision

The built script carries the source block's output as data, so scanning it
for placeholders let a caller choose which secret materializes beside its
own payload: `{{SECRET}}` in trigger data mounted that secret and had the
compiler expand it into the serialized context. Both scans now read the
expressions, which is where every legitimate route to a secret runs —
including a workflow variable holding `{{NAME}}`, since the resolver inlines
that value into the expression before this handler sees it.

`throw` joins the keywords a regex may follow. `throw /re/` is legal, and
without it the scan reads the pattern body as code and mis-reports the
context of everything after it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): read what a closing parenthesis closed

`)` ends a value in `(a + b) / 2` and a control-flow head in
`if (a) /re/.test(b)`, and the character alone does not say which. Treating
it as one or the other unconditionally misreads the other: as a value, a
statement-position regex is scanned as code, and a quote inside it decides
how every reference sharing that line is spliced; as a head, ordinary
division opens a regex that swallows the quotes after it.

The scan now records which kind of parenthesis each `)` closed, by reading
the keyword in front of its opener, and answers from that.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): decide the environment read from the author's own text

Resolved data is quoted inside the expression the handler sees, so a
payload containing `environmentVariables` read exactly like the author
reaching for the map, and a caller could restore the full secret set by
sending the word. The resolver now records that answer per branch from the
pre-resolution expression, where only the author's text exists, and the
handler reads the record — falling back to scanning only when a caller did
not resolve through the resolver, since narrowing a real read would route
the run silently.

A closed regex literal also counts as a value now, so the division in
`/re/.source.length / 2` no longer opens a second regex that swallows the
quotes after it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): do not read a keyword-named method as a control-flow head

`p.catch(fn)` is a call whose name happens to be a keyword, and what
follows its `)` is an operator rather than a statement — so the division in
`p.catch(fn) / 2` opened regex mode and ran over the quotes around any
reference later on that line. A control-flow head is never a property
access, so the check now refuses one that follows a dot.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): keep a caller from choosing which secret expands

A placeholder-bearing string stays in source so the boundary compiler can
expand it, which is how a workflow variable holding `{{NAME}}` reaches its
value. Any run value took that path too, so text arriving from a trigger or
a loop item could name a secret and have the compiler materialize it beside
the payload that named it. Only a workflow variable — a surface an author
configures — keeps the inline form now; every other value binds.

A block comment can also stand between a property-access dot and a
keyword-named method, hiding the dot from the control-flow-head check. A
comment ending there now reads as the method call it almost always is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): step over comments instead of reading them as tokens

Treating a comment end as the answer was too blunt: `/* c */ if (x)` is a
control-flow head, and calling it a method left a statement-position regex
scanned as division — the failure the comment guard was added to prevent,
moved one shape over. The scan now steps back over comments to the token
that precedes them, so the dot in `p./* c */catch(fn)` is still found and
a keyword after a comment is still a head.

A condition's environment read is placed the same way references are: an
occurrence inside a string, a template, or a regex is text and mounts
nothing, while any executable read — whatever its shape — keeps the map.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): take the preceding token from the scan, not from a walk back

Reading backwards cannot tell which characters were code: a block comment
opens at its first delimiter, so `p./* a /* b */catch(fn)` defeated a
search for the nearest `/*` and the call read as a control-flow head again.

The scan already knows — it stepped over that comment on the way in — so
the two facts the check needs, the token before the parenthesis and whether
it followed a property access, are now recorded as it passes and read from
there. No search back through the source, and nothing left for a comment
body to imitate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): divide after a postfix update

`+` and `-` precede a regex as operators, but doubled they end a value, so
`i++ / 2` was scanning a regex from the division and swallowing whatever
quotes followed it on that line. The check now reads the pair rather than
the single character; a lone `+` still admits `params.n + /re/.test(x)`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(executor): start a new identifier at the character before it

A token continues only when the character immediately before it belongs to
the same token. Asking the previous *significant* character instead made a
name after a line break look like a continuation, so it kept whatever
property-access answer the last token had: `const seen = params.a.b` on one
line left the `if` on the next carrying `b`'s, which turned the statement
head into a method call and the regex after it into division.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 16:19:04 -07:00
Waleed 70783dcd13 improvement(settings): accelerate navigation and data loading (#7299)
* improvement(settings): accelerate navigation and data loading

* fix(settings): harden loading and session boundaries

* fix(settings): tighten navigation and auth coverage

* fix(settings): handle unavailable pathname

* docs(settings): document data warming pattern

* fix(settings): isolate identity lifecycle state

* fix(settings): harden async lifecycle consistency

* fix(settings): release superseded reconnect ownership

* fix(settings): preserve debug lifecycle ownership

* fix(settings): tighten intent and execution boundaries

* refactor(settings): remove orphan sandbox query module
2026-08-31 16:17:58 -07:00
Waleed f9c22fd50f fix(auth): revoke stale email share access (#7314) 2026-08-31 16:16:20 -07:00