mirror of
https://github.com/simstudioai/sim.git
synced 2026-11-27 17:39:54 +08:00
main
49
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
02fb744393 |
fix(workflow-code): correctness, safety and speed for workflows and workspace as code (#10237)
Wave 1 from the staging evaluation of workflows/workspace as code, audited by 5 lenses and re-audited. Deploy/drift safety (no out-of-band draft publishes; expected-draft fingerprints on deploy and chat writes; drift warnings by default), adopt/promote/partial-apply safety, one shared refusal decision for server and offline check, compiler and CLI correctness, feature gate after authorization, read-cost plan routes, realtime flush lost-update fixes, deterministic edge/block load order, and diff-based normalized saves with restored workflow_edges block FK indexes (migration 0467). |
||
|
|
bc8f09ccb1 |
feat(workflow-code): workflows and workspace as code (#10129)
* test: type the MCP base address the concealment check compares
* fix(workspace-code): check file path collisions on a segment tree, not a map of every prefix
Keeping every folder prefix of every path still held about a million prefix strings for
20,000 deep paths. A tree of folded segments costs one fold per segment and holds each
segment once, so the depth cap is no longer needed.
* refactor: drop the exports of isSuspiciousCharacter and readFolderWritten, used only in their files
* docs(workflow-code): CI needs a personal key; document workspace-key E_APPLY_FORBIDDEN and --only
workflows.source.apply and create deny workspace API keys, so the CI guidance now asks for a
personal API key or an OAuth login. Workspace as code names the kinds a workspace key cannot
write (workflows, skills, secrets, deployments), the E_APPLY_FORBIDDEN refusal, and narrowing
an apply with --only.
* docs(workflow-code): link the code pages from workflows, CLI, getting started, API and MCP
Adds a For coding agents section to Workflows as code (get, edit, check, status, apply, starting
from .sim/AGENTS.md), a prefer-source note on the API build guide, and an MCP section on editing
a whole workflow with getWorkflowSource and applyWorkflowSource.
* docs(self-hosting): document the WORKFLOW_CODE preview flag
Adds a Preview features section with WORKFLOW_CODE and links it from the in-preview callouts on
the workflows and workspace as code pages.
* feat(workflow-code): Code tab header with Preview label, CLI copy and docs; Download as code
The Code tab gets a title row: a Preview badge, a button copying
sim workflows source get <workflowId> --dir ./<workflow-name-slug>, and a link to the docs.
The workflow menu gains Download as code beside Export workflow, saving the draft as the
single TypeScript file the Code tab shows (function code inline). The download revalidates the
cached source by ETag first, so an edit since the tab last read is never missed.
* chore(rules): load the workflow-code rule for the v2 source routes, contracts and staging cleanup
* feat(llms): list workflows as code in llms.txt
* docs(cli): workflows and workspaces as code in the README, help epilogue and source group descriptions
Adds a README section (get, check, status, diff, apply and the coding-agent loop), a source get
example to the root help, and describes both source groups as read and apply, marked (preview)
while the server flag gates them. Regenerating the CLI docs changes nothing: the pages list each
command, not group descriptions or the root epilogue.
* test(workspace-source): a re-run adopting a stopped MCP replace with stored() headers still needs an admin
A workspace key re-running an interrupted replace is refused with E_APPLY_FORBIDDEN, the
owner's re-run finishes it, and a read-only member's get prints the adopted server's
literal headers as stored().
* feat(workflow-code): roll the workflow-code flag out by organization, workspace or user
Every source use case, the Code tab layout and useFeatureFlag now evaluate
workflow-code against the workspace, its organization and the acting user,
so AppConfig orgIds/workspaceIds/userIds allowlists take effect. Adds the
rollout plan to the workflow-code design doc.
* feat(mothership): grant the workflow-code entitlement where the source commands run
computeEntitlements now sends workflow-code to the worker for a workspace or
organization chat whose rollout has the flag on, ahead of the worker's
ENTITLEMENTS enum (the wire accepts any name). The CLI inventory marks every
workflows source and workspaces source command with entitlement: workflow-code
so the worker can hide them once it reads the field.
* docs(api): say how workspace source blobs are staged, and that dryRun previews
The applyWorkspaceSource description pointed MCP readers at Stage Workspace
Source Blobs, a multipart route MCP does not expose; it now names the CLI and
the blob upload route. The MCP write tool no longer claims no write can be
previewed: the source applies take dryRun.
* feat(analytics): record workflow source reads and dry runs, and workspace source applies
Adds workflow_source_read, workflow_source_dry_run and workspace_source_applied
beside workflow_source_applied: same attribution, kinds and counts only. A
refused dry run is now a dry-run event, never an apply.
* docs(workflows): commit written.json and point workspace CI to its own section
* test: read the MCP server URL as nullable in the stopped-replace check
* test(workflow-code): resolve the workspace before the flag in the HEAD 403 check
The flag now needs the workspace's organization, so the read routes resolve
the workspace first; the test gives them one to resolve.
* test(analytics): one workspace_source_applied per apply, refused, partial or committed
Busy, rejected and partial applies each record exactly one event with their
outcome, the committed retry one more, and a dry run none.
* fix(cli): resend a rate-limited GET even when its response body is lost
Cancelling an errored body rejects, so a 429 whose body was lost threw the raw
stream error instead of resending.
* fix(tests): order the workspace source "nothing was written" snapshots by id
The snapshots compared before and after a refused apply selected rows with no
ORDER BY, so their order was whichever index the planner chose: on the
workflow table the sort, unique-name and workspace_id indexes each return a
workspace's rows in a different order. Once autovacuum analyzed the table
between the two reads the plan could change, and the cross-kind test failed
with equal rows in a different order. Forcing the second read off index scans
reproduced the exact failure; ordering by id makes the comparison
plan-independent.
* refactor(source): one vocabulary for the fingerprint of what the server stores
PlannedChange.serverFingerprint is storedFingerprint and KindAdapter.fingerprintNow is
storedFingerprintNow; the workflow adapter's currentFingerprint() is readStoredFingerprint;
the sf1: helper in print-stored is storedSourceFingerprint, beside the kinds' rf1:
storedFingerprint; the workflow apply's local and EvaluatedSource field are storedFingerprint,
as source-commit already named it. The 409 wire field currentFingerprint is unchanged.
* fix(workflow-sdk): the workspace runtime exports defineSecrets and defineCredentials
secrets.d.ts and credentials.d.ts declare them and the cookbook imports them, but the
runtime entry did not export them, so running such a file failed with 'export not found'
instead of SimSdkNotExecutable. codeFile now re-exports core's stub, as tool.d.ts declares.
A test keeps the runtime's exports equal to every value the declarations declare.
* fix(workspace-source): re-scan deletes for new users under the apply lease
The plan's in-use scan ran before the lease, so an apply that saved a workflow
using a resource another apply was about to delete went unseen: the deleting
apply took the lease and deleted anyway. The apply now scans its deletes again
once it holds the lease and refuses (E_APPLY_STALE, nothing written) a delete
that a workflow the plan did not find now uses; a scan timeout still fails
closed.
* fix(cli): take a stale source-directory lock over safely, never through a link
Two commands that found one lock stale could both remove it: the later one's
removal deleted the live lock the first had taken, admitting two writers. A
takeover now claims the stale lock folder it removes (only one command can) and
checks it is still stale first, so a lock that replaced it is left alone.
The lock path also bypassed the source directory's symlink checks: a .sim or
command.lock that is a link was followed. Both are now refused
(SOURCE_SYMLINK) before the lock is created, read or removed.
* fix(cli): workflow commands in a workspace folder hold the workspace directory lock
A single-workflow apply, create or get inside workflows/<key>/ of a workspace
directory rewrites the workspace's written record and base, but took no lock, so
it could interleave with a workspace command (or another folder's) and lose a
record. These commands now hold the workspace directory's command lock for the
whole command, refused like a workspace command (SOURCE_DIR_BUSY, exit 10)
with nothing read or written.
* fix(cli): status recommends commands in its own scope, with --allow-delete for dropped data
The command workspaces source status recommended dropped the scope it was asked
for: status --only tables suggested an apply of every kind, and a status pointed
at a workspace with --workspace suggested one at the profile's. Every
recommended command now carries --only and, when the target is not the
profile's default, --workspace.
It also asked for --allow-delete only for whole-resource deletes, so an update
that drops a column was suggested without it and refused. It now uses the same
destructive count the apply prints.
* fix(cli): an apply that reprints a tool as stored() removes its old code file
When the server keeps a tool's code as stored() (it holds a credential), the
apply reprints tools/<key>.ts without tools/<key>.js, but saving the answer
left the old .js and its digest behind, so the next apply failed with
E_TOOL_CODE. Saving an apply now removes, from disk and the written record,
every text file the directory sent for a reprinted resource that the reprint no
longer holds (workflow folders keep pruning by lock).
* refactor(table): move cell value rules into @sim/workspace-code/table-cells
The per-type coerce/validate/salvage/equality rules, the row loops (required
cells, coercion policy, batch unique scan) and the pure date, currency, ttl and
select helpers move from apps/sim/lib/table into the workspace-code package
(timezone helpers into @sim/utils/timezone). The column-type registry spreads
CELL_RULES into each definition and validation.ts delegates, so there is one
implementation. The workspace source table adapter refuses declared rows with
refusedTableRows, which the CLI can now run offline.
* feat(sim-cli): workspaces source check validates table rows files offline
Each tables/<key>.rows.jsonl (managed or seed) is read against its declaration
and checked with the write's own rules (refusedTableRows): a malformed line, an
undeclared column, a managed key two lines share, an empty required cell, a
unique value two rows share, a value its column's type or options cannot hold.
Each is an E_TABLE_ROWS error at its line.
* fix(workspace-source): credential adoption never takes a credential from a key bound outside source
* test(workspace-code): assert linear growth, not a wall-clock budget, for hostile inputs
The file-grouping test asserted 20,000 deep paths group within 6 s and took 7.2 s
on a CI runner. It now counts the characters case folding reads at depth 100 and
400 (about 4x linear, 15x for the per-prefix fold it guards against), which no
machine load changes. The two compile tests with a 3 s budget (JWT pattern,
numeric precision) now compare the fastest of three runs at n and 4n: reverting
either fix gives about 15x against a bound of 9.
* fix(table): a seed reshape refuses a table that gained rows since the plan saw it empty
* fix(table): a keyed row write inside a reshape runs at the bulk-write statement timeout
* fix(workspace-source): hold the apply lease from before the plan, not only the writes
An apply planned before taking the lease, so another apply could write between
its plan and its writes: the first then wrote half of itself and failed
(E_NAME_TAKEN, E_APPLY_STALE), or deleted a resource a workflow had just
started using, because its in-use check had run before the other apply's save.
A non-dry-run apply now takes the lease first and plans and writes under it, so
a second apply is refused SOURCE_BUSY before it reads anything. This replaces
the post-lease in-use re-scan, which covered only deletes. Dry runs still take
no lease; the per-write lease confirm and stored-fingerprint re-checks stay for
UI edits, which the lease does not order.
* fix(workspace-code): literal-secret findings carry a span but no code frame
E_MCP_LITERAL_SECRET, E_DEPLOY_SECRET, W_TOOL_LITERAL_SECRET and the workflow
W_LITERAL_SECRET framed the line holding the secret, echoing it over v2 and MCP.
They keep their span; the finding cap and the server locator drop the frame too.
* fix(workspace-source): a secret declared without a description records no base entry, so it is never falsely stale
* test(workflow-code): time hostile inputs with Date.now, repeated past the clock's resolution
The package has no Node or DOM types, so performance is not declared. Each
growth timing now repeats the work until it spans 25 ms, so millisecond steps
do not swing the ratio.
* fix(workspace-code): an env reference or helper call is never read as an object
headers: env.TOKEN parsed with no finding into a header named $env, and
defineTable(column.string()) reported the encoding's $call/args fields. Both
now get one finding that names the value and how to write the object.
* feat(workflow-code): mixed-script block names, workflow inputs, env hint target
- E_LOOKALIKE_NAME also refuses a block name with a word mixing Latin with
Cyrillic, Greek, Armenian or Cherokee letters (Unicode script property, no
confusables table), naming the code point; W_ when the block is stored.
- startInputs and INPUT_TRIGGER_TYPES (shared with apps/sim) read a workflow's
Start trigger inputs; W_CHILD_INPUT_UNKNOWN and W_CHILD_NO_START join the
vocabulary for the CLI's offline child-call check.
- CompileInput.envDeclaredIn points a W_ENV_UNKNOWN hint at secrets.ts.
* feat(sim-cli): workspaces source check covers skills, child inputs and workspace.d.ts
- skill('<key>') is checked against skills/ like every other kind; a key with
a non-ASCII letter names its code point and script.
- A child workflow call is checked against the child's Start trigger in the
same directory (W_CHILD_INPUT_UNKNOWN, raised on new blocks; W_CHILD_NO_START).
- A get keeps the server's resource manifest beside workspace.d.ts, and check
regenerates workspace.d.ts from it and the directory's declarations, typing
new keys and each workflow's inputs without a request.
- Did-you-mean hints on E_MAT_UNKNOWN_RESOURCE, W_TABLE_UNKNOWN_COLUMN and
W_ENV_UNKNOWN (which points at secrets.ts); a warning raised to an error no
longer says it is kept as written.
- check --help lists every kind it checks.
* fix(workspace-code): check the option cap before a linear duplicate scan; pin a duplicate column to itself
A select's repeated-option scan was quadratic and ran before the maxOptions cap:
80k options took 7 s per parse (now ~0.1 s). E_TABLE_DUPLICATE_COLUMN spanned the
whole defineTable argument instead of the second column.
* perf(workspace-code): group a status's changed files in linear time; key server findings by code
localResourceChanges copied the kind's array per file: 40k files took 3.3 s.
SERVER_FINDINGS is now checked against WorkspaceDiagnosticCode.
* perf(workflow-code): print a fill in linear time by advancing an offset
printFill re-spread the remaining parts for every content/separator pair, so a
number-only array printed in quadratic time (40k numbers took 17.5 s). The rest
of the fill is now queued as the same parts from a later offset.
* fix(workflow-code): refuse a tool param or operation option the builder pins
A tool builder's fixed params and the operation option overwrote the method's
pin silently, so the tool stored an operation the method contradicts and printed
back as raw(). Report E_FIXED_PARAM, as the block path does.
* refactor(workflow-code): look a tool's builder up once
toolBuilderPath found the builder, returned its path, and compileToolCall looked
it up again behind an early return that could not fire.
* fix(workspace-code): cap knowledge document findings apart from knowledge.ts's own
Document findings were uncapped and counted against the field reporter's
100-finding budget, so the declaration's own findings became E_LIMIT_EXCEEDED.
The field reporter now counts only what it appends.
* fix(workspace-source): a workflow delete is fingerprinted only once its live triggers are counted
* fix(workflow-code): exclude a retyped block from rename inference by its own id
A retype matched by lock ident (or against a prev block the canvas renamed)
excluded the prev block under the new key, not the one it retyped, so another
new block of the old type could inherit the old id, its run history and its
webhook. Record the retyped prev id and exclude that.
* fix(workspaces): a key claim that loses a concurrent race refuses with 409 or retries, never a raw 23505
claimResourceKey read the key with select-for-update, but an unheld key has no row to lock, so a
concurrent get (allocation) or claim could insert first and the plain insert failed with a unique
violation on either index, surfacing as a 500. The insert now skips on conflict and the claim
re-reads the committed winner: kept, ResourceKeyTakenError, or a retry that replaces a key the
resource was allocated meanwhile. Rebinding deletes and re-inserts so it shares the same path.
* perf(workflow-code): push identity group keys instead of re-spreading the group
Each push copied the whole group, quadratic when many unmatched blocks share a
type and parent.
* fix(workflow-sdk): new on a runtime export throws SimSdkNotExecutable; one stub for both entries
The Proxy target was an arrow function, which has no [[Construct]], so the
construct trap never ran and new t() threw a TypeError. The workspace runtime
re-declared notExecutable and seven identical functions; both entries now share
the stub in not-executable.ts.
* feat(workflow-code): x.error compiles in the handler of an onError edge
The executor returns { error: <message> } as a failed block's output when an
error edge leaves it (BlockExecutor errorOutput, block-executor.ts:738-740,
returned at :868-877). Compile accepted no such path, so the INDEX promise of
${x.error} failed with W_UNKNOWN_OUTPUT_PATH. Now x.error checks once the edges
are known: accepted with an error edge, refused with a hint to wire onError
without one. Block<O> types error in the SDK, INDEX says how the handler reads
it, and the integrations cookbook shows it.
* fix(workflow-code): compile stored() in a loop or parallel's meta.extra
The printer writes a container param holding a detected credential as stored()
under meta.extra, but compileContainer passed no keep callback, so the print
failed to compile. Keep the stored value as a regular block's extra does.
* fix(workflow-sdk): never embed a dotfile from the cookbook
WORKSPACE_COOKBOOK embedded every file on disk under cookbook/workspace, so a
.DS_Store or editor swap file would be written into every user's example
directory. The listing now lives in embedded-files.ts, shared with the drift test.
* docs(knowledge): say why an upload's processing relay is safe on every surface
* perf(workflow-code): read each node's successors once in the cycle check
stronglyConnected called successors on every step of a frame, and the caller
maps the node's whole outgoing list each time, so a block wired to many targets
cost O(deg^2). Read them once when the frame is pushed.
* perf(workflow-code): test a restored inactive value with withStoredValue
staysInactiveWithPrev rebuilt the block's whole activity inputs (every param,
the modes, the ids deploy reads) for each inactive id on each pass. Build them
once per pass and swap the one value in, tracking the pass's restores.
* fix(workflow-code): keep collapsed on inputFormat fields whose id stays inline
Canonicalize drops the editor's collapsed flag from every field, but materialize
restored it only for fields whose id moved to the lock, so a field with a shared
or missing name lost it whenever the list changed.
* feat(sim-cli): no login exits 13 with AUTH_REQUIRED
Not logged in, an OAuth login that expired and cannot refresh, and a 401 from
the server exited 1 with CLI_ERROR, the same as a source with errors. They now
exit 13 (AUTH_REQUIRED_EXIT_CODE) with the code AUTH_REQUIRED (a 401 keeps the
server's code when it sends one). A status still falls back to the local view
without a login, and its note now reads as sentences.
* fix(workflow-code): write a subflow collection holding a $sim object back unwrapped
Canonicalize and compile wrap an object with its own $sim key as a literal node,
but materialize wrote forEachItems and distribution raw into block.data and the
loops and parallels maps, so after any config change the executor iterated the
wrappers. Unwrap literal nodes there, and say so in jsonField's TSDoc.
* fix(sim-cli): source diff filters resolve against --dir; cancellation and 413 keep their exit
- diff ./, an absolute path or a path from the current directory selected
nothing and printed "No local changes."; filters now resolve against --dir and
one that selects no file is refused (SOURCE_PATH_UNMATCHED).
- A cancelled request carries REQUEST_CANCELLED, so status no longer reports it
as an unreachable server; noAnswer() is the one copy of that predicate.
- workflows/workspaces source status and diff map a 413 to exit 7, as get does.
* fix(workspace-source): holding a change for one credential key keeps another key's unreachable refusal
* fix(sim-cli): an apply drops the written.json entries of the resources it deleted
The record kept every deleted resource's files, so status reported the delete
forever (exit 11) and recreating the key made get refuse with SOURCE_LOCAL_EDITS.
An entry is dropped only when its file is gone and the returned base no longer
holds the resource or blob, so a held or failed delete stays retryable.
* fix(workspace-source): a chat auth type source cannot name leaves the deployment out instead of reading as public
* perf(workflow-code): bucket wiring and order dependencies by scope once per print
Each scope's wiring rescanned the members of every enclosing scope and refiltered
their edges by edgeScope, and each scope's declaration order was handed every
dependency in the workflow: O(scopes x blocks). Bucket edges by the scope they
print in, and dependencies by the scope they order, in one pass.
* fix(workspace-source): file creates of one name check every key they may take, and a lost key claim refuses the create
* perf(workflow-code): memoize buildFieldIndex and group pair members in one pass
The index was rebuilt for every block in print and compile and for every tool,
and each canonical pair rescanned every subBlock for its members: O(pairs x
subBlocks) per call. Group the members once, and memoize the read-only index by
block, trigger mode and pinned ids.
* refactor(workflow-code): sort compiled edges with canonicalize's compareEdges
Compile kept its own copy of the comparator, and the CWM edge order is hashed
(canonicalHash), so two copies could drift.
* chore(workspace-source): unexport WorkspaceSourceChange, used only in its own file
* docs(workflow-code): move compileRegularBlock's TSDoc onto it
It sat above BlockShape's own TSDoc, documenting nothing.
* fix(workspace-source): the staging sweep removes objects before their rows, keeping a row whose object survived
* docs(workflow-code): describe LoopSpec as canonicalize reads it
The TSDoc said the spec is the loops map's config and that canonicalize never
fills defaults; loopSpec reads block.data first, never takes the map's count,
and falls back to a for loop of 5.
* refactor(workflow-code): stop exporting ConfigItem
Nothing imports it; it is only printedConfig's item type.
* refactor(workflow-code): read pinned values and the catalog block once
compileMetaParams rebuilt the map of every stored value once per pinned id, and
needsTodo looked the catalog block up twice though collectParams already holds it.
* fix(table): a reshape resolves each column update to its id, so a by-name swap renames both
* fix(workspace-source): a get leaves out a secret named __proto__ instead of printing an unapplyable secrets.ts
secrets.ts printed every stored secret, but the declaration reader refuses a
__proto__ key, so after a get the whole file stopped applying. The secret is
now listed in skipped.json with the reason; MCP header names the reader refuses
already round-trip-fail into skipped.
* perf(sim-cli): a status past one dry run prunes its whole read instead of walking the directory again
When the workflow folders exceed one dry run, status read the directory a
second time: a second walk, read and hash of every file. It now prunes the
unchanged folders from the read it already made.
* perf(sim-cli): workspaces source apply walks the directory once, inside its lock
assertWorkspaceDir walked every kind folder outside the lock before
readWorkspaceDir walked it again; the apply now checks the read it made and
runs the full check only to refuse. orphanedWorkflowFiles groups the answer's
paths by folder once instead of per lock, assertBaseWorkspace reuses
baseWorkspaceOf, and printPlan no longer shadows counts.
* fix(sim-cli): --only reads past an empty segment instead of refusing an unnamed kind
* refactor(workspace-code): un-export four unused types, name the skill locator apart from a line's offset, fix two TSDocs
* feat(workspace-source): an existing column becomes required in the same apply as the managed rows that fill it
* perf(workspace-source): list MCP servers' tools concurrently while planning tool references
* perf(workflows): a batched source read prints its workflows concurrently
* fix(workflow-types): hold a container's edges to the handle they leave from
A loop or parallel's start handle connects only into the container, and any other
handle never does. The shared scope rule ignored the handle, so the editing engine
kept a start edge to a block extracted from the loop (and an end edge to a block
moved into it): edges the canvas never draws and workflow source refuses
(E_EDGE_SCOPE), so such a workflow could not be applied back from its own source.
* fix(editing): refuse an error edge from a block with no error output
The engine accepted an 'error' handle on any block, so a trigger or a loop or
parallel container could store an error edge the canvas has no port for and
source cannot write (E_ERROR_PORT_UNSUPPORTED). It now follows the source
catalog's errorPort rule.
* fix(editing): normalize row ids only on fields declared as row lists
Row-id normalization keyed on the subblock id alone, so any field that shares an
id with a table field (supabase's JSON code 'params', 'metrics', 'headers',
'variables') was coerced to a row list: a JSON object or code text was replaced
by [] and the value lost. It now applies only where the block declares the id as
a row-list type.
* fix(workflow-code): keep the pair member a trigger-mode pair's mode does not select
Deploy reads every member of a trigger-mode pair, so the inactive-param restore
never brought back the member the mode does not select. An unchanged apply of a
block toggled into trigger mode dropped that member's stored value, and editing
the selected member dropped the other one. The pair's value is now its
mode-selected member's, and the other members keep their stored values, as on
the canvas.
* fix(workflow-code): write only the subflow config fields an edit changes
Canonicalize fills a loop's count (5) and the collection and conditions the
subflow map holds when block.data omits them; a changed config wrote all of them
back, so renaming the block a loop condition reads also stored count, collection
and condition fields nobody edited. Fields equal to the stored config keep their
stored spelling, absence included.
* fix(workflow-source): compile a block renamed in source against the block it continues
Compile matched the stored block by key, while materialize keeps a renamed
block's id through its ident (lock-ident). Renaming a block in source therefore
refused its stored() secret (E_STORED_VALUE_MISSING), turned a stored cycle into
E_EDGE_CYCLE, and reset fields source never writes (a note's color) to their
defaults. compileSource re-keys the stored model to the source's renames and
compiles again.
* refactor(sim-cli): name what source helpers do and fix their docs
- mergedGitattributes merges .gitignore too: withMissingLines.
- isMissing reads the code through errorCode, not a cast.
- workflows source check calls workspaceFolderOf directly.
- Exit codes 5, 6 and 7 document workspaces source as well.
- workflows source resources lists MCP servers; any source get writes it.
- Two TSDocs a reflow mangled.
* perf(workflow-persistence): read only live in-workspace graph rows in a batch load
loadWorkflowsFromNormalizedTablesRaw read every block, edge and subflow row of every requested id,
then dropped the ones outside the workspace, and kept archived workflows the read snapshot
discarded afterwards. Each graph query now filters by the live in-workspace ids as a subquery.
Measured on 100 live + 300 archived workflows of 30 blocks: loadWorkflowReadSnapshots median
579ms -> 151ms.
* perf(workflows): one credential lookup for a batch load's block migrations
loadWorkflowsFromNormalizedTables ran each workflow's block migrations serially inside the
REPEATABLE READ snapshot, and the credential-id migration queried once per workflow holding a
legacy account id. The batch now prefetches the credential ids for every workflow's legacy ids in
one query, and only queries again for an id a migration surfaces that the prefetch did not ask
about, so the result is unchanged: N serial round trips become one.
* fix(api): one ETag revalidation path; tagged v2 bodies are revalidated, and cached per request
- ifNoneMatchSatisfied was copied in the internal and v2 JSON builders; definition.ts now owns
entityTagMatches and notModifiedResponse.
- The v2 builder answered a tagged 200 and its 304 with private, no-store, which forbids keeping
the body the ETag exists to revalidate. Both now say private, no-cache, as the internal one did.
- The v2 validated-body LRU was keyed by the tag alone and served across principals and inputs,
though present() reads the parsed request. It is keyed by tag and parsed request now, and
entityTag documents that it must be a strong validator of the result for every caller.
- The internal builder's HEAD branch re-checked a missing authorize() that definition-time
validation already refuses; it captures the authorize phase once instead.
* fix(workflow-sdk): codegen uses its layout helpers; INDEX.md lists legacy builders only when there are some
- generate.ts builds block, models and index paths from layout.ts; blockTypesFile
leaves the barrel; layout.ts reads TOOL_NAMESPACE.
- @when names both fields of an and clause.
- typecheckSdkDirectory spreads SOURCE_COMPILER_OPTIONS.
- The cookbook declares ORDERS_API_KEY, which its tool reads, and says a new
query string updates an MCP server in place; column.ttl() says one per table.
- Doc fixes: arrayOf, declaredBlockTypes order, core.d.ts names tsc.
* fix(schedules): a written zero is an invalid schedule field, not a missing one
The reason classifier read fields through getSubBlockValue (value || ''), so a numeric 0 counted
as empty. It now checks undefined, null and '' explicitly.
* docs(environment): state the non-empty invariant both env paths share
* chore(scripts): name the pure package an offender is in, not always workflow-code
* refactor(chat-deployments): one identifier-ownership check, and one live-chat read per replace pre-check
* refactor(workflows): the code tab names its directory with the shared slugify
* refactor: keep types no other module imports private
* refactor(workflows): drop the field-by-field source apply presenter
The response schema already strips the result's internal fields, so both routes present the
result as it is.
* refactor(workspace): the workflow-code flag is required of every flags producer
* refactor(utils): one mapWithConcurrency, with documented failure semantics
apps/sim had its own mapWithConcurrency next to @sim/utils/concurrency's, with different failure
semantics: it rejected through Promise.all as soon as one item failed while its other workers kept
starting items nobody awaited. Every caller now uses the @sim/utils one: after a failure no item
starts, and the first failure is thrown once the running items settle, so nothing the batch began
is still running when the caller handles it. mapSettledWithConcurrency (attempt every item, keep
each outcome) moves alongside it. createConcurrencyLimit, MATERIALIZE_CONCURRENCY and
waitWithAbort stay in apps/sim.
* perf(workspace-source): a knowledge plan never downloads a document named in neither the base nor the directory
* docs(workspace-code): CI commits back what apply rewrote, tsc step, Gmail provider
- The scripting.mdx CI job runs tsc after check (which regenerates
workspace.d.ts), and on merge commits back the files the apply rewrote, with
[skip ci] and contents: write; a protected branch opens a pull request instead.
- workspace-code.mdx says what check now covers (skills, child inputs, rows,
workspace.d.ts).
- The cookbook credentials.ts shows Gmail's provider id, google-email (the id
apps/sim/lib/oauth/oauth.ts registers for Gmail).
- The docs baseline records the changed CI fence.
* docs(cli): regenerate the CLI reference for the check help and exit 13
* test(api): the source catalog's tagged 200 is private, no-cache
* fix(workspace-source): a renamed or name-taken stored() tool reports only that, not a missing stored tool
* fix(workspace-source): a deleted chat's base no longer records its password variable
* fix(table): reshape audit entries name columns, never their ids
* refactor(workflows): drop the never-filled SourcePlan.notes, share the stale message, and read a rename's folder from the loaded workflow
* refactor(source): one managed-row key, one tool-input field list, and no unreachable fallbacks
* docs(source): gated manifest sections, the required-column 400, carried tags and the manifest limit
* chore(source): regenerate the v2 OpenAPI and MCP operations for the documentation changes
* test(workspace-code): bound the option-cap and status-grouping fixes by n vs 4n growth, not wall clock
The ratio helper is exported from @sim/workflow-code/scaling.test-helpers so
other packages' scaling tests share it.
* fix(workflow-code): x.error is a string in a JSON field
The executor's error output is the failure message, so a reference to it in a
JSON body (response, API body) is stored quoted, as compile and print decide
through refValueKind; bare, a message would break the JSON.
* refactor(workspace-code): rowKeyText reads any cell value, so the table row writer shares it
* chore: drop the apply wire type no module reads, and shrink the non-null baseline the batch load cleared
* test(workspace-source): the cookbook apply test holds the Gmail credential the cookbook declares
* fix(workflow-code): keep a stored field the printer left out as inactive
Compile fills an omitted param with its default, then keeps the stored value only
when the field is inactive, judged with the default in place. A standalone
advanced field runs once non-empty, so a stored '' choice (cloudflare's 'Active
only' certificate filter) read as active under the default and every apply
replaced it with 'all'. Inactivity is now judged with the stored value.
* refactor(utils): point the merged mapWithConcurrency callers at @sim/utils
* test(workflow-source): prove canvas, JSON API and source stay in lockstep
A seeded fuzz applies random sequences of real editing-engine operations (add,
delete, move, edit fields, connect, disconnect, insert into and extract from
loops and parallels, rename, enable, retype, trigger and advanced mode, loop
config, variables) to corpus workflows, then asserts the source of the result
applies back as a no-op and one random source edit changes exactly that field.
Failures shrink to a one-minimal edit list. Every registry block type is added
(or, for legacy and single-instance types, edited) with non-default values in
each subblock kind it has. Each divergence fixed on this branch keeps a minimal
regression. The integration suite runs the full stack on Postgres: JSON write,
editing operations, source get and apply, JSON read, and a canvas-built workflow
against the one created from its source.
* chore: drop exports the cell-rule move left unused; move the timezone baseline entry
* chore(audits): count staging's new integration double-cast in the merged ratchet
* test(workflow-source): satisfy the audits in the fidelity suites
* test(workspaces): wait with the shared sleep helper
* fix(cli): recover a command lock abandoned before its owner was recorded
The takeover claim inside the lock refreshed the lock folder's mtime before
the staleness re-check, so a lock with no owner.json never read as stale and
every command returned SOURCE_DIR_BUSY. Judge an unrecorded lock's age from
the sighting taken before the claim, and guard against a replacement lock by
checking the folder is still the one seen (dev/ino) and still stale.
* chore(helm): bump chart to 1.11.22 for the source-staging cleanup cron
* fix(workspace-source): match managed row keys after their column's coercion
planRows compared declared key cells with stored ones before coercing them,
so a number key written as "007" counted the stored row 7 as removed and the
apply refused without --allow-delete, though the keyed write coerces "007"
to 7 and matches it. Coerce the declared key with the key column's cell rule
(the reject policy a keyed write uses) before matching.
* fix(workflow-code): print a JSON code field in meta.extra as its stored text
An advanced JSON code field the serializer still forwards under an operation that
hides it prints under meta.extra, which compile reads verbatim. It printed as an
object literal, so compile stored a native object and an unchanged apply rewrote
the stored text (minified, or not at all equal when it held references). It now
prints as text there; only a builder param takes the literal form.
* fix(workflow-source): keep a block keyed __proto__ in the lock and hints
buildLockFromState, hintsFromSourceMeta and printStoredSource assigned by bracket,
so a block whose name normalizes to __proto__ set the prototype instead of an
entry: it vanished from the lock, and renaming it in source lost its identity
(compile treated it as new and reset its unwritten fields).
* test(workflow-source): regressions from the long fidelity run
A JSON field forwarded under a hiding operation, a block keyed __proto__, and the
by-design collision-key refusal the fuzz now leaves out.
* fix(cli): workspaces source status and diff refuse a directory holding no workspace source
A mistyped --dir, an empty directory, the wrong working directory (--dir
defaults to .) or a workflow folder read as clean: status exited 0 after a
dry run of no kinds, and diff printed "No local changes.". They now refuse
it with the reason and the get to run, as apply and check do.
* fix(cli): status recommends the get that restores a removed kind folder, not an apply
Removing a managed kind's folder or root file (tables/, secrets.ts) stops
managing the kind: an apply leaves its resources alone. status reported its
recorded files as deleted and recommended apply --yes, which wrote nothing, so
the next status said the same thing again (exit 11 forever) while get refused
to write the files back. When every local change is in such a kind, status now
recommends get --only <folders> --force, which restores them, and says how to
delete the resources instead.
* fix(utils): mapWithConcurrency throws the first failure in time
The shared helper threw the failure of the lowest-numbered slot, so a slow
slot-0 error masked an earlier one from another slot. The apps/sim helper it
replaced (Promise.all) threw the first failure, and the TSDoc still promises
that.
* fix(cli): workspace source commands handle a directory no one may write
Every workspace source command takes the directory's lock by creating
.sim/command.lock, so in a read-only checkout status, diff and apply --dry-run
crashed with a raw EACCES stack trace. Commands that only read (status, diff,
a dry run) now run without the lock there, since nothing can rewrite the
directory; get, check and apply are refused as SOURCE_DIR_UNWRITABLE with the
reason.
* fix(cli): status refuses a broken .sim/written.json instead of calling every file created
A merge conflict that leaves markers in .sim/written.json (two branches that
each applied) made status read every file as created and recommend an apply.
It now refuses with SOURCE_WRITTEN_INVALID and names the get that rewrites the
record. A broken .sim/base.json names its way out too (SOURCE_BASE_INVALID).
* docs(cli): status and diff help name exit 7, and the workflow guide exit 13
status and diff exit 7 when the server refuses the source as too large (413),
as exit-codes.ts documents, but their help listed only 0, 11, 12 and 1. The
workflow directory's .sim/AGENTS.md now names exit 13 (not logged in) as the
workspace guide does. CLI docs regenerated.
* fix(executor): splice already-escaped values into JSON strings as written
Escaping every reference landing inside a JSON string literal fixed values that
broke the JSON (quotes, newlines, stray backslashes), but it also re-escaped
values that were already valid string content. A deployed workflow whose env
var holds a key with literal \n escapes, or that escaped a value in a Function
block to work around the old bug, now sent backslash-n instead of a newline.
Only a value that would break the literal is escaped now; one that is already
valid string content splices raw, exactly as before.
* fix(table): write every row's cancellation when one write fails
cancelWorkflowGroupRuns cancels every row's queued jobs, then writes each row's
cancelled status. The shared mapWithConcurrency starts nothing after a failure,
so one failed write left the later rows of the page 'running' with no job behind
them; the apps/sim helper it replaced still wrote them. The writes now all
settle before the first failure is thrown.
* fix(cli): count a workflow changed only on the server as unchanged in workspace status
The status dry run sends every workflow folder whole to detect drift, so the server plans an
update for a folder edited only in Sim. An apply sends that folder by its base and leaves it
unchanged, so the status plan line said 'Applying would: 1 update' for an apply that changes
nothing.
* fix(cli): an interrupted source command releases the directory lock
Ctrl-C during a workspace source command left .sim/command.lock behind. A
later command takes a lock over only when its owner ran on the same host, so
one left in a folder shared with a dev container or another machine stayed
until removed by hand (exit 10 every time). The lock is now removed on
SIGINT/SIGTERM before the signal ends the process, as a staged write's folder
already is.
* test(workspace-source): a key-claim failure trigger left by a killed run no longer breaks the next one
* fix(e2e): expire the workflow source e2e session in UTC
session.expires_at is a timestamp without a zone that the app reads as UTC. now() writes the
database's local time, so on a Postgres west of UTC the one-hour session was already expired
and the canvas-route check got 401.
* fix(cli): get keeps a directory bound to its workspace when its base does not parse
get decided which workspace a directory belongs to only from a base that
parsed cleanly, so one this CLI refuses (a field a later CLI added, a bad
fingerprint) read as no base: get then used the profile's workspace, and
--workspace naming another one was not refused (SOURCE_OTHER_WORKSPACE). It now
reads workspaceId as leniently as apply and status do.
* fix(cli): print nested source apply results as JSON in text output
`sim workflows source apply --output text` printed the modified blocks as
`modified [object Object]`.
* test(workflow-code): alternate small and large runs in the growth check so machine load slows both sides
* fix(workspace-source): in-use scan reads the live deployment version
A delete of a resource that a deployed workflow's live version still uses,
while its draft no longer does, now warns W_RESOURCE_IN_USE naming the
live version, unless the same apply publishes the draft or undeploys it.
* fix(workspace-source): class a refused apply by the errors that refuse it
The rejected error counted and classed every error, including those of
changes the plan holds back, which refuse nothing. The plan now returns
the refusing errors (plan-level plus non-held changes) and the error
classes from those.
* fix(workspace-source): a key taken after a committed write reports the write
A key claim that found the key held by another live resource after the
write committed threw, dropping the written resource from applied. write()
now returns it with E_NAME_TAKEN; the apply records it as applied, keeps
the base entry unchanged, and stops so no later write resolves the key to
the other resource.
* test(workspace-source): per-process source slot refuses past its cap with 429
* fix(cli): check table row columns when the row holds a non-string reference
Compiled row data stores a non-string reference bare ("n": <score.value>), which JSON.parse
refuses, so check skipped the whole row: an unknown column or select option in any row writing a
number, boolean or object output went unreported. Parse it as a JSON field instead.
* feat(workflow-code): hint api for http.request and fn for javascript.* builders
An agent guessing the HTTP request block as http.request got E_UNKNOWN_BUILDER with no hint:
no edit distance reaches api.
* docs(workflow-code): correct workspace-key, rows, written.json and create claims; fill agent-guide gaps
- credentials bind with a workspace API key; secrets and deployments do not (guide, CI docs, API description)
- table rows are source when a table opts in; list rows.jsonl and the limits
- .sim/written.json is committed, not gitignored; drop stale tsc sizes; exit 9
- a created-not-yet directory has no base: create --dry-run, not status
- guide: api is the HTTP block, W_* print as error in check, self-hosted apiKey, promote setup
* test(workspace-source): a key-claim failure trigger left by a killed run no longer breaks the next one
* test(workflow-code): alternate small and large runs in the growth check so machine load slows both sides
* test(workflow-code): time the block-cap round trip by thread CPU, so machine load cannot fail it
* fix(workflow-code): never print a credential through the response body form
The response(name, { body, status, headers }) form printed its fields'
stored values verbatim, so a response block holding a detected credential
(an Authorization header, a token in the body) printed the secret into the
file while W_LITERAL_SECRET claimed it printed as stored(). Such a block now
keeps its own params, where the field prints as stored(), and compile warns
W_LITERAL_SECRET when source writes one in the form.
* fix(workflow-code): check agent tool calls the way blocks are checked
compileToolCall accepted any builder as a tool (api.tool, condition.tool,
trigger.gmail.tool.poller), stored any param key unchecked, and never warned
about a literal secret, though print writes these tools as raw(tool) and
warns W_LITERAL_SECRET. A tool call now needs a builder with a tool form
(E_UNKNOWN_BUILDER), each param must be one its tool type declares
(E_UNKNOWN_PARAM with a did-you-mean, W_FIELD_NOT_APPLICABLE for another
operation's), and a literal secret warns as on a block.
SYNTAX.md and core.d.ts no longer document agent.tool() or
runWorkflow.tool(): neither is typed, and print writes such tools as
raw(tool).
* fix(workflow-code): refuse stored() and codeFile() in a loop or parallel config
compileConfig dropped any config value that was not a plain value, so
loop.forEach('L', { collection: stored() }) or a codeFile() condition
compiled silently to a loop with no collection or condition. Both are now
E_UNSUPPORTED_SYNTAX with the form to write instead.
* fix(workflow-code): give every compile finding a hint that names its fix
E_TARGET_TRIGGER, E_ERROR_PORT_UNSUPPORTED (a loop or parallel has none:
wire onError from its children), E_UNKNOWN_BRANCH in meta.branches (lists
the branches), W_VALUE_KIND (the literal form the field takes) and
E_UNKNOWN_IDENTIFIER for undefined, NaN and Infinity had no hint. The test
catalog's loop and parallel now have no error port, like the real catalog.
* fix(table): keep batch rows that keep a unique value in the DB check
batchUpdateRows excluded every batch row from each unique column's DB check and
compared the rest by the values it read before taking the value locks. A row the
batch leaves alone could take the value from a concurrent edit after that read,
so both it and the batch's writer stored the same unique value. Each column's DB
check now skips only the batch rows that rewrite that column.
* docs(tables): say add-column refuses a required column rows leave empty
* fix(cli): Ctrl-C during an apply write names what it may have done
An interrupt while the apply request was in flight exited 130 silently, so
nobody learned the write may have landed. The lock's interrupt handler (which
already releases the lock) now prints the same next step a lost answer gets,
then ends with the signal.
* fix(cli): a status without a login recommends sim login
With no login on the profile, status shows the local view (the server is
treated as unreachable) and its note says to log in, but next was
apply --dry-run, which only exits 13. next is now the login, then status again,
for workflows and workspaces alike.
* fix(cli): check offline with no cached catalog names the get that caches it
A fresh clone checked while the server could not be reached failed with the
raw "Could not reach …" and no next step. It is now CATALOG_NOT_CACHED (exit
1) naming sim workspaces source get, as a check with no credentials already
is; no login keeps its AUTH_REQUIRED refusal (exit 13, naming sim login).
* fix(workflow-code): keep meta.retry within the bounds the loader pins it to
Persistence saves a retry policy verbatim but loads it clamped (2-5 tries,
0-5000 ms, whole numbers), and canonicalize kept a well-formed policy raw.
A file writing maxTries: 10 stored 10, read back as 5, and every re-apply
of the unchanged file showed a retry change. Compile now refuses an
out-of-range policy with a hint naming the bounds, and canonicalize pins
the numbers as the loader does, so a printed policy always compiles back
unchanged.
* Revert "fix(workflow-types): hold a container's edges to the handle they leave from"
This reverts commit
|
||
|
|
d8d7c8cc77 |
improvement(credentials): resolve agent fallback credentials once, Vanta 401 grace, true refusal codes, headless client-credential modes, and registry cleanups (#9977)
* improvement(credentials): resolve agent fallback credentials once, Vanta 401 grace, true refusal codes, headless client-credential modes, and registry cleanups * fix(credentials): name refused hosts in token responses and drop the S3 saved-credential setup flag |
||
|
|
9c1857cf02 | fix(executor): resolve saved model credentials inside each fallback attempt in Router and Evaluator (#9968) | ||
|
|
e5af3243af |
feat(knowledge): let the S3 connector sync with a saved AWS credential (#9934)
* feat(connectors): sign S3 connector requests with a seeded AWS session The S3 knowledge connector can now sign with keys a saved AWS credential resolved to, read from the run's syncContext. STS session tokens are sent as x-amz-security-token and included in the SigV4 signed headers. A saved credential signs only for Amazon S3 in an AWS region: a custom endpoint is refused so an AWS session never reaches an S3-compatible host. Inline keys sign exactly as before. * feat(knowledge): let a key connector sync with its declared saved credential A key-based connector may now declare a saved-credential alternative (auth.savedCredential); Amazon S3 declares a saved AWS credential. A row that names a credential resolves it for the knowledge base's own scope through the same owner check and STS exchange AWS tools use, and the resolved session is seeded into syncContext. Rows that store a key keep using it, and key-only connectors are unchanged. - connectorUsesCredential/connectorHasAuthSource decide the auth source in one place for the resolver, sync engine, validation and setup. - resolveConnectorAccessToken takes the knowledge base scope. - A run token reuses an STS session until shortly before it expires and re-seeds syncContext when it is replaced. - Setup with a saved credential is gated by the global knowledge-connector-saved-credentials flag: workers from an earlier release read a key connector without a key as credential-removed and unschedule it, so the flag stays off until the release is live on the app and Trigger.dev. - The connector catalog and v2 contract gain optional savedCredential and apiKeyOnly fields; generated OpenAPI, CLI API and CLI docs updated. - Adds a central mock for @/lib/internal/aws/credentials. * feat(knowledge): offer a saved AWS credential when setting up an S3 connector When knowledge-connector-saved-credentials is on, the add-connector modal lets Amazon S3 authenticate with a saved AWS credential instead of its access keys, hides the key-only Access Key ID and custom endpoint fields, and never sends values typed into them. The edit modal keeps the credential replaceable for a connector that syncs with one, including after its credential was removed. Inline keys stay the default. * docs(knowledge): describe the S3 connector's saved AWS credential option * fix(knowledge): refuse moving a stored-key connector onto its saved credential The access update accepted a credentialId for a key connector that still stored its key. The key stayed on the row and took over again, silently, once the credential was deleted. Switching auth source now means creating the connector anew, as it did before saved credentials. * fix(knowledge): classify saved AWS credential failures and labels consistently - Share the AWS failure message and transient check with the AWS tools, so STS throttling or an IdP outage during setup is no longer a 400. - Refuse another service's credential on S3 creation, as access updates do. - Return an empty access token for a saved AWS credential, not its id. - Record saved-credential connectors as authMode savedCredential in audit. - Narrow savedCredential.provider to aws, the only provider that resolves. - Derive create's key-vs-credential choice from connectorUsesCredential and rename the run-token refresh. * fix(connectors): sign saved AWS credentials only for commercial and GovCloud S3 China regions serve S3 under amazonaws.com.cn and the isolated partitions under their own domains, so a saved credential for them failed with an opaque DNS error. Refuse them with a clear message instead. * docs(knowledge): state saved-credential availability and rollback limits Catalog and connector credentialId descriptions say saved credentials work once the deployment enables them, the connector credentialId field covers saved credentials, and the flag notes that a release rollback is unsafe once any connector uses one. Regenerates OpenAPI, CLI API and CLI docs. * fix(knowledge): redact saved AWS session secrets and share the credential service check A saved AWS credential resolves to an empty bearer with its secret key and session token in awsSession, so redacting accessToken alone left them in provider validation text. Both validation sites now redact every secret the resolved token carries (connectorTokenSecrets). Setup and access updates now share requireConnectorCredentialService, so a key connector's saved-credential setup refuses a missing service config instead of skipping the provider check. * fix(knowledge): keep long-lived saved AWS keys per run and gate saved-credential edits on rollout - Reuse a saved AWS credential without a session token for the whole run instead of reloading it on every page and hydration - Hide the edit form's saved-credential replacement while saved-credential setup is disabled, matching the server gate - Classify a connector whose credential service has no config as internal, not caller-fixable - State in the v2 catalog that apiKey connectors with savedCredential accept credentialId * docs(knowledge): describe the saved-credential provider as a service, not an OAuth service * test(llm): mock AWS credentials through the central @sim/testing mock |
||
|
|
9b58238790 |
fix(api): release-audit follow-ups for the agent API work (#9910)
* fix(api): name the failing field once in v2 validation errors A message that already leads with its field label no longer repeats it after the location prefix, and the CLI restates the prefix as the flag the caller typed instead of rewriting it to query.--flag. * fix(api): call the v2 error id requestId The id in error bodies is the request id that x-request-id carries and logs store as requestId; traceId already means the OTel trace id in logs, so a search by the published value found nothing. * fix(api): describe what the workflow outline actually omits Only null values are dropped, every sub-block hidden from agents is dropped (some are real configuration), and blocks whose parent container is gone are left out, so point readers at Get workflow state for the full configuration. * fix(api): prove the workspace schedules list against Postgres Adds an integration suite for listWorkspaceLiveSchedulesPage: it returns the rows the per-workflow live list reports, leaves out archived, undeployed and other-workspace workflows, and pages through createdAt ties without repeats or gaps. sortBy=createdAt now says that each deploy creates new schedule rows. * chore(skills): include the optional requestId in the v2 error shape * fix(cli): pick the handoff for --expires-in and name a refused key sim login --expires-in without --method failed on servers that offer OAuth, because OAuth was chosen and then refused the flag; a lifetime now selects the API-key handoff. A refused handoff key no longer says nothing was stored: it already exists on the account, so the CLI points at how to revoke it. * fix(api): publish the workspace logoUrl pattern without a lookahead RE2-based validators (Go, Rust, many gateways) reject lookaheads, so the OpenAPI pattern for logoUrl could not be compiled there. The rewrite accepts and refuses exactly the same values. * chore(cli-auth): drop the poll-body half of a test that could not fail The poll contract strips unknown keys and the route never reads them, so sending access and expiresInDays in the body proved nothing. The test keeps checking that the approval's access and lifetime reach the mint. * fix(workflows): refuse withheld blocks before the operations lock applyWorkflowOperations now hands the persistence primitive a reader, which skipped its pre-lock withheld-block check, so a refused batch took the row lock and re-read the graph first. The use case checks the graph it composed before writing. A failed re-read under the lock is now an internal error instead of a 400 saying the workflow has no state. * chore(api): document the CONFLICT 409 from Apply workflow operations * improvement(workflows): prove the operations conflict guard against Postgres Holds the workflow row lock to force each interleaving: an unchanged workflow with containers and a migrated legacy block commits, a write that lands after the base read is refused as a conflict, and of two concurrent applies one commits and the other is refused with nothing lost. * chore(api): tighten comments and the field-label check from review * fix(cli): name a refused handoff key exactly The poll response now carries the minted key's name (an additive, optional field), so the CLI tells the caller exactly which key in Settings → API keys to revoke, falling back to the key id for an older server. Restores the route context argument the trimmed poll test dropped. * fix(workflows): run the conflict-guard races on their own connections The applies and the lock-wait poll started inside the lock holder's transaction callback, so the transaction tripwire refused them. They now leave that context, the applies run in a permission-group scope as routes do, and an apply that settles early is reported without awaiting the ones queued on the held lock. * chore(cli-auth): declare the poll key name the server always sends * fix(workflows): count lock waiters queued behind another waiter A second FOR UPDATE waiter queues on the first waiter's tuple lock, so pg_blocking_pids names that waiter rather than the holder; the barrier now walks the chain. * fix(cli): probe the endpoint before an --expires-in handoff --expires-in without --method chose the handoff before the reachability probe, so a mistyped endpoint printed a pairing code and polled instead of failing fast. The probe now runs first. A refused key from a server that does not report its name is described by the name pattern and time it was made. |
||
|
|
3d8996f0e6 |
feat(api): workflow outline, workspace schedules list, clearer v2 errors, and catalog value types (#9905)
* feat(api): add traceId and field paths to v2 errors, name the read-only key remedy * feat(api): publish declared value types on block catalog fields * feat(api): add workflow outline and workspace schedules reads to v2 * fix(api): type declared catalog inputs as block params and regenerate the docs manifest * fix(api): compare member responses without their per-request traceId * improvement(api): tidy catalog field projection default and integration test comment * docs(api): say the outline's derived fields come from values state already returns |
||
|
|
02293a9372 | feat(api-keys): read-only API keys and expiry at creation (#9855) | ||
|
|
ff98c86570 |
feat(knowledge): import knowledge base bundles through the API and sim knowledge import (#9327)
* feat(knowledge): import knowledge base bundles through the API and `sim knowledge import` - v2 knowledge imports resource (create, part URLs, complete, get, cancel) over a new knowledge_import upload purpose - background runner recreates the base, tags, and documents from an exported bundle; reuses vectors when the embedding model matches and queues re-processing otherwise - knowledge_base_import job table with a stale-import janitor sweep - `sim knowledge import <bundle.simkb.zip>` plus `knowledge imports get/cancel`, and an import guide - shared dispatchBackgroundTask helper for Trigger.dev-or-in-process task dispatch * fix(knowledge): validate bundles before writing, close import cancel and cleanup gaps, and fix CI - read every chunk entry before the base is created, reject reversed offsets, and length-check vectors before decoding - confirm the import is still running before creating the base, and remove it if a cancel wins - record the import inside upload completion, so a refusal or crash cannot strand the bundle; re-read on a concurrent completion - serialize progress writes, keep the source character count, cap rebuilt text, and recheck uploads when issuing part URLs - janitor fails in-process documents a dead worker left processing, and deletes bundles when pruning settled imports - shrink the unused-exports baseline, count the new janitor passes in its test, and fix the integration test's Blob typing * fix(knowledge): re-dispatch an import whose first dispatch was lost, and remove a base whose tag setup fails - the base takes the import's id and a worker claims the import before working, so a second dispatch exits untouched - a retried completion dispatches again an import no worker has claimed - a worker that finds its import settled before any claim deletes the unused bundle - tag-definition setup that fails removes the still-empty base * fix(knowledge): keep a failed dispatch from stopping a live import, audit each import once, and close review gaps - a dispatch never settles the import itself; a retry or the stale-import janitor does - projected audit entries take an idempotency key, recorded through recordAuditOnce, so a retried completion audits the import exactly once - a cancel that races completion stops the record the completion wrote - refuse empty rebuilt chunk-only documents; knowledge_base_import.user_id references the user * fix(knowledge): keep import records through account deletion, and recheck uploads on re-dispatch - knowledge_base_import.user_id is attribution only, so the janitor's cleanup record outlives its importer's account - re-dispatching an unclaimed import repeats the knowledge.upload assertion * fix(knowledge): audit an import as started, and drop the mock-only dispatch test - the completion records knowledge_base.import_started; the base exists only once the runner creates it - background-task.test.ts only checked forwarded mock arguments; the delete-async route test and the integration suite exercise the helper's real paths |
||
|
|
fd4323a7ae |
improvement(docs): refine screenshots, copy, and API interactions (#9269)
* improvement(docs): refine screenshots, copy, and API interactions * fix(docs): preserve icon gradients and refresh generation inputs * fix(docs): keep OAuth setup prerequisites visible |
||
|
|
2676575f21 |
improvement(docs): standardize copy and responsive navigation (#9020)
* docs: standardize copy and page organization * docs: preserve tab spacing and qualify output limits * docs: align responsive navigation and preserve readable content * docs: link the scoped tab component in agent guidance * docs: preserve procedural details and correct reference examples * docs: record final review and preserve accessible provider bookmarks * chore(docs): finish ship review and update audit evidence * fix(docs): correct review findings and tablet header alignment * fix(docs): polish API controls and inline code * fix(docs): announce API picker selections * fix(docs): expose checked API picker choices * test(ui): align single-choice picker locators |
||
|
|
de95f24e55 |
improvement(api): declare OAuth scopes in OpenAPI, JSON 404s for unknown API paths, and root MCP resource metadata (#9026)
* improvement(api): declare OAuth scopes in OpenAPI, JSON 404s for unknown API paths, and root MCP resource metadata * fix(api): shrink the unused-exports baseline and keep rewrite checks out of the dev-server e2e |
||
|
|
684b228623 |
feat(api): expose credential sharing and SSO administration (#8770)
* feat(api): expose credential sharing and SSO administration * fix(api): make SSO administration atomic and align CLI actions * fix(auth): align SSO admission locks and reject stale provider links * fix(auth): serialize domain administration and align SSO validation * fix(auth): preserve SSO audit events across application operations |
||
|
|
e919e4cf2d |
fix(mothership): follow-ups for v1.0.0 regressions (#8215)
* fix(execution): resolve stored file references only for workspace members Workflow file inputs can reference stored files by id, key, or internal URL, and every resolved file is added to the run's explicit file grants. Any caller could use this, so an anonymous public-API, public MCP, chat, or webhook caller could pull another workflow's run files or workspace files into a run and receive a presigned URL for them. Execution now derives a stored-file reference scope from the run's principal: authorized member principals (session, personal/workspace API key, OAuth token, delegated) resolve workspace-wide; system principals may only reference files already stored under the current execution, which keeps chat and webhook uploads working. The default is the restricted scope, so a new caller fails closed. Input-format defaults are workflow-authored and still resolve workspace-wide. Outside workspace scope, an upload whose URL is an internal file URL is resolved as the stored reference it names rather than downloaded with the run user's access, and a key from another execution is refused before it is looked up, so the refusal does not reveal whether the file exists. * fix(mothership): withhold unregistered table secrets from sim_cli results Table rows read through sim_cli reached the model without their persisted secret provenance, so stored secrets in cells were never redacted. Row use cases now report the provenance of the rows they return to an observing transport (mirroring the workspace-file delivery observer), and the agent CLI table transport imports it into the tool call's registry, answers 503 without a registry, and marks the registry incomplete when a row-bearing table route returns without reporting provenance. Provenance reported by detached work after the call settles is ignored. Export download links are refused outright: a signed link to the whole table as plaintext CSV cannot carry provenance once fetched. Run-state and enrichment error text (runState.error, blockErrors, enrichment provider errors) is captured from executor output without its secret provenance, so a read that returns any of it is withheld as well; reads whose run state carries no error text are unaffected. * fix(search): run live Calendar service search on the crawl scope PR #8208 widened Google Calendar's domain-wide delegation scopes to include calendar.readonly for every service-account token. Google refuses the whole token exchange when any requested scope is not authorized for the client, so indexed admin-mode Calendar syncs configured for calendar.events.readonly failed every run and were eventually disabled. Live service search only needed the wider scope to read an all-day event's calendar time zone. events.list returns the calendar's timeZone under calendar.events.readonly, so live search now reads it there and delegates with the same single scope as the indexed crawl, matching Drive and Gmail. The admin calendar picker keeps its own calendar.readonly request, as documented. * fix(search): keep results painted when Show more widens the page * fix(chat): use the defined brand token for the resource activity dot * fix(knowledge): document connector auth in the v2 contract and reject $NAME secrets * fix(mothership): resolve Copilot env-reference passwords for chat deploy and file share Copilot now deploys chats and shares files through the v2 API, which stored a whole-value {{NAME}} password literally (or 400'd a short one on length). The application use cases now resolve the reference from the effective environment when, and only when, the caller is an admitted Copilot workspace invocation and the password will actually be stored (password mode; for a file share, only while enabling it), refuse an unset variable by name, and hold the resolved value to the password rules. Every other principal keeps literal semantics. The v2 password fields admit a whole-value reference below the password minimum as one refined string (not a union, which would make the CLI flag JSON-only), still capped at the password maximum; the use cases enforce the 15-character rule on the value actually stored. Connector API-key references share the same principal environment lookup, and the exact reference regex now lives in one module. Unlike the removed Copilot tool path, the resolved password is not recorded in a resolved-secret trace registry: the v2 use case has none, and the password is write-only and never echoed back. |
||
|
|
f734ba5be2 |
feat(mothership): v1.0.0 (#8208)
* mothership agent cli: grep --in accepts the world/resource path a match line prints
* workflow lint, block catalog, tables, files, sandbox tools: fixes from exploration run 5
Lint: trigger-category blocks are entry blocks (schedule was an orphan); references inside Function code are checked with the runtime tokenizer; the agent-cli lint and grep read the draft state instead of the sanitized export. Catalog: operation inputs publish sub-block ids only (no canonical-param aliases); trigger-category blocks expose their trigger-mode fields. Tables: dispatch processedCount counts unlimited dispatches; json-language code fields accept objects. Files: restore keeps the folder when it still exists. Sandbox tools: outputTable failures report the files already written and the per-language result shape; the file writer keeps the computed result.
* sim-cli: --output json prints the API data verbatim; the single-key unwrap stays a table-only convenience
* route and connection validation, trigger defaults on add, table folder restore, dispatch listing, group column attach, import block summary; logs query and deps engines; run-tool errors and payload compaction; stale tests aligned
Editing: router routes validated as {id?, title, value} with unknown keys named; malformed connections reported instead of dropped; sub-block value() defaults evaluated on add so a webhook gets its token. Tables: folder restore no longer 500s (lock inside the row transaction), completed dispatches are listed, groups attach to existing output columns. Workflows: import answers with its blocks. Mothership engines: logs query resolves bare paths under output, marks missing paths, drops non-executed runs under --where; deps lists graph predecessors and child return shapes; run-from-block validation errors reach the agent; run payloads compact input.code. CLI generated types regenerated.
* sim-cli: the operations apply confirmation describes the batch as written, not a delete
* sandbox export keeps the code's result; --trigger implies --manual; deps mock skeleton; run tools lift the terminal output and take select; lint all-clear names what it checked; docs chunker keeps code spans
* sim-cli: runs get --select-output takes block names; groups delete says it removes the output columns and their data; a publish that lands on public auth prints a note
* null-safe block.error, strict start-trigger coercion, lint checks reference paths against output schemas; logs stats segments; requiredWhen and model ids in the agent catalog; live tag usage; one row-filter grammar; minted service-account credential ids; webhook delivery URLs on deployment status; mv semantics for folder moves
Executor: <block.error> resolves empty on a block that succeeded so a shared error collector is writable; a number input given a non-numeric string fails the run at start naming the field; a regression test pins that failure traces carry child spans. Lint: a reference whose first path segment is not on the block's effective outputs (or its responseFormat schema) is an unknown-field finding. API: logs stats honours segmentCount and omits empty buckets unless includeEmpty; block detail publishes requiredWhen instead of flattening conditional requirements and always lists model options with hosted marks; knowledge tag usage counts through the document slot; every table rows filter accepts a bare condition; service-account credentials mint their id; deployment status lists each webhook's delivery URL; a folder move into an existing folder moves it inside. OpenAPI and CLI generated types regenerated.
* same-workspace import keeps or warns about workspace bindings; generic required-field lint; folder moves to the root; empty-graph and no-entry lint notes; span durationMs; MCP tools reported on undeploy and listed inactive; paged connector types and workspaces; grep --in refuses unknown selectors; run_function names exported files; run tools surface the failing block's error
Export takes includeWorkspaceBindings for same-workspace round trips and import answers with warnings naming every block whose required binding was stripped. Lint reports a missing required field for every block type (the knowledge base id was skipped), notes an empty graph and a graph with no entry block, and the trace spans carry durationMs. Undeploy answers with the MCP tools it archived and the tools list shows them inactive. connector-types list is paged (25, summary projection, detail=full) and workspaces list defaults to 25. The agent CLI's grep refuses a prefix or unknown --in selector with the accepted forms; a run_function that exported files and wrote a table says both; a run tool whose executor result carries no message uses the failing block's own error.
* table groups default to the deployed version and refuse a dispatch without one; column rename reports unmigrated Table-block filters; lint checks table fields against the live schema; runCount counts every settled run; runs cancel is honest about no-ops; dry-run apply answers with previewBlockIds; conditionResult is the chosen test's boolean with selectedTitle; workflows run --select-output keys blockOutputs by the selector and rejects unknown heads; knowledge search exposes rankScore and rank; the multi-trigger error names workflows state get; the Knowledge block declares cost, tokens, model; media writes refuse to fork a moved folder; grep --in knowledge points at knowledge search
* agent cli grep: the searchable text leads with the resource's name and description
* Catalog hides sunset blocks unless includeSunset; enrichment get returns the group's run state and outputs; knowledge upload prints the document fields; docs chunks titled by page not nav link; logs carry hasHandledErrors and opt-in handledErrorRuns; outputTable receipt keeps stdout
* Sandbox exports decode by the path rule the reader used: a .jpg declared without a format is written as image/jpeg bytes, not as its base64 text under the json format (thumbnails opened as raw text)
* Chat uploads resolve by uploads/<name> for reads, sandbox mounts, and image references (never listings or writes); an unresolved reference image fails the call instead of rendering without it; copilot session-sandbox calls are priced like Function-block sandboxes and report the raw cost beside the billed one; CLI docs regenerated
* grep: resolve --in against listings, fetch only the named resources
A bare --in selector (e.g. --in agent, --in file_v5) materialized every searched
world to find one block: 65 block details plus every workflow state per call. On
dev that took 18-34s per grep and tripped the per-user rate limit. Each world now
has a cheap index (its listing) and a per-resource fetch; a --in search reads the
indexes and fetches only the matches. Whole-world searches are unchanged.
* mothership: model-facing strings name only what exists on the CLI surface
The copilot back-derives fixes from the strings sim hands it, so a retired name
becomes a wrong instruction to the user (dev 2026-09-03: a save_upload mention
became "drag the photo into the files panel"). Every model-facing string audited
today now names the current surface:
- upload notice: a chat upload lives at uploads/<name> and is not a workspace
file; workflows import takes --workflow (there is no --file); a .zip is mounted
and unzipped in the sandbox rather than a files unzip path that does not resolve
- table import resolves uploads/<name> directly (includeChatUploads) instead of
pointing at the retired save_upload tool
- function-execute / generate-image: outputs get, files ls, files restore and
tables list replace read/grep/glob/restore_resource and Go VFS meta.json paths
- process-contents: browser/terminal pointers no longer name browser_* or a
terminal tool this surface does not have; docs fallback names docs search
- lint/deps usage strings use the plural workflows group
- integration credential error names credentials list
* docs: every model-searchable page states the current surface
The copilot answers users from these pages (docs search), so a wrong sentence
becomes a wrong instruction. Audit fixes:
- chat: uploads live under uploads/, not the Files panel; on-demand workspace
reach instead of a per-message snapshot; Chat runs Opus 4.8; connectors and
deletes/restores as they actually behave; login pages via the shared browser
- cli: --select-output works on sync runs (only --async conflicts); runs get
takes the same block selectors; secrets set needs --scope; workflows run runs
the deployment or --manual; sim profiles honours --output; which groups have
no singular alias; the embedded CLI has no profile, login, or config; @path
reads the chat sandbox
- model defaults are claude-sonnet-5 (guardrails has none); API examples use
https://www.sim.ai/api/v2 (apex 301s POSTs into GETs)
- quick reference / shortcuts: only affordances that exist (no Deploy tab, no
workspace duplicate/export, Mod+B not Mod+E, variables under the ⋯ menu,
<variable.name> syntax)
- editor read-only rules match round-trip-safety.ts; card links fixed
- sim-cli: runs-get selector error and the Settings label match the product;
batch delete describes its ids as deleted, not updated; docs/api regenerated
* mothership: prepare_file_edit create + new_file pass input validation
The workspace-file handler has always supported operation=create with a
new_file target, but the generated tool schema (from the copilot catalog)
forbade both, so the watched write could never create a file: a "save this
report as a workspace file" turn died on `/operation must be equal to one of
the allowed values` (dev 2026-09-03). Regenerated from the catalog that now
declares create, new_file, and fileName; regression test on the validator.
* mothership: the embedded CLI answers v2 in-process; grep memoizes both platform catalogs
The embedded CLI and the agent-cli engines were typed v2 clients pointed at the
server's own URL: every tool call was a network round trip through the proxy,
API-key auth, the abuse rate limits, and the proxy body ceiling. A grep over one
block definition cost 8-34s and tripped the per-key limit (dev 2026-09-03).
- sim-cli: ResolvedProfile / EmbeddedCliIdentity take an optional transport; the
client sends through it instead of fetch. The installed CLI never sets it.
- sim: an in-process transport resolves a v2 path against a generated route table
(scripts/generate-v2-route-table.ts, check:v2-route-table in check:audits) and
invokes the route handler directly. The request is marked internal through a
WeakSet — not a header — so admission still authenticates it but skips the
pre-auth IP bucket and the per-key rate limits, which exist for callers on the
wire. Contracts, use cases, presenters, and error envelopes are the ones the
network path runs. Anything outside the v2 table falls through to fetch.
- grep engine: blocks and tools (5,000 built-ins at 100 a page) are memoized per
workspace; an exact block or tool id (--in file_v5) resolves from that corpus
without listing any workspace world; name fragments still index every world
and fetch only the matches.
* mothership: take the embedded CLI off the in-process transport until the dev hang is understood
Every cli_grep on dev timed out at 60s from the first deploy of 99aad281a7. The
transport, marker, route table, and grep memo stay; the embedded identity goes
back to the HTTP path while the hang is diagnosed from sim's logs.
* grep: share in-flight builds, bound nested requests process-wide, cache file text by version
The first dev turn on the in-process transport fired eight world-wide greps at
once. Each rebuilt every world concurrently on the one process serving the chat
— 24 block-catalog listings, 150 tool-catalog pages, 130 file reads in sixty
seconds — until all eight timed out. Over the wire the same fan-out had been
spread across tasks and throttled by the network.
- concurrent greps now await the build already in flight for a (world, workspace)
- nested requests are bounded to eight for the whole process, not per world
- platform corpora (blocks, tools) are kept an hour, not ten minutes
- a file's text is cached by id + updatedAt + size, so repeat greps re-read only
files that changed
* grep: an exact block id answers before the tool catalog is built
* grep: honour -A and -B context flags
The engine read only -C; -A and -B were ignored silently, so `-A 40` returned
the bare match line and the model concluded context flags were unreliable
(dev 2026-09-03). A bad value is refused like -C's.
* sandbox pricing: normalize COST_MULTIPLIER at the boundary
Under skipValidation the value arrives as the raw string it was deployed with;
the sandbox lease's finite check rejected it, so on dev every run_code failed
as "Boot sandbox" (Sandbox pricing multiplier must be a finite nonnegative
number). getCostMultiplier now goes through envNumber, as the env module's own
rule says numeric overrides must.
* sandbox pricing: cost-multiplier imports env relatively — next.config.ts loads env-flags outside alias resolution
* mothership: pack a workspace inventory with every chat request
The agent spent nine tool rounds and ~20K tokens learning what exists in the
workspace before an orientation task could start. The chat request now carries
a compact inventory (contracts ChatRequest.inventory): workflows, tables,
knowledge bases, files, skills, custom tools, MCP servers, credentials, and
secret names — names and ids, one page per world, capped worlds named in
`truncated`. It is read through the same use cases the v2 listings run, under
the caller's session principal, so authorization is unchanged; a world that
fails to list is left empty and logged rather than failing the turn. The worker
renders it once per turn as a request-local message.
* grep: the tool catalog is one use-case call when the engine has the caller's principal
The tools world paged 5,000 built-in tools through the route stack at 100 a
page — fifty round trips, each re-resolving the gate and walking the registry —
which was the whole cold cost of a world-wide grep. The embedded bridge now
resolves the delegation key to its principal exactly as the v2 surface does and
hands it to the engines; with it, the tools world reads the catalog through
listCatalogTools in one call — same authorization, same projection. Without a
principal the client path stays.
* mothership: background tasks — subscriptions, wake turn, task pill (21 §6)
Sim side of copilot background tasks. copilot_task_subscriptions
(migration 0315) records a worker task's watch on a workflow execution;
the logging session's completion attempt posts every subscribed run's
outcome to the worker. POST /api/mothership/tasks/subscribe and
POST /api/mothership/wake (internal key): the wake runs the inbox's
headless lifecycle under the task id as message id, announces itself on
the chat status channel so an open chat reconnects, persists the user
message with origin 'task', and resolves the pill in the arming turn.
Client: a 'task' content block end to end (run handler, turn-model node,
both serializer directions, persisted normalizer — which also flattened
plan blocks to text on reload —, display block, segment, TaskPill) and a
muted TaskNotificationRow for task-origin messages. The stream
validator's run kinds now derive from the generated contract; the
generated mothership-stream-v1 gains task_armed / task_delivered.
* mothership tasks: resolve the pill by task id (jsonb text spacing broke the exact-key match)
* task pill: icons from @sim/emcn (lucide-react is not an app dependency; the Docker build failed)
* mothership: checkpoint Sim interaction and workbench boundary repairs
Capture the accumulated Mothership control, recovery, sandbox session, embedded CLI, and standalone diagnostic repairs. Companion worker checkpoint: c8245400. Validation and limitations are recorded in the Mothership revamp ledger through iteration 38; the latest expanded Sim diagnostic selection passed 1231 tests. The new table-mount audit is excluded and will follow separately.
* mothership: authorize table snapshot mounts and honor folder references
Move Mothership table snapshot resolution, provenance checks, and bounded storage reads into a registered application operation. Reuse the table VFS resolver for folder paths, recheck current actor access before materialization, and project safe mount errors. Preserve CSV transport, budgets, default paths, and workflow/public API behavior. Validation: 517 related tests, app/auth type checks, API and agent-CLI boundary checks.
* mothership: stream workbench downloads with atomic publication
* mothership: stream uploads and imports from workbench snapshots
* mothership: bind upload requests to the snapshot lifetime
* fix(mothership): preserve and bound embedded CLI output
* fix(mothership): preserve file provenance through host CLI reads
* test(mothership): guard current CLI catalog entry points
* fix(mothership): make search current, isolated, and explicit about coverage
* fix(mothership): bind file mounts to one canonical version
* feat(mothership): persist private upload source classification
* fix(mothership): preserve classification across workbench file copies
Record encrypted source evidence against host-streamed bytes and physical workbench identity. Bind completed upload streams through the authorized application operation, sealing pending provenance with the completion lease so recovery preserves the first result.
* fix(mothership): retain source evidence for saved CLI output
Classify settled stdout through the existing workspace-file helper and persist evidence against the streamed workbench bytes. Preserve completed command outcomes on publication failure and verify copied output across fresh invocations and pending sibling tools.
* test(mothership): exercise CSV composition through the Sim runtime
* test(mothership): connect CLI workflow runs to report publication
* fix(mothership): preserve raw CLI data with scoped presentation
* fix(mothership): expose canonical workflow identity for watches
* fix(mothership): preserve watches across transcript replay
* fix(mothership): convert code execution timeouts once
* fix(mothership): preserve child failures across transcript recovery
* test(mothership): distinguish replay from executable handoff
* test(mothership): verify persisted run diagnostics through CLI
* test(mothership): verify workflow execution log readback
* test(mothership): verify controller execution and resume recovery
* fix(mothership): acknowledge text received before stream retries
* fix(mothership): reconcile response text across reconnects
* test(mothership): verify automatic relay interruption recovery
* fix(mothership): unify replayable child lifecycle handling
* test(mothership): verify child recovery after worker exit
* fix(mothership): distinguish tool history from executable handoffs
* fix(mothership): acknowledge received activity between stream legs
* test(mothership): recover missing initial relay frames
* test(mothership): cover overlapping relay attachments
* fix(mothership): observe results owned by overlapping controllers
* fix(mothership): preserve long CLI command budgets
* test(mothership): verify table pipeline against real execution
* fix(mothership): recover one-shot response delivery
* fix(mothership): align one-shot MCP discovery guidance
* fix(mothership): make inbox attachments readable
* fix(mothership): scope upload names to the requesting chat
* fix(mothership): preserve worker history when forking chats
* fix(mothership): cancel only response-owned workflow executions
* fix(mothership): serialize workflow pickup with run Stop
* fix(mothership): track browser workflow execution through Stop
* fix(mothership): require settlement for Stop before chat attachment
* fix(mothership): preserve canonical history when stopping a response
* fix(mothership): handle abort failures while Stop history persists
* fix(mothership): retain queued Stop dependencies through retries
* fix(mothership): recover outgoing handoffs through the durable queue
* fix(mothership): bind queued retries to the active Stop operation
* test(mothership): exercise physical workflow edits and oracle execution
* test(mothership): verify extracted workflow invocation through saved logs
* test(mothership): verify build-only consent through physical run history
* fix(mothership): retain terminal failures in saved chats
* fix(mothership): retain active runs through worker connection loss
* fix(mothership): persist Stop before worker delivery
* fix(mothership): recover interactive streams after Sim process loss
* fix(mothership): durably admit chat turns before worker dispatch
* fix(mothership): recover lost tool handlers with fenced execution leases
* fix(mothership): finalize steered answers by turn identity
* fix(mothership): separate committed tool outcomes from stream publication
* fix(mothership): serialize saved resource panel changes
* fix(mothership): persist resource effects once before publication
* fix(mothership): preserve complete saved resource addresses
* fix(mothership): preserve saved table views in chat context
* fix(mothership): follow the current embedded table view
* fix(mothership): preserve exact table selection identities
* fix(mothership): attach usable file folder references
* fix(mothership): render saved file folder resources
* Revert "fix(mothership): render saved file folder resources"
This reverts commit d7854344686e06314ad7db3856347e472fda7b32.
* fix(mothership): align attachment context with available tools
* fix(mothership): authorize MCP calls as the chat subject
* fix(mothership): keep workbench policy out of the public CLI
* fix(mothership): preserve composed code export outcomes
* fix(mothership): retain completed files after export failure
* test(mothership): verify hosted workbenches and task compositions
* ci: restore staging jobs and keep Mothership acceptance local
* feat(mothership): receive private Sim controls over outbound transport
* fix(mothership): bound stream reconnection attempts
* fix(mothership): export chat sandbox files through workspace storage
* fix(cli): isolate embedded output from host process logging
* fix(mothership): preserve file intents and workflow result contracts
* perf(mothership): trace CLI and tool persistence boundaries
* fix(mothership): preserve resource effects and execution recovery
* fix(mothership): reconcile staging contracts and consolidate migrations
* fix(mothership): share and verify billing callback contracts
* fix(mothership): preserve catalog curation and embedded CLI access
* fix(mothership): mount code secrets explicitly
* fix(mothership): own sandbox profile at the code tool boundary
* fix(workflows): validate field values before full-state writes
* fix(chat): collapse main tool groups into action summaries
* fix(mothership): restore workspace API key dispatch
* fix(chat): label workflow dry runs as validation
* feat(chat): expose model, reasoning effort and Astra Fast controls
* fix(chat): align composer model and effort controls
* Group Mothership tools by activity and show scoped resource names
* Report requested Mothership model without legacy telemetry defaults
* Restore Mothership Slack bot connection from stored secrets
* Preserve execution events for deployed Copilot workflow runs
* Expose active workflow API details to Mothership
* Restore desktop parity and preserve interrupted chat progress
* Keep Mothership resource panels and activity groups in sync
* Show active tools before completed activity summaries
* Fix shared agent tool execution and discovery boundaries
* Port Assistant to shared Mothership runtime and repair resource recovery
* Refresh CLI docs and desktop validation after staging rebase
* Restore staging image inventory commands
* Fail migrations correctly and resolve empty direct database URLs
* Match chat attachment guidance to supported file capabilities
* fix(ci): retain the latest published desktop prereleases
* fix(mothership): read file contents through one adaptive command
* fix(chat): simplify pending tool activity label
* feat(chat): inspect scratch files and preserve inline images
Resolve workspace, upload, and sandbox references through authorized file readers. Preserve explicit Markdown images privately with each chat turn without creating workspace files, and keep visual bytes out of bounded UI tool-status events.
Keep sandbox CLI credentials scoped to the active callback so file provenance checks cover data entering the workbench.
* fix(chat): keep tool failures in expanded history
* fix(db): avoid repeated dev index builds and search backfills
* fix(chat): preview inline images with shared lightbox
* feat(mothership): operate across organization workspaces
* feat(mothership): manage settings and workflow file inputs
* fix(mothership): preserve stopped chat admission and queued corrections
* fix(mothership): show sequential activity intent and concrete tools
* fix(mothership): expose canonical model hints in internal discovery
* fix(mothership): unify scoped CLI and organization resource panels
* feat(assistant): connect and use personal organization integrations
* feat(chat): unify Home modes and search resource tabs
* feat(chat): tailor Home controls and starters to the selected mode
* fix(mothership): preserve file upload and preview resource context
* fix(mothership): stabilize Home search panels and add optional Fast Search
* fix(mothership): preserve staging authorization and resumed billing
* fix(db): make development schema pushes noninteractive (#7906)
* fix(db): resolve dev schema push column ambiguity
* refactor(db): generalize push rename handling
* docs(db): describe schema push reconciliation steps
* feat(search): unify Home search levels and composer
* fix(db): retire file size bridge before forced schema push
* fix(ci): restore test isolation and memory file scope checks
* fix(ci): keep metadata imports pure and narrow component graphs
* fix(mothership): refresh client settings after scoped mutations
* fix(db): repair partial member sync status on existing databases
* fix(home): reuse the shared loading fallback
* fix(mothership): remove eager catalogs and bulky admission saves
* fix(mothership): keep reads out of resource panels
* test(search): assert lazy integration catalog in headless chat
* fix(search): label balanced search level Auto
* fix(mothership): provide authorized context for chat titles
* fix(search): restore standalone search and refine chat mode controls
* fix(search): align mode selector with the standard search icon
* fix(mothership): resolve integration discovery service identities
* fix(desktop): reuse Sim login for authenticated browser previews
* fix(chat): preserve configured origin in deployment URLs
* fix(search): recover GitHub installation setup and verify ownership
* fix(search): retain sync failures and resume reconnected accounts
* fix(chat): restore thinking indicator after tools finish
* fix(mothership): expose and validate tool attachment identities
* feat(mothership): inspect configured workflow tool bindings
* feat(mothership): support dynamic Sim Chat tool modes
* fix(mothership): continue Sim Chat block conversations
* feat(mothership): create organization workspaces through CLI
* perf(desktop): observe browser state in action calls
* fix(mothership): repair background wakes and simplify watch activity
* fix(mothership): clarify tool permissions and folder context
* fix: reconcile staging rebase contracts and migrations
* fix(db): reconcile staging search migrations in dev
* fix(chat): preserve live turns and recover interrupted streams
* fix(workflows): scope custom block schemas during authoring
* fix: reconcile staging search and file contracts after rebase
* style(db): format rebased migration snapshots
* fix(slack): deliver Sim Chat text and tool progress reliably
* test(slack): verify Agent and Sim Chat thinking parity
* fix(slack): bound each long-answer append request
* fix(slack): continue long streams across message limits
* fix(slack): recover explicitly rejected size overflows
* fix(mothership): simplify saved results display label
* fix(slack): clean up long-response continuations
* feat(mothership): simplify Build picker to Astra effort levels
* fix(mothership): hide mode selection after the first message
* feat(search): add feature-flagged live provider retrieval
* fix(search): scope repository retrieval and add Coda MCP OAuth
* fix(search): restore account hooks client directive
* Fix GitHub connected-account tools in Search Assistant
* Add organization-scoped live search and admin-managed GitLab
* Add date-aware live enterprise search and bounded listings
* Polish live Search results, citations, and effort controls
* fix(mothership): preserve hosted service billing through cutover
Record hosted integration, sandbox and media spend through a trusted durable
service outbox independent of tool output, cancellation and worker delivery.
Preserve service billing under model BYOK and restore title admission.
Use workspace BYOK settings and fresh credentials, retain execute transport,
and restore the locked actor-authority check for billing-sensitive membership
removal. Add migrations and local HTTP/PostgreSQL billing acceptance coverage.
Validation: 1,453 billing tests passed with 30 environment-gated skips, app
and dev infrastructure types passed, and local SQL charge proofs passed.
* fix(search): restore live citations and streamed source panel
* fix(search): replace live results tab with cited sources
* feat(search): simplify federated sources and add scoped secrets
* fix(search): make service account setup directly accessible
* feat(mothership): add dev-gated Plan mode across chat surfaces
* fix(search): preserve account connection links in Slack
* fix(search): remove indexing language from live search
* fix(search): keep admin setup out of member integrations
* fix(search): route Search MCP through live retrieval
* fix(plan): normalize the runtime feature flag to a boolean
* ci(dev): deploy Trigger tasks independently of app images
* feat(mothership): set organization Generic Secrets in chat
* fix(search): verify federated connectors and align setup docs
* fix(search): remove stale Slack indexing copy
* docs(search): document Generic Secrets and clarify source setup
* fix(mothership): allow authorized organization code secrets in Build and Plan
* fix(search): restore live integration connection chips
* fix(search): include Gmail in live connection inventory
* fix(search): expand composer around image attachments
* fix(mothership): restore saved Plan chat history
* fix(mothership): address review findings and CI regressions
* test(deploy): align promotion expectation with Trigger CLI
* improvement(desktop): make saved password autofill field-aware
* fix(mothership): preserve trace filters and shared app workers
* fix(desktop): dismiss credential picker when browser hides
* feat(mothership): simplify model controls and add native desktop files
* fix(desktop): preserve password picker focus and lifetime
* chore(mothership): align model and deployment test expectations
* fix(mothership): resolve model and Plan controls from AppConfig
* fix(desktop): contain native imports and preserve UTF-8 pages
* fix(credentials): preserve unrelated setup controls
* feat(browser): file transfer, popups, PDFs, click gestures, and dialog answers for the browser agent
- Upload workspace, chat-upload, or granted local files into a page's
file input (DOM.setFileInputFiles on the input a ref, label, or drop
zone resolves to), staged privately and bound to the claimed tool
call; save completed downloads into workspace files. New
/api/desktop/tool/file route with application use cases.
- Same-session popups adopt Chromium's WebContents so window.opener
works (sign-in and connect flows); a page that closes itself leaves
cleanly and agent work returns to its opener.
- PDFs render: enable Electron's internal PDF plugin and let its
packaged viewer resources past the network guard.
- Clicks take button, clickCount, and modifiers; agent right-clicks
never open the native menu. Actions answer confirm/alert dialogs via
dialog: {accept}. press_key gains F1-F12, Insert, and repeat; scroll
and hover accept post-action observation.
* chore(chat): provide runtime flags in composer tests
* fix(browser): isolate actions and bound file transfers
* fix(browser): retain upload input identity through dispatch
* fix(mothership): validate complete billing protocol headers
* fix(browser): preserve upload dispatch before acknowledgement
* fix(browser): distinguish unconfirmed upload outcomes
---------
Co-authored-by: Vikhyath Mondreti <vikhyathvikku@gmail.com>
Co-authored-by: Vikhyath Mondreti <vikhyath@simstudio.ai>
Co-authored-by: Waleed Latif <walif6@gmail.com>
|
||
|
|
96b941f8a8 |
feat(api): expose organization access and usage operations (#8127)
* feat(api): expose organization access and usage operations * fix(api): enforce current invitation and organization scope * fix(billing): serialize credit caps with access revocation * fix(workspaces): align detachment with invitation lock order |
||
|
|
00c841326b |
feat(knowledge): export knowledge bases as bundle archives (#7620)
* feat(knowledge): export knowledge bases as bundle archives Adds a streaming zip export for a knowledge base across the v2 API, the internal API, the CLI, and the UI. The bundle carries the base's configuration and tag definitions, each workspace-visible document's original file and chunk text, and optionally the chunk vectors so an import into a deployment with the same embedding model can reuse them. Access-control lists, connector links, credentials, uploader identity, and storage keys never leave. - knowledge.export operation gated by a new Knowledge Base Export permission group setting; exports record an audit event - entries are appended one at a time so a large base never fans out storage reads and the manifest is written last with the counts actually produced - sim knowledge export <knowledgeBaseId> --output-file kb.zip [--no-vectors] - Export in the knowledge base row menu and base page header * fix(knowledge): expose authorize on knowledge use cases and gate export on describable bundles - defineAuthorizedKnowledgeUseCase now answers authorize() through the same resolution execute() uses, which headSafe: false routes require at module init; defineAuthorizedWorkspaceUseCase's return type states that authorize is always present - the export use case validates the stored base against the bundle manifest schema before any byte streams, so a value the import side would refuse surfaces as a 409 rather than a truncated archive - Export is hidden in the base menu and header when a permission group withholds knowledge.export - operations id snapshot includes knowledge.export * chore(docs): count the knowledge export path in the OpenAPI download test * improvement(knowledge): read inline document payloads lazily and scope chunk reads to the base Follow-ups from an independent review pass over the export path. - the document listing no longer selects fileUrl: a data: document can hold megabytes in that column, so the listing carries a flag and the archive reads one payload at a time when it reaches that entry - iterateDocumentChunks filters on knowledgeBaseId as well as documentId, so a future caller cannot reach another base's chunks through the bundle - tag definitions are validated by the single bundle gate, which answers 409 like every other undescribable value rather than throwing a bare ZodError - a consumer that abandons the download aborts the append loop and destroys the in-flight source instead of leaving it pending - direct tests for the knowledge use-case builder's authorize() on the workspace, organization, and legacy personal branches * improvement(knowledge): validate stored chunk counts and scope inline reads to the base - the bundle gate checks each document's stored chunk count against the format's per-document ceiling, so a base holding more chunks than a bundle can describe is refused up front rather than written into an invalid manifest - the inline payload read carries its knowledge base id, matching the chunk reads, so neither can reach a row outside the base being exported - an append is refused once the consumer has aborted, since a destroyed archive has no listener left to receive the error it would emit * improvement(knowledge): bound the streamed chunks and validate the written manifest Findings from a reuse, simplification, efficiency, and altitude review. - the chunk stream stops at the per-document ceiling and raises afterwards, and the manifest that actually ships is the one validated: chunkCount is denormalized, so a document re-chunked mid-export could previously pass the pre-flight gate and land in a manifest no importer would accept - a real archive failure is no longer mistaken for the consumer walking away; archiver emits close for both, so only the abort's own error is swallowed - the inline-file probe reads a 5-byte prefix instead of matching the whole column, which was detoasting every document's fileUrl and defeating the optimization the listing exists for - storedChunkCount replaces the redundant hasChunks pair - the CLI reads the RFC 5987 filename first, so a knowledge base named "Suporte tecnico" no longer saves under a mangled ASCII name - drops three bundle ceilings the import half will introduce, breaks a circular type import, and states the authorize guarantee in the type so a headSafe route is proven at compile time rather than at module load |
||
|
|
7e9dd2af8c |
improvement(docs): simplify navigation and share editor previews (#7606)
* improvement(docs): simplify navigation and share editor previews * fix(docs): preserve focus in workflow illustrations |
||
|
|
236eb53f94 |
fix(provenance): close durable writer and reader gaps (#7584)
* fix(provenance): close durable writer and reader gaps * fix(provenance): preserve mixed files and repeated durable bindings |
||
|
|
d594a9e151 |
fix(api): clarify and standardize endpoint descriptions (#7580)
* fix(api): clarify and standardize endpoint descriptions * fix(api): qualify run recovery and trace duration guidance * fix(api): align descriptions across resource families |
||
|
|
d7124cdb4d |
feat(scim): directory provisioning (SCIM 2.0) (#7567)
Sim-native SCIM 2.0 provisioning for Okta, Microsoft Entra ID, OneLogin, and JumpCloud: Users and Groups CRUD with filters and paging, RFC 7644 discovery and error envelope, provider payload tolerances, bearer tokens with rotation, reversible deactivation, removal with ownership handoff, group mappings onto permission groups, workspace access, and the organization admin role, hourly reconciliation, an activity log, and the settings UI under SSO. Ships with the Enterprise plan on the hosted product; SCIM_ENABLED / ENTERPRISE_ENABLED on self-hosted. Migration 0324_scim_provisioning (expand-only). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DGXcwsHzYGp6pUDWRtJKpz |
||
|
|
8adb986f69 |
feat(auth): add scoped OAuth access and browser-based CLI login (#7488)
Add scoped OAuth authorization-code login with PKCE, rotating token families, consent and revocation, and operation-level API scope enforcement. Preserve existing API-key, session, connector OAuth, and browserless CLI authentication. Use the existing global AppConfig oauth-provider flag for request-time rollout control, with the environment variable as its standard fallback. Share the database lifecycle between migration and db:push, bound token cleanup, and document rollout sequencing. Validation includes the full app, CLI, and database suites; both PostgreSQL provisioning paths; live browser and CLI authentication; API-key regression checks; and AppConfig off/on/off changes without restarting the app. |
||
|
|
0db625629d |
feat(knowledge): permission-aware knowledge bases behind a feature flag (#7385)
* feat(search): add Sim Search mode, connectors tab, and cited sources
- Build/Search mode switcher in the chat composer; Search mode swaps the
suggested actions for Connect Sim Search rows that open the OAuth modal
- Search tab beside Integrations and Skills: a personally scoped catalog
of knowledge-base connectors with connect-in-place rows and a
connected-credential page without sharing or members
- <source> special tag contract: inline citation chips at the citation
point plus a scrolling, right-faded sources strip under the reply
- chip `shape` variant so a fully round chip is chip chrome, not a class
override
- keep the connector catalog out of the workflow editor's module graph
and record the new routes in the boundary baseline
* fix(search): harden source parsing, availability, and provider matching
- validate <source> urls by parsing them and requiring a host, so a
malformed value never renders a dead citation link
- gate Search-mode suggestions on deployment OAuth availability, sharing
the predicate with the Search catalog
- match connected credentials across a service's additional provider ids
(Salesforce sandbox) and count them in connector telemetry
- collect footer sources from the rendered text segments, covering a
block-less message's fallback text and excluding subagent lanes
- use a distinctive citation-link sentinel and an absolute import for
SuggestedActions
- teach the email tokens transcription test the composed chip geometry
* feat(knowledge): add document ACL schema and members-mode tables
Adds document.acl (sorted access tokens, fast default '{ws}') with a partial
GIN index and a token-shape CHECK, source_modified_at, the members-mode
columns and lease on knowledge_connector, a real FK on credential_id (left
NOT VALID until script migration 0011 has remapped legacy account ids), and
three tables: knowledge_connector_member, knowledge_document_observation,
knowledge_connector_member_sync_log.
The document contract stops passing unknown keys through so the new column
and storageKey never reach clients.
* feat(knowledge): add access scope, token, and predicate libraries
Pure building blocks for document-level access: the token vocabulary and
its single sorting/validation site, the subject token derived from a managed
credential row, the read-side predicate (scalar binds, literal ARRAY), the
per-principal scope resolver with a lazy memoising provider, the branded
system scope, and the members-mode sync limits. Nothing consumes them yet.
* feat(knowledge): enforce document access scope on every read path
Every document loader, chunk list, tag usage, search leg, metadata lookup,
and knowledge-base file serve now takes a required access scope and applies
the shared ACL predicate. Context resolvers attach a lazy, memoised scope
provider derived from the acting principal and load documents through it,
so a document the caller may not read is absent from the first read. Raw v1
routes and legacy helpers resolve the same scope; the outbox handler is the
one branded system-scope caller. Vector legs run inside a transaction that
enables pgvector's relaxed iterative scan (with a 42704 fallback) so a
narrow ACL still fills topK. Forked workspaces copy documents as '{ws}'.
Behaviour is identical today: every row carries the default '{ws}' token.
* refactor(knowledge): extract connector sync primitives from the sync engine
Splits the content sync engine into four modules without changing behaviour:
sync-lock (lease predicates, heartbeat, and a SyncRunLease the stages run
under), sync-persistence (storage and document-row writes), sync-primitives
(the pure decision functions plus the six orchestration stages: listing
pass, owned-corpus load, classification, hydrate/persist/dispatch, deletion
reconciliation, and the stuck-document sweep), and sync-engine (lock
acquisition, terminal state, and executeSync composed from the stages with
its original closures). The stages take the token, hydration, and lease as
inputs so a second engine can run the same guards under a different lease.
Tests keep every assertion; only import paths moved with the symbols.
* feat(knowledge): plumb credential groups into knowledge connectors
Registers Google Drive as a Credential Group provider (provider list,
adapter registry, and the Google managed-OAuth policy), marks the Drive and
Confluence connectors as permission-scoped listings with the config fields
that would cap them, and extends the Credential Group policy with a
knowledge_connector principal and a credential_group:OptionId condition so a
group can grant one connector the credentials collected under one option.
The policy codec gains one KnowledgeConnectorCredentialAccess statement per
option, decoded by SID; workflow-access edits now carry connector grants
through untouched. Knowledge-side helpers grant and revoke the binding under
the policy's revision CAS, mint a member token only when the policy names
the connector for the credential's option (audited per access), enumerate an
option's credentials in every state for membership reconciliation, and
validate a members-mode binding before anything is touched. Nothing calls
them yet.
* feat(knowledge): add the members-mode sync engine
Adds the engine that crawls a knowledge connector once per Credential Group
member with that member's own token and derives each document's ACL from who
observed it. A run takes the member lease (mutually exclusive with the
content engine's), finishes any pending access rewrite, mirrors the option's
credentials onto member rows (active or suspended, tokens rewritten, departed
members dropped), then claims due members one at a time until its budget
ends: each member's listing is admitted into a first-writer-wins union, every
listed document is hydrated once through its observers' tokens, observations
are recorded, removals follow only a full, complete, non-suspect listing, the
affected ACLs are rematerialised from the observation graph, and the document
lifecycle tombstones the unobserved, resurrects the re-observed, and purges
the long-unobserved under the lease. The run re-dispatches itself while
members remain due.
Around the engine: a member queue mirroring the content dispatch (token,
lease, lost-hand-off release), a Trigger.dev task on its own queue, a cron
scheduler that reclaims stale leases and lost dispatches, closes orphaned run
logs, sweeps members whose crawls stopped, and dispatches due connectors, and
the Docker and Helm cron entries. The content engine and its dispatch refuse
members-mode connectors, workspace-mode syncs restore the workspace ACL on
completion, document writes carry the ACL each mode needs, the hard-delete
guard can verify the member lease, and the Drive and Confluence connectors
report a scope the member cannot reach as an empty listing rather than an
error. Nothing enters members mode yet.
* feat(knowledge): let connectors enter members mode
Wires the members-mode engine to the connector surface. A connector can be
created in members mode (admin only) bound to a Credential Group option, or
switched between modes through a new admin-only access operation and route:
the switch takes the connector's content lease, rewrites the documents' ACLs
to the new mode's default in bounded batches (finishing under the member run
when the request budget runs out), grants or revokes the option's credentials
in the group's policy, flips the mode, and queues the first run of the new
engine. Members-mode source edits refuse listing caps and queue a member run,
a manual sync routes to the member queue, keep-documents deletion is refused,
and deletion revokes the grant. Contracts carry the access mode, the binding,
the member-sync state, the member summary, and member run logs; the member
scheduler and dispatch honour a paused connector.
* feat(knowledge): per-member access controls in connector settings
Add an Access section to the add and edit connector modals so a workspace
admin can sync a permission-scoped connector once per credential-group
member. The connector card shows the per-member badge, member sync status,
and a member run history in place of the content sync history.
* feat(knowledge): note member-scoped retrieval on the knowledge block
Knowledge bases report whether a live connector syncs per member, and the
knowledge block's selector explains that such documents depend on who
triggers the run.
* feat(knowledge): per-member change feeds for members-mode connectors
Connectors may open a change feed over a member's view of the source.
Google Drive reads changes.list, where a lost share arrives as a removal,
so a member's access is withdrawn without waiting for a full listing;
Confluence filters its CQL listing by lastModified for incremental
content refreshes. Each member stores where their feed resumes, and a
member with an open feed is relisted fully only weekly as a check.
* feat(knowledge): hybrid retrieval by default with a source-recency boost
Search fuses the full-text and semantic legs unless a caller asks for
vector-only, at every surface: internal, v1, v2, the knowledge block,
and Sim's own knowledge tools. Connector documents now record when the
source last changed them, and a recently modified document edges past
a stale one of similar relevance.
* feat(knowledge): gate permission-aware knowledge behind a flag and harden the stack
Add the knowledge-member-access feature flag (workspace allowlist and
platform admins via AppConfig; KNOWLEDGE_MEMBER_ACCESS off-AppConfig). It
gates members mode at creation and switching, the member engine, and the
hybrid-by-default retrieval with its recency boost; the connector modals
read it from the workspace host context. The knowledge block's retrieval
mode gains an Automatic option so the server's default applies.
An admin with no credential group for the connector's provider can create
one from the Access field; the group is named after the connector and
members are invited from Settings.
Review fixes: manual-only connectors no longer re-dispatch member runs
forever; ACL materialisation is idempotent so a run that died mid-way is
repaired; incomplete listings retry at once only when they can resume;
suspended members keep their observations; a scope the member cannot reach
closes their change feed; the workspace ACL restore runs inside the
completion lock and only for workspace-mode connectors; the mode switch
grants before rewriting and flips in one transaction, clearing listing
caps; minting checks group, option, and enrollment status; connector
document lists, bulk select-all operations, and tag usage stats apply the
access scope; the connector card reads the member engine's status; the
edit modal applies an access switch on its own instead of racing the
settings save.
* test(knowledge): cover retrieval default resolution behind the flag
* fix(knowledge): judge members mode by the workspace alone and fail closed when the flag is off
Members mode is gated by the workspace at creation, switching, in the
member engine, and in the workspace host context, so no gate can open a
mode another will refuse; the flag's admin clause now affects only the
retrieval default, and search passes the signed-in person rather than a
billing owner or key creator. Member tokens count only where the feature
is on, so turning it off hides member-scoped documents on the next read.
New and reactivated members are due at once so a drain re-dispatches
until everyone has been listed. Leaving members mode flips first under
the lease with the rewrite marked pending, then rewrites; a failed move
between options of one group restores the previous option. The edit modal
closes after a switch and cannot re-choose per-member where the flag is
off; connector document exclusion honours the caller's scope.
* feat(knowledge): provision per-member access in the background
Choosing per-member access no longer asks the admin for anything: the
server reuses the workspace's one credential group for the connector's
provider or creates one, invites every workspace member to connect, and
each member run invites people who joined since. A member's only step is
to connect: the knowledge base page shows a banner for every per-member
connector they have not connected, and a new enroll route mints their
enrollment link on demand so the invitation email is never needed. The
connector list reports the viewer's membership for that banner.
The permission-scoped listing CI test now compares OAuth provider ids,
which is what the runtime checks. The knowledge page module baseline is
re-recorded for the provisioning graph.
* fix(knowledge): make per-member access self-serve end to end
Choosing per-member access provisions a group named after the connector
and the first member run invites everyone in the workspace, under the
run's lease; the request itself sends nothing, so nobody gets two links.
A member connecting queues a member run for every connector on that
option, and the knowledge base page shows what each viewer must do —
connect, reconnect, verify their email, or nothing — opening enrollment
in a new tab and refreshing until they are connected.
Every gate reads one availability check (flag and Credential Groups).
When it is off, readers get no member token, the engine waits instead of
suspending anyone, and the field cannot re-choose per-member access.
Member tokens go only to current workspace members with a live group and
option. A connector that just entered members mode never tombstones its
documents before a member has listed, the stale sweep leaves paused and
manual connectors alone, a disabled member sync is re-enabled by
re-applying its binding, leaving members mode forces a full content
sync, and by-id bulk operations honour the caller's scope. Deleting a
per-member connector always takes its documents.
* feat(knowledge): list a workspace's per-member connectors for the viewer
One read returns every per-member connector in the workspace with where
the viewer stands on each, so a surface outside the knowledge base can
ask them to connect. The member sync status enum now has one home in
lib/knowledge/types.
* feat(search): show per-member knowledge connectors on the Search tab
The Search tab lists the knowledge bases whose connectors sync per member
under "Shared with you", with where the viewer stands on each and the same
one-click connect the knowledge base page offers. One hook opens
enrollment in a new tab and refreshes the surface until the viewer is
connected; the knowledge base banner uses it too.
* feat(knowledge): enable per-member access on every permission-scoped connector
Google Slides, Docs, Forms, Calendar, Gmail, Notion, Jira, Jira Service
Management, Box, Dropbox, monday, ClickUp, Asana, Salesforce, Linear,
DocuSign, and Zoom list only what the caller's own account can read, so
each now declares its listing caps and can sync per member. A shared
listing-scope error lets a connector report a folder, space, board, or
calendar the member cannot reach as a complete listing of nothing; Notion
and Asana report it from their typed errors, Dropbox from its 409, and
the Atlassian connectors also from an unreachable site. Google Docs and
Forms join the credential-group providers so their accounts can be
collected per person.
* refactor(knowledge): tighten the per-member access surface
- The credential-group policy canonicaliser carries knowledge-connector
statements through instead of rejecting a third statement
- Google Docs and Box report an unreachable scope so a member's access is
withdrawn rather than retried forever; Notion leaves members mode because
its page access is granted to the shared integration bot
- Provisioning reuses a Credential Group only when other members-mode
connectors already sync through it, never a group curated for something
else; the fast dispatch on connect accepts the same statuses as the sweep
- Enrollment opens its tab inside the click so popup blockers cannot swallow
it, and the membership poll stops after ten minutes
- Session-only routes use session auth; members mode stores the cap-stripped
config; one liveness rule for members and managed bindings
- Drop dead code: the access barrel, system.ts and rank.ts folded into their
siblings, unused ACL helpers, the unread change_cursor_at column, stale
documentation, and the engine/provisioning/queue import cycle
* fix(knowledge): repair CI and apply cleanup passes
- Bump the chart version for the member-sync cron and secret
- Pass an access scope to getDocuments in the list-convention test and
resolve a knowledge scope only for knowledge-base file reads
- Drop memoisation nothing observes, read the enrollment error from the
mutation, hoist the empty connector list, use the default Cancel variant,
let Badge own its gap, and keep the sidebar lit on the Search tab
* fix(knowledge): apply the audit swarm's findings
- Mutation responses failed contract validation because a viewer's
membership was required; a mutation now answers with null
- Bulk enable/disable wrote to documents outside the caller's scope
- The staleness sweep tombstoned deferred and backing-off connectors;
it now only touches connectors that completed a run in the window
- Members pace on the plain interval so the connector's jittered run
finds them due; a member who alone exhausts the run budget backs off;
an account that connects mid-run keeps the connector re-dispatching
- Gmail and Google Calendar kept a 500-item cap once the cap field was
cleared; caps are now written as 0, which every connector reads as
unlimited, on the update path as well
- Jira, ClickUp, Asana, Linear, and Dropbox classify an unreachable
scope on the source's own error rather than a bare 404; an unmatched
Atlassian domain is a configuration error, not this person's access
- A Credential Group or option serving a members-mode connector cannot
be removed under it; the OAuth completion dispatch cannot fail the
callback; the content queue refuses a connector that syncs per member
- The iterative vector scan runs only for a personal token set; the ACL
check validates each element; the flag is read before the enrollment
join; connector info is loaded only where it is shown
- Search tab: the empty state counts member rows, rows stack, one
membership vocabulary shared with the knowledge base banner; an admin
can rebind a per-member connector to any matching group
* feat(knowledge): search results a person can open, from Chat
- The composer's Search mode searches every knowledge base as the signed-in
person and lists what they may read as result cards: source icon, title
linking back to the document, knowledge base, updated date, and the
matching passage with the query terms in bold; Summarize hands a document
to the agent in Build mode
- The agent's knowledge tool returns each result's title, link, connector,
and modified time and is told to cite with source tags carrying a snippet;
a reply whose sources carry snippets ends with the same cards
- A session route for the search, bound to the shared search use case, so
the browser reads through the same access predicate as everything else
- Search quality: hybrid legs over-fetch before fusion, the vector leg's
iterative scan fills a limit past the default candidate pool, and the
recency weight moves a fresh document a few places rather than the list
- A manual member sync makes every active member due, so Sync members now
lists everyone instead of nobody
* fix(knowledge): land member observations and ACLs only under the lease
A run that stalled past the lease TTL and resumed after a replacement took
over could commit stale observations, membership rows, and document ACLs
over the replacement's. Every such write now runs in a transaction that
first proves the run still holds the connector's member lease, holding the
connector row's lock so the scheduler cannot reclaim it mid-transaction; a
run that lost it ends as superseded.
* fix(knowledge): disable a member sync only under the lease
A run whose binding was removed suspended members and rewrote ACLs before
proving it still held the lease; a run reclaimed meanwhile could suspend
the replacement's members and then fail. Suspension, the ACLs it changes,
and the disable now land in one lease-guarded transaction, and a reclaimed
run ends as superseded.
* fix(knowledge): record a member failure only under the lease
A listing that ran past the lease TTL and then failed wrote its backoff
over the replacement run's counters and schedule. The failure ladder now
lands under the same lease guard as every other member write.
* fix(knowledge): tombstone and resurrect only under the lease
The document lifecycle's tombstone and resurrection writes ran outside the
lease guard, so a run reclaimed after its ACL transaction could hide a
document the replacement restored or expose one it removed. They now run
in the same lease-guarded transaction as every other member write, and a
run whose lease is lost while it disables itself ends as superseded rather
than rejecting.
* fix(knowledge): prove the lease before a batch's document writes
Hydrating a batch can outlast the lease. processDocOps now takes the strict
lease probe before persisting anything from a batch, so a run replaced
during hydration cannot land stale content or queue processing over the
replacement's; it ends as superseded. Both engines share the guard.
* feat(knowledge): one click connects a Sim Search source and indexes it for the person
Connecting a source on the Search tab, or from the composer's Search-mode
suggestions, no longer creates a bare credential that indexes nothing. It
finds or creates the workspace's Sim Search knowledge base and a per-member
connector for the source, then enrolls the person; the OAuth completion
queues their member run, so indexing starts on its own and the row counts
their documents up as they land. Sources that need a site or space are set
up from a knowledge base instead. The credential-only detail page goes.
* feat(knowledge): the composer's Search mode shows every source and reads like a search
- Under the input, Search mode lists every Sim Search source as a chip with
the person's own state: connected with a document count, indexing,
reconnect, or one click to connect; sources that need a site link to
Knowledge. The sampled four-row list goes, and with it the rows that
offered sources the server had to refuse
- Results carry a header (how many documents, searched as you, and which
source is still indexing), hover actions to copy the link or summarize,
an Answer with Sim action for a prose answer, and source and recency
filters once a list is long and mixed enough to need them
- An existing chat opens in Build; a new chat keeps the last mode. Results
never join a transcript
* fix(knowledge): process connector-owned documents as the system
Members-mode documents are inserted hidden until the member sync
materializes who observed them, so the processor's own source-file read,
authorized as the actor with workspace scope, denied every document a
per-member connector created. Connector-owned rows now read their source
as the system; uploads keep the actor's authorization.
* feat(search): connect every personal source in place
The Sources strip lists only what a person can connect themselves and
asks for a source's required setup (a site, a space) in a small modal on
the first connect; sources an admin must set up as workspace connectors
no longer appear as dead chips. The indexing loader spins, the query
stays in the composer after a search, and the knowledge-base page drops
the per-member sync banner.
* feat(search): keep the results familiar to a search page
A result's second line names its source app rather than the knowledge
base, emptying the search box returns to the sources, and the arrow
keys walk the result links.
* feat(knowledge): sync Google Chat, Meet, Sheets, Bitbucket, and Airtable per member
Google Chat lists only the spaces the caller belongs to, Google Meet only
the conferences they organized, and Google Sheets, Bitbucket, and Airtable
one configured spreadsheet, repository, or table that a member either can
read in full or cannot reach at all, so each now declares its listing caps
and can sync per member. Sheets, Bitbucket, and Airtable report a 403 or
404 on their configured scope as a complete listing of nothing for that
member; Bitbucket reads a zero cap as unlimited instead of refusing it.
Google Chat, Meet, and Sheets join the Google managed OAuth providers, and
Bitbucket gains a managed policy that takes its subject from account_id
and its address from the confirmed primary email, requesting the email
scope that needs.
HubSpot stays a workspace connector: HubSpot documents that an OAuth token
reflects the app's scopes, not the authorizing user's record permissions.
Google Vault needs the Vault admin privilege and Trello authorizes through
its own OAuth 1.0a flow rather than a managed OAuth 2.0 connector.
* feat(knowledge): sync Microsoft connectors per member
Microsoft Teams, Outlook, OneDrive, SharePoint, and Microsoft Excel list
only what the caller's own account can read, so each now declares its
listing caps and can sync per member. Outlook reads a 0 conversation cap
as unlimited instead of the default. A team, channel, folder, site, or
workbook Graph answers 403 or 404 for reads as a complete listing of
nothing for that member, as does a channel or folder the member's own
listing does not show.
A Microsoft managed OAuth policy lets a Credential Group collect each
person's account: the id_token is verified against the identity
platform's keys and bound to the access token through the OIDC userinfo
subject, the person is recorded by oid and tid, and the email counts as
proven only through the claims Entra vouches for.
* fix(knowledge): close the connector access-switch and members-mode update races
- Leaving members mode dispatched the first workspace sync against a fresh
clock read while the row held the flip's nextSyncAt, so the queue refused
it as stale; the dispatch now asserts the instant the flip wrote.
- A workspace credential change kept the incremental watermark, so the new
credential's corpus was never fully listed; it now drops lastSyncAt, makes
the sync due, and refuses under a CAS while any sync owns the row.
- Both switch directions released the lease before revoking the previous
group's grant, and a revoke drops the connector from every option of the
group; the lease now outlives the revoke.
- The members-mode flip and the members-mode create lock the Credential
Group row and re-check the option under it, the same lock the group's
option removal and delete hold while they look for bound connectors.
- Members-mode updates wrote interval changes and resumes to nextSyncAt,
which the member scheduler never reads; they now land on nextMemberSyncAt
under the matching CAS, a running member run refuses every edit, a queued
one refuses config edits, and a pause releases the queued entry.
* fix(knowledge): close member-sync races found in review
- sweep stale member observations under the connector share lock and the
member row lock, re-checking mode and staleness so a run's fresh
observations and a mode switch's ACLs are never overwritten
- gate the member queue CAS and lease on connector status and on the
schedule the dispatch was made for; keep dispatching after one failure
- prove the run lease inside every connector document write transaction
- drop the per-member page cap on listing passes; a capped listing could
never reach the documents behind page 200
- issue member invitations with reject-on-revoked so a concurrent
revocation is never reactivated
- re-apply the caller's access at document delete and upsert-replace
- keep sourceModifiedAt/connectorType on provenance-bearing searches
- read Google Calendar's updatedTime as the source modified time
* fix(knowledge): resolve Sim Search review findings
- Sim Search connect: the first connect of a source requires a workspace
admin and refuses everyone else with the way forward; per-member
availability is checked before anything is created; creation runs under
a per-workspace advisory lock with a re-check; the route forwards the
source's setup fields
- Connector access switch: workspace mode requires credentialId in the
contract and the credential must belong to the connector's provider
- Base64 hydration reads knowledge-base files as the run's principal
- Search surfaces gate on the workspace's per-member access flag; search
results skip legacy personal bases, surface list errors, and report
indexing across every per-member connector
- Enrollment hook: explicit copy for failed/disabled member sync, awaited
connections are dropped once connected, each path clears the other's
error; Search mode keeps its query in an existing chat and keeps its
context chips diffable; citation labels are Markdown-escaped; an access
switch also refetches per-document caches
* fix(connectors): withdraw member access on unreachable scopes and page unlimited listings
Gmail treated the members-mode cap of 0 as "capped after the first page",
so a member's sync never listed past 100 threads and could never withdraw
access. Box turned a subfolder a member cannot reach into a capped listing,
which suppressed removals forever; the members-mode crawl now marks its
sync context, and Box takes the skipped folder as absent from that member's
complete listing while a shared credential still caps. Google Calendar with
several calendars withdrew everything when one calendar answered 404; per
member it now skips only that calendar. JSM classifies 403 (a service desk
the caller may not view) alongside 404, and the Atlassian connectors also
treat a token that reaches only other sites as not on the site. Monday
reports every configured board coming back absent as the scope being
unavailable. Salesforce classifies 400 INVALID_TYPE and 403
INSUFFICIENT_ACCESS as the object being unreadable, and filters on
LastModifiedDate with supportsIncrementalSync so member passes stop
enumerating the whole org. The duplicated Graph listing error helper moves
into the shared connector utils.
* feat(search): make a search a shareable link
The composer's Search-mode query lives in the URL as q, so a search can
be bookmarked or sent; opening such a link restores the query and Search
mode.
* test(knowledge): pin member-access availability in the v1 search route test
* refactor(search): apply the cleanup passes to the Sim Search surface
Drop three memos over cheap derivations, make the search setter's
callers honest about their dependencies, ignore a whitespace-only query
from a link, give a dropdown setup field its hint, and drop the query
from the URL when the composer leaves Search.
* refactor(search): apply the simplify passes to the Sim Search surface
One availability gate for every members-mode refusal, the shared role
gate behind the admin-first message, setup fields precomputed on the
catalog, the connect flow owned by the enrollment hook and shared by the
strip and the Search page, the latest attempt derived instead of
cross-resets, a trailing adornment slot on the chip in place of a loader
wrapper, the processor's source access as one object with the
connector-row rule in one place, and the first connect's independent
lookups run together after its synchronous checks.
* fix(connectors): keep per-member listings complete across partial scopes and blank caps
Teams, SharePoint, and OneDrive skip one of several channels or a descendant
folder a member cannot reach instead of failing the whole listing, which the
members-mode crawl would read as the member reaching nothing. Gmail and
Outlook keep their default cap for a null, empty, or whitespace field rather
than lifting it, through a shared parseDefaultedUnlimitedSafeInteger. The
Confluence incremental CQL clause is fixed on the first page so a cursor is
never paired with a query that crossed a minute boundary.
* fix(knowledge): address review threads on search surface, lease-guarded dispatch, and selected-output principal
- Guard the processing-queue write and dispatch with the sync lease so a reclaimed run neither marks nor enqueues processing
- Pass the executing principal into the final-frame selected-output context
- Read JSM statusDate as the source modification time
- Keep a first-connected Sim Search source non-actionable until its membership row appears
- Render the Build/Search switcher only for the Home composer
- Keep every Search-mode submit out of the agent; attachment-only submits do nothing
- Skip the member-connector fetch and 'still indexing' note when per-member access is off, and scope it to the searched bases
- Queue the workspace member-connector list on a members-mode sync trigger
- Log a refused clipboard write on the source card instead of leaving it unhandled
* fix(connectors): validate Gmail's thread cap with the sync parser and reject invalid Date metadata
* fix(knowledge): prove the lease inside every ACL rewrite batch and harden source-modified-time parsing
* fix(knowledge): claim a member only under a proved lease and read email conversation dates
* feat(search): show the matching passage and the author on each result
A result's snippet is the window around the first query term, skipping
the header block an email carries, so the row shows why the document
matched; its meta line names the source, the person behind the document
from its author-like tag, and the date. The agent's citations carry the
author too.
* refactor(search): style the results and sources as one surface with the composer
Result rows take the chat surface's row rhythm with hairlines between
them, fade-clipped titles and meta lines, a proper icon button for Copy
link, a ghost Summarize matching Answer with Sim, actions revealed on
keyboard focus, and a linkless document rendered in the same row with
its author, date, and bolded passage. The source and date filters live
in the URL beside the query, cleared with it. The sources strip keeps
connected chips at full weight, and the member-connector query is gated
with an enabled option and cancelled before an optimistic queue write.
* fix(search): safe result links, script-aware term matching, and honest header stripping
A result links only to an http(s) URL; term matching judges word edges
by the surrounding characters instead of ASCII \b and strips quotes
from a phrase, and the same matcher bolds the passage; a chunk that is
nothing but fields keeps its content; the agent leaves unknown optional
citation fields out and keeps the tool's published result count; route
errors log the wrapped cause and Postgres code.
* fix(search): no cached member rows with access off, no double enrollment, code-point-safe matching
Surfaces consume member-connector rows only while the feature is on;
the Search page treats an awaited enrollment, including a first
connect, as non-actionable; a refused members-mode sync rolls back only
the member lists; result actions show on pointers without hover; route
error causes go through the redacting describer; the citation template
is valid JSON; term edges and snippet windows respect code points.
* fix(knowledge): create a Sim Search source without holding a transaction across the nested use cases
The first connect held an advisory-lock transaction while the nested
base and connector use cases queried the pool, which the transaction
tripwire now refuses, so every first connect of a new source failed.
Concurrent first connects are coalesced per workspace base and per
source within the process and re-check before creating instead.
* fix(search): admin-gated first connect on the surfaces, live indexing state, honest filters and loading
Route errors redact bound values from the outer message too; a source
nobody connected is offered only to an admin and others see why; a first
connect refreshes the base's connector list; member connectors poll
while a source is indexing for the viewer; a filter from a shared link
applies even when the controls would not appear; results kept from the
previous query show as loading.
* improvement(routes): log the deepest cause's stack outside production
* feat(home): add Ask mode, an agent turn grounded in the searched sources
* fix(home): keep the composer on the live search query, not a mount-time snapshot
* feat(home): make Ask turns answer from the searched sources with the knowledge tool alone
* improvement(chat): name the query in the knowledge search row and list a reply's sources densely
* fix(home): carry the Ask request mode through every send lane and refuse every non-server tool on an Ask turn
* improvement(chat): put a reply's sources behind a counted button in the action row, and keep Ask follow-ups to questions
* feat(chat): let the agent use the person's own Credential Group credentials, and keep integrations on Ask turns for questions knowledge cannot answer
* fix(knowledge): treat a reclaimed lease during a member purge as superseded; tidy the chat reply sources after cleanup
* improvement(home): fold Ask into Search behind an Answer toggle
* fix(credentials): prove a Chat managed-credential use only from a real tool call, and list or mint only live group bindings
* improvement(home): name both choices in Sources mode with a Search / Assistant toggle
* improvement(home): make Assistant a peer of Build and Search in the mode switcher
* improvement(home): keep the composer mode in the URL and drop the mode store
* fix(home): let Search be chosen inside a chat now that the mode lives in the URL
* fix(chat): scope the managed-credential listing to the group's workspace and carry only chat params on the handoff
* fix(credentials): refuse a managed credential whose group or option is disabled on every mint, workflow runs included
* fix(home): clear the composer when a result is handed to the Assistant, follow the search query in a chat, restore a queued message's mode, and seed the base list
* fix(knowledge): budget the pending ACL rewrite per run, and converge a racing first connect on the oldest base and connector
* fix(home): ground an Assistant send from the query cache instead of growing the page graph with a prefetch
---------
Co-authored-by: Emir Karabeg <emirkarabeg@berkeley.edu>
|
||
|
|
51d2118ecd |
feat(tools): run one integration tool over v2, and fix the ones that could not be run (#7374)
* feat(tools): run one integration tool over v2, and fix the ones that could not be run
Adds `POST /api/v2/tools/{toolId}/execute` and `sim tools execute <toolId>`,
then fixes the 119 tool parameters that made the same call impossible through
Copilot.
The catalog already published every tool's parameters and outputs; there was
no way to supply them. The only execution endpoint on v2 was
`POST /workflows/{id}/execute`, so a caller could read that `gmail_send` takes
`{to, subject, body}` and still had to wrap it in a workflow to send the mail.
Building it surfaced the second half. Copilot authorizes integration tools when
their schemas are built — `projectIntegrationToolsForViewer` decides what the
model is told exists — so by dispatch the id has been vouched for. An endpoint
whose caller types the id has to make those decisions against it, which is what
the use case does, and which is how the parameters below came to light.
117 of them are mislabels: mailchimp and zendesk mark a user-typed API key
`hidden`, which firecrawl spells `user-only` for the identical shape, and
pipedrive and wealthbox omit the `oauth` declaration that fills the
`accessToken` they correctly hide. The other 2 are not — calcom's `attendee`
and mistral's `file` are composed by their block at serialization time, so
`hidden` was right until a caller could reach the tool directly.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(mistral): align MistralParseV3Block on the tool's `file` parameter
`check-block-registry.ts` requires every required `user-only` tool parameter to
have a subBlock whose `id` or `canonicalParamId` matches it, because the
serializer resolves those by direct lookup and a mismatch false-flags the field
as missing at submit time. V3's subBlocks carried `canonicalParamId: 'document'`
against a tool parameter named `file`, bridged by the block's params mapper.
Aligning them needs no migration. Saved state is keyed by subBlock id
(`fileUpload`, `fileReference`), which is unchanged; `canonicalParamId` is a
config-derived index rather than a storage key. `data.canonicalModes` is keyed
by canonical id, but `backfillCanonicalModes` re-derives a missing entry from
whichever value is populated, so a workflow using the advanced file-reference
field still resolves to `advanced` on open.
V2 keeps `document`: only V3's `file` parameter is `required`, so only V3 is
under the contract.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): reject a direct call missing a required user-only input
`validateRequiredParametersAfterMerge` checks `user-or-llm` parameters alone,
because on the workflow path a `user-only` parameter was already validated
during serialization against the block field that holds it. The v2 execute path
has no serialization step, so nothing had checked them: omitting
`zendesk_get_ticket`'s `subdomain` reached Zendesk as `undefined` and came back
a provider authentication failure — the same undiagnosable shape this branch
set out to remove.
The check exempts a parameter Sim supplies itself, mirroring
`injectHostedKeyIfNeeded`'s three tests in the same order so the two cannot
disagree about whether a value is coming. `firecrawl_scrape` stays callable
with no `apiKey` where keys are hosted, and requires one where they are not.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): require every input the caller is the only source for
The previous commit gated the check on `user-only`, which reads the visibility
taxonomy as if it constrained who may send a value. It does not. `visibility`
describes editor roles — a human filling a block field, the agent block's model
choosing an argument, either, or neither — and a direct call has no editor and
no agent block, so those roles collapse to one caller.
`createUserToolSchema`, which this endpoint and Copilot's
`call_integration_tool` both publish, already says so by omitting `hidden` and
nothing else.
So the rule is not about roles: Sim supplies it, or the caller must. Skipping
`hidden` stays safe because `check-tool-param-reachability` fails any required
hidden parameter without a declared filler.
Concretely this closes `thinking_tool.thought`, the one required `llm-only`
parameter in the registry, which the narrower check let through as `undefined`.
It also moves required `user-or-llm` inputs to a pre-dispatch failure naming
every missing field at once, rather than the merge validator's first-failure
mid-execution.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): address the cubic review round on direct tool execution
Two were real defects rather than polish:
The usage ledger de-duplicates on `eventKey`, and the derived key hashes actor,
workspace, source and description — identical for every call to the same tool.
`onConflictDoNothing` therefore billed the first hosted-key call and silently
dropped every one after it. A workflow run has an `executionId` to separate its
rows; a direct call has nothing, so it now mints one.
Undeclared input keys reached the executor. `impersonateUserEmail` is read
straight out of params and forwarded to credential-token resolution as an
impersonation request, and no tool declares it. The two ad-hoc denylists are
replaced by a declared-parameter allowlist — the actual boundary, and the one
`GET /api/v2/tools/{toolId}` already publishes.
Also: renaming a canonical id orphans `data.canonicalModes`, and the backfill
recovers it only when one side holds a value. `setBlockCanonicalMode` writes the
mode without clearing its sibling, so a workflow holding both would have
silently switched from the typed reference to the uploaded file.
`migrateCanonicalModeIds` carries the key across, ahead of the backfill.
Smaller: the reachability audit now mirrors execution exactly, exempting
`credentialType` only under `authoritativeParams` and refusing to treat
conditional hosting as a guarantee; the boundary guard splits on both path
separators so it still excludes the execute route on Windows; the route stops
documenting the 409 and 423 it cannot produce; and `sim tools execute` prints
the output it promised in the human formats.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): bill only spend that was Sim's, and scope the boundary predicate
Metering read `output.cost.total` and billed it. That field is not a hosted-key
marker: `knowledge_upload_chunk` and the enrichment runner report their own cost
there, so a workspace would have been charged `api-tool` spend for something
already metered elsewhere, and a failed call carrying a cost billed too. The
registry writes hosted-key cost under exactly two conditions —
`hostedKeyInfo.isUsingHostedKey && finalResult.success` — and metering now
matches them.
`hostedKeyParamFor` derives the first of those the way `injectHostedKeyIfNeeded`
does, including the test the earlier version omitted: a caller's own key wins,
so supplying one means Sim's key was never spent. The same helper answers the
other question that turns on it, since a required parameter Sim fills is not a
missing one.
The boundary predicate matched `execute` anywhere in the absolute path, so a
checkout living under a directory of that name would have excluded every
catalog route and retired the guard silently. Now derived from the path relative
to the app, still split on either separator for Windows.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): refuse a caller-supplied hidden parameter
Declared was being treated as accepted. A `hidden` parameter is Sim's to fill —
a resolved credential's `accessToken`, a hosted key, a block-composed shape —
and `createUserToolSchema` omits it from what this endpoint and Copilot
publish. Accepting it anyway either let a caller pre-empt the executor's value
or silently discarded theirs when the executor overwrote it; either way the
published schema made no such promise.
The accept-set is now exactly the publish-set: a key is taken if and only if
`GET /api/v2/tools/{toolId}` lists it as something the caller may send. This is
the rule the required-input check already followed ("Sim fills it, or the caller
must"), applied to the other direction.
Verified live against a dev server: a forged `accessToken` on `gmail_read_v2`
is refused before dispatch, and the credential-backed read still succeeds.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): honor a tool's declared credential selector, and refuse its aliases first
Sixty-eight tools — Snowflake among them — declare the credential selector as a
required `user-only` parameter (`oauthCredential` or `credential`) with no
`oauth` block, filled by their block from an `oauth-input` field. The
required-input check ran against the raw body, before the top-level
`credentialId` had been placed anywhere, so a valid credential was rejected as
a missing `oauthCredential`. And the alias refusal ran only over *undeclared*
keys, so `input.oauthCredential` on such a tool passed the declared-key check
and bypassed the top-level field — credential precedence differing per tool.
The credential is still named once, at the top level. It now lands under
whichever selector the tool declares (or `credential`, which the executor reads
for OAuth resolution, when it declares none), and required inputs are validated
against what the executor will actually receive. A declared required selector
also demands `credentialId` up front, the same as an `oauth` block does. The
alias refusal is unconditional and runs first.
Verified live: a Snowflake call with a top-level credential passes the
validator and fails downstream at resolution; `input.oauthCredential` is
refused; omitting the credential names `credentialId` as required.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tools): read the registry's hosted-key verdict instead of re-deriving it
The metering gate re-derived "did Sim's key pay" from the tool's hosting config
and whether the caller omitted the key. That cannot see a workspace or
organization BYOK key, which `injectHostedKeyIfNeeded` injects while reporting
`isUsingHostedKey: false` — the org's own key, not billable — so the derivation
called a BYOK call hosted.
The registry's verdict does propagate, by one path. On a tool with `hosting`,
`output.cost` has a single writer, `applyHostedKeyCostToResult`, and it runs only
under `isUsingHostedKey && success`. A BYOK call, a caller-keyed call, and a
failed call all leave the field absent. The gate now reads that: `hosting`
present, success, cost present. The derivation stays for the one question it
can answer before dispatch — a parameter Sim will fill is not missing.
The reading rests on hosted tools not reporting their own cost in that field,
which is true of all 131 today and now pinned by the reachability audit, so a
future hosted tool that self-reports fails CI rather than billing BYOK calls.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(audit): exempt a token-response field only where the tool declares it
The reachability audit treated seven credential-derived fields as guaranteed
fillers for a required hidden parameter on any OAuth tool. Only `accessToken`
is: the resolver assigns it unconditionally. `idToken`, `instanceUrl`,
`apiDomain`, `cloudId`, `domain` and `authStyle` are assigned under
`if (data.X)` — present on some providers' credentials and absent on others —
and `credentialType` additionally only when the tool lists it in
`authoritativeParams`. Whether a credential carries one is a fact about the
provider that the resolver cannot vouch for.
The tool can. `oauth.authoritativeParams` is already the declaration that the
token response supplies the named field, and every real case — the eight
`microsoft_dynamics_365_*` tools hiding `instanceUrl` — already lists it. So a
required hidden parameter in that set is now exempt only when its tool declares
it there, generalising the rule `credentialType` alone had. A tool that hides
one without declaring it is asserting a filler the resolver may never run,
which is the shape this audit exists to reject.
Mutation-tested at the real declaration site: stripping `authoritativeParams`
from `DYNAMICS_365_OAUTH_CONFIG` fails the audit naming all eight tools with the
remedy; restoring passes. Nothing is flagged on the current tree.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
||
|
|
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.
|
||
|
|
479ae8c138 |
fix(cli): seven defects found by live-testing the CLI against staging (#7176)
* fix(catalog): resolve an unversioned tool id against the visible set `tools get github_comment` answered NOT_FOUND while `github_comment_v2` worked, though the toolId help promises an unversioned name resolves to the newest version. A superseded tool stays in the registry, so `resolveToolId` short-circuits on the exact hit and returns it unchanged; the visibility gate then refuses it because no visible block exposes a v1 tool. 204 base names were unresolvable this way. Resolution now walks the visible set newest-first, the way blocks already do. `resolveToolId` is untouched — execution depends on an exact id returning that exact id, and none of the 5182 visible ids change under the new path. * fix(files): resolve an archived folder path through its active ancestors The archived folder listing built its path map from the archived rows alone, so a folder whose parent is still active came back as its own name. Deleting `a/sub` and restoring `a/sub` therefore disagreed — restore only matched the truncated `sub` — and the path and parentPath fields were wrong. The extra read is taken only for the archived scope; active and all keep their single query, which a test now pins. Restoring by path also stopped guessing. Archiving, recreating and archiving again leaves two archived folders with the same canonical path, and the resolver took the first match, silently restoring the wrong one. It now refuses and names the folder-id form. * fix(v2): answer a folder-list miss with an empty page A parentPath naming no folder returned 404 on the workflow, table and knowledge folder lists, and an empty page on files. The rule the codebase already publishes is the empty page: V2_FOLDER_FILTER_MISS is appended to the folderPath filter on six list surfaces, and resolveFolderPathFilter documents why a list must not become an existence oracle — a 404 claims the collection is missing and breaks a walk when a folder is deleted mid-pagination. Both TSDocs asserted the sibling folder lists already behaved that way. They did not; that premise is corrected here too. Mutations keep every 404. The miss short-circuits before the row query, because an unfiltered parent id lists the whole workspace. * fix(cli): gate activating a deployed version `workflows activate create` switched which version production serves with no confirmation, while `rollback` refused without --yes. They are the same application operation under two transitions, so gating one and not the other was an accident of naming. The destructive-operation classification in the client tests listed activate as non-destructive, which is what kept its sweep from noticing. Moved, so two independent tests now hold the gate. * fix(cli): name the profile in the suggestion configure prints Refusing a root global printed a command to save it — without --profile, so following it verbatim wrote the default profile and left the named one untouched. The neighbouring suggestions in this file already carry the flag. Resolution matches resolveProfile, so SIM_PROFILE is covered too, and the profile name is redacted like the value beside it. * fix(cli): fail a row delete that matched nothing `tables rows batch-delete` exited 0 when none of the named rows existed, while the table equivalent exited 1 on the same shape. Only the id-list selection is checked: a filter answers without a requested count, so the guard self-excludes and an idempotent sweep still exits 0 on its second run. * fix(cli): show the -- escape for an id that opens with a dash Short ids draw from a 64-character alphabet containing one dash, so 1 in 64 open with one and commander reads it as an unknown option. It reaches `audit-logs get` and the custom-tool commands, and the escape was documented nowhere. The hint is appended only for a lone dash followed by two or more characters carrying an uppercase letter or digit — a shape no flag on this surface has — so a misspelt flag keeps commander's own suggestion. * chore: regenerate the API reference and CLI surface * fix(cli): quote a profile name a pasted command would otherwise split The suggestion configure prints is meant to be pasted, and it interpolated the profile name bare. Profile-name validation is creation-only by design — the validator says so, because a hand-written `[profile my stack]` has to keep resolving — so a name carrying whitespace, or a `;` that would end the pasted command and start another, reaches this message unchecked. Names that already satisfy the creation rule stay bare; the rest are single quoted, embedded quotes included. Redaction runs first, so a control character becomes a space and is then quoted rather than splitting the command. |
||
|
|
c930830310 |
fix(v2,cli): second audit pass over the v2 API and CLI (#7126)
* fix(chat): resolve a caller-supplied conversation id through its owner The v2 chat route used the caller-supplied conversationId verbatim, with no existence, owner, or workspace check, against a store keyed by bare text with no owner column. A caller who knew another user's conversation id reached that conversation. Ids now resolve through the same owner-scoped loader the web chat path uses, and anything unresolvable answers one uniform 404 before any lifecycle work runs. Omitting the id mints a server-issued conversation. The contract also accepted any 1-128 character string for a column typed uuid, so a malformed id raised a driver error and rendered 500 while an unknown but well-formed id rendered 404 - a shape oracle, and a 500 on ordinary input. The ownership predicate had no coverage anywhere: the route test mocked the module and the lifecycle test drove a chain mock that ignores its where clause, so deleting the owner condition left both suites green. It is now asserted by composition and by condition count, which is what catches a dropped condition. Also renames the reply's model identifier away from a term the project's own copy rules forbid on a user-facing surface. * fix(v2): conceal workspace absence, and stop archived tables faulting their page Two reads answered a caller more than they were entitled to know. A workspace a caller cannot reach at all returned FORBIDDEN while one that does not exist returned NOT_FOUND, so a workspace-key holder could enumerate which workspace ids exist by diffing the two. Both now answer the same absence, using the concealment policy the billing routes already use. A refusal from inside the workspace - a member whose role is too low - still answers FORBIDDEN, because that caller already knows the workspace exists. Separately, archiving a folder cascades onto its tables but leaves each table pointing at the archived folder row. The archived listing resolved those paths strictly, so one such row faulted the whole page and no cursor could step past it - which also made the ids undiscoverable and left restore unreachable for exactly the tables that need it. The archived scope now resolves leniently to the root, where a restore would place them, matching the shipped workflows behavior. Active listings still fault loudly on a dangling folder. * fix(knowledge): validate upload processing options without stranding live sessions recipe and lang were accepted as free strings up to their length caps, silently discarded, and echoed back nowhere, so a typo was unobservable: uploading with a misspelled recipe returned 200 and quietly used the default. Both are now validated at the boundary and a bad value answers 400 naming what is accepted. The accepted recipe set deliberately includes the sentinel every first-party caller sends today alongside the three real chunker recipes, and the three are derived from the chunker's own union so removing one there is a compile error here rather than a silent 400 in production. The same schema also parses metadata read back off a persisted upload session, so tightening it would have thrown out of resume and complete for any session created before this - a 500 on work that could then never finish. The read-back path now drops a value it no longer recognises instead of rejecting it; the request boundary stays strict. Neither field reaches chunking, so nothing here moves chunk boundaries, embeddings, or search results. * fix(v2): honour a requested stats window, and answer a claimed graph id with a conflict Log statistics accepted a start and an end, filtered the totals by them, and then built the series against wall-clock now. Bucket width was computed over a span the caller never asked for, and every bucket past the requested end was structurally empty - so a bounded historical query returned a wrong-width series with fabricated trailing buckets, under a window label that disagreed with the request. Each edge now honours the bound it was given and keeps its previous derivation when omitted, so an unbounded request is unchanged. Separately, block, edge and subflow ids are global primary keys while the delete that precedes a state replace is scoped to one workflow. An id owned by another workflow survived that delete, the insert violated the key, and because callers pass their own transaction the driver error escaped unclassified as a server fault. The write now refuses such an id up front with a conflict naming it, and re-classifies the same violation if one races past the check, since the lock covers only the workflow being written. The dry run checks the ids a commit would insert and reports the warnings a commit would report, which is what its own contract already promised. * fix(secrets): let a workspace secret change its metadata without resending the value Restoring redaction cost more than removing it. The only way to flip a secret back to redacted was to re-send the plaintext, because the write required a value and omitting it fell into an interactive prompt that cannot run in CI. A workspace secret can now change its description or visibility on its own; the stored value is never re-encrypted or rewritten, a write that names no existing secret answers not-found rather than creating one, and a personal secret still requires a value because it has no other writable field. The path parameter was also one shared schema across the write and the delete, so a single description had to cover both and the delete documented an argument that could create and replace. Split, mirroring the credentials pair. The metadata write is a new update against the credentials table, so its scope is asserted by composition and by condition count: an unscoped update would let one workspace flip another workspace's identically-named secret out of redaction, and the cache invalidation would then carry that flag into the other workspace's runtime catalog. * fix(v2): say what an error means in terms the caller can act on A size-limit refusal collapsed every value under a kilobyte to "0 Bytes", so a 28-byte file over a 27-byte ceiling read "is 0 Bytes, above the 0 Bytes limit" - self-contradictory, and useless for choosing a value that would work. Errors and field descriptions also told callers to invoke raw HTTP endpoints. These strings serve the REST reference and the CLI's own help equally, so they now name the operation and its object rather than a method and a path. A sweep test walks every v2 schema description and holds the line, with the remaining offenders in files this change does not own recorded explicitly rather than left to be rediscovered. Listing the editors of a built-in skill claimed the skill did not exist, while reading the same id succeeded - a well-formed request for a real resource is not malformed, so the list answers an empty roster and only the mutations refuse. Bulk folder deletion recorded only the leaf name in its audit trail while the single delete recorded the full path, leaving two same-named folders under different parents indistinguishable after the fact. Bulk chunk enable, disable and delete each treated an unmatched id differently behind one sentence of documentation. They now follow one rule. A workspace-scoped list refused with the name of a resource the caller never addressed, which reads as an empty workspace rather than an unreachable one. * fix(cli): stop a config value forging a section it was never meant to write The config file is written by joining names and values into INI lines, and nothing checked what was in them. A profile name carrying a newline and a section header wrote a section that merged into a different profile and took over its endpoint - and the next command sent that profile's stored API key there. A workspace value could do the same from the other side, since only the endpoint flag validated its input. The refusal now lives at the writer, the single place untrusted text enters the document, with the flag-level checks kept for the better message. Either alone blocks the forgery; the pair is deliberate. Rejecting rather than escaping, because the format has no escape syntax and these files are hand-edited and read by other tools that would not decode one we invented. The forbidden set covers control characters and the two Unicode line separators, which the previous guard missed - those parse as an unreadable line, so the key silently vanished on read and the next write appended a duplicate while the command reported success. Login also wrote the key before the settings, so a malformed response from the deployment could leave a key on disk with no endpoint beside it, and the next command would send it to the default host. Settings are written first, and the response is checked before anything touches disk. Name validation applies only when creating a profile, so a hand-written one that predates the rule keeps working. * fix(docs): tell the reader which key a command needs, and stop the ids contradicting the CLI Around sixty v2 operations refuse a workspace API key, and the CLI's help said nothing about it - the caller found out from a 403 after the request went out. The restriction is already stated in the API spec, so the generator now reads it from there and the command description carries it. The sentinel sentences are imported from the spec's own constants rather than copied, so a reword cannot silently unmark every command, and the test pins the count as well as named operations because a reword confined to one family would otherwise slip past. The generated reference also rendered an empty default as a sentence pointing at nothing - "Defaults to ." - for every repeatable filter. Omitted now, while false and zero still render, which is the trap that shape of check usually walks into. The hand-written guides used a workflow-shaped id for workflows that the CLI's own help says never names one, and five other families were equally wrong. All of them now match the scheme the CLI declares, consistently per entity across pages, with the shared ones taken from that help text so the two read as one voice. The page documenting every flag was linked from nowhere; both landing links pointed at the overview instead. And the generator's test file was absent from the hand-maintained list CI runs, so its guards never executed. * fix(cli): stop a page-size default capping a destructive filter Every request field named limit inherited the pager's default of 100, but only a cursor-paginated command interprets that flag. The two filter-based row mutations declare no cursor, so the default went onto the wire as a row cap: a filter matching 250 rows deleted 100, exited 0, and said nothing - while the confirmation the user had just answered promised every matching row. The flag's own help offered 0 for everything, which those endpoints reject; the unbounded form is the field being absent. The pager's default now applies only where the pager runs, and the tests pin the omission on the request body rather than in help text. A cap typed alongside an explicit row list was silently ignored; it is now refused on the client, where refusing costs nothing to already-installed versions. Lists also truncated at a hundred with no signal in any format, and the two inventory endpoints that do report truncation had that field dropped on the way out - so a caller reconciling against a clipped list could not tell. One note now goes to stderr while stdout stays a bare array, and a flag raised on a later page survives the fold. Also: a folder whose name contains the separator no longer prints a path that resolves to a different folder; validation errors name the flag the user typed instead of the wire field; an unknown subcommand with --help exits non-zero instead of printing the parent's help; a fractional or negative page size is refused rather than floored; an empty query filter is refused rather than silently returning everything; and the two spellings of the missing-workspace message became one. * fix(cli): gate destructive table imports and fix follow-mode rendering A `tables import --mode replace` empties the table before its first batch, so the only warning was in the describe. It now confirms, and the wording tells the truth per mode: cancelling a replace leaves a prefix of the new file with the originals already gone, while an append re-adds its rows if the file is imported twice. `--yes` skips the gate, and the gate runs before the file is opened. Import and export cancellation carried no describe at all; the import one now confirms, the export one records why it deliberately does not. Follow-mode output truncated cells to whatever the first row happened to measure, so a longer status or workflow name arrived clipped with no signal. Cells now clamp at a shared ceiling and pad to the lock, and the log columns carry width floors so a short first page cannot pin a column narrower than its own values. Interrupting a staged download left the staging directory behind; it is now removed on SIGINT and SIGTERM before the signal is re-raised. `--select-output` without `--follow` selected from a response that does not carry outputs, and said nothing. It is refused client-side, with a separate message for `--async`. Its describe now names what the path addresses. `secrets set` always read a value, even when only metadata flags were passed. Off a TTY that was an immediate refusal, so a metadata-only edit exited 1 in CI for a value it was never asked for; on a TTY it stopped to prompt, and the prompt rejects an empty entry, so there was no way to say "leave the stored value alone" short of re-typing the secret. The read is now skipped and the field omitted, which is what lets a metadata-only edit run unattended. On a TTY, setting only a description no longer prompts. Passing both spellings of the reveal flag is refused rather than silently resolved. Four mandatory hand-authored flags now say so, `billing logs` names its key-type scope, and the dispatch list declares its columns. * fix: close the gaps an adversarial review of this branch found A conflict handler added earlier in this branch was dead code. It read the Postgres error code off the thrown object, but the driver error arrives wrapped with the real one on `cause`, so the check returned false on its first line and the 409 never fired. Its test passed only because it threw a flat shape production never produces. It now reads through the cause chain with the shared helpers, compares the constraint name exactly instead of matching a substring of the SQL, and its test throws the real wrapped error. Resuming a conversation checked its workflow and its workspace but not its type, so a conversation created by the web surface could be continued as a CLI turn. It now refuses through the same uniform 404 as every other mismatch, which closes the same omission on the web posting path. Minting one no longer leaves a blank untitled row at the top of the Chat list. The pre-write check on a minted API key refused fewer characters than the writer does, so a key the check accepted could still fail at the write — after the endpoint beside it was already stored, pairing a new endpoint with the previous key. The two had drifted because the set was spelled three times; there is now one. A description claimed a processed count reported only the chunks that changed. The update returns every row it matched, so re-enabling chunks that were already enabled counts them all. Two OpenAPI sentences promised no conflict detection and no persistence warnings in a dry run, both of which the same branch had just made false. A described window was wrong whenever a start was supplied without an end. Listing the editors of a built-in skill answered a read with a modification refusal on the internal surface. Archived table listings could reach the strict folder projector again through a third scope value the input type still allowed. A metadata-only secret write skipped the guard its personal-scope twin has. The internal document boundary still took the two processing fields as unbounded strings. Truncation was reported only from the response envelope, so a clipped file body, row search and workflow-stats list said nothing. A staged download stopped watching for signals before it finished removing its directory, and cleared every listener for the signal rather than its own. Three tests asserted a contract constant against itself; they now drive rendered help, real argv, or real render output. * chore: regenerate the API reference, CLI surface, and CLI docs The published reference still marked a secret value required and described the delete parameter as one that also creates, the CLI surface still lacked the marker that says which operations refuse a workspace key, and the reference rendered an empty sentence for every repeatable filter whose default is an empty list. * test(cli): use the package's own delay helper in the staging poll The audit bans a hand-rolled setTimeout promise. `sim-cli` does not depend on the shared utils package, and its own idiom is `node:timers/promises`. * fix: act on a second review round, and correct two earlier claims The conflict pre-check read block ids from the wrong side. The writer inserts each block's own `id` field while the check read the record key, and the two can diverge because preparation copies a value under its key without reconciling them. Edges already read the value and subflows are genuinely keyed by the record key, so only blocks were wrong — collecting every family from the values, as first suggested, would have broken subflows instead. A minted API key carrying leading or trailing whitespace passed the pre-write check but failed the writer, leaving the new endpoint on disk beside the previous key. It is refused up front now rather than trimmed: a key is opaque, so trimming would store a value the server never issued and turn a loud failure into an unexplained 401 later. The endpoint normalizer does trim, which is what made a padded `--endpoint` fail only after the browser flow had already minted a key. A metadata-only secret write raced with deletion returned 500, because the follow-up read that only assembles the response body threw an unclassified error; it now reports the same not-found the non-racing miss already gave. An unusable output format in the environment silently printed a table instead of refusing. Two validation messages printed control characters verbatim. A dry run now reports the preparation warnings its own commit path returns. The chat route created a titled conversation and never wrote a message, so it appeared in the Chat list promising content it did not have. Both sides of a successful turn are now persisted; a failed turn still writes nothing, so a question is never stored without its answer. Two claims of mine were wrong. The earlier commit message said `secrets set` sent an empty value that overwrote the stored secret — it did not; the prompt refuses off a TTY and rejects empty on one, so the old behaviour was a clean refusal. And the delay helper commit said this package's idiom is `node:timers/promises`; the package carries its own `sleep`, which is the audit's sanctioned home and has five callers. It uses that now. Also: a test asserting a deadlock stays unclassified could not fail, since every candidate rejects it; it now pins a unique violation carrying no constraint name. Workflow ids spelled with the file prefix are corrected in the remaining fixtures, leaving the genuine file ids alone. * fix: close a credential-misdirection path this branch had opened Making the endpoint normalizer trim handled whitespace around a value but not a control character inside one, and the URL parser removes those from anywhere in its input — so a value that reads as one host could resolve to another, and the profile's key went with it. The flag and environment paths never touch the config writer, so its guard did not cover this. The normalizer now refuses the same character set the writer does, which also keeps the invariant that nothing it blesses can be refused by the write that stores it. Comparing the parsed URL back against its input was the alternative and is wrong: the parser rewrites percent-encoding, case, internationalized hosts and default ports, so legitimate endpoints would be refused. The blank-query guard tested for exactly empty, so a whitespace-only value still reached the wire — as a real zero on a numeric filter, an explicit false on a boolean one, and as an encoded space the server then rejected. It now refuses any value that is blank once trimmed, while a body string keeps its meaning, an explicit zero still sends, and a value with content around its whitespace is passed through untouched rather than trimmed. A graph-id conflict reported 409 on the v2 route and fell through the older persistence wrapper as an unclassified 500. That wrapper now classifies orchestration failures through the cause chain, which also fixes a pre-existing case where a workflow archived between authorization and the locked read reported 500 rather than 404. Persisting a chat turn claimed its row by id alone, so a conversation soft-deleted mid-turn still received the messages and was bumped back up the list. It now requires a live row. A turn whose caller hung up after the model had already answered persisted nothing, though the work was done and billed; it now persists and still reports the connection as closed. An empty workspace id from the login response was read as no workspace at all. A published description still promised a language-tag standard the schema does not enforce. The test asserting that a turn is stored before the final event drained the whole response first, so it held whichever order the code used. It now reads the stream incrementally and fails if the write moves after the event. |
||
|
|
4508ec75d2 |
fix(cli): resolve blockers and majors from a full command-surface audit (#7083)
* fix(cli): resolve blockers and majors from a full command-surface audit Audit of all 222 CLI leaves against a live deployment, plus fixes for every defect it confirmed. Blockers: - An unrecognized --profile resolved to built-in defaults, so a typo silently targeted production and transmitted the API key there. - sim logs follow sent an undeclared query key and failed on every invocation. - sim workflows run exited 0 on a failed run, so CI reported success. - knowledge connectors documents update matched rows already in the target state, making exclude and restore permanent no-ops. - PDF text layers below the OCR threshold are transcribed by a model and stored verbatim with no record that it happened. Majors include: rollback --version was swallowed by the program-level flag and silently did nothing; nullable string flags could not send null despite their help promising it; six protocol commands discarded excess arguments, dropping files on upload; sim chat crashed with EPIPE when piped to head; tables import dropped malformed CSV rows without reporting them; audit-logs required an organization id no API surface exposed; secrets could not opt out of redaction or read a value from a file; bulk deletes and moves exited 0 having done nothing; and MCP registrations were destroyed by undeploy rather than restored. Adds extraction_method to documents so OCR output is distinguishable from parsed text, and reports the applied scope on billing logs so the two ledger questions are no longer indistinguishable. * fix(mcp): bound MCP restore by server and re-check uniqueness under the lock Two gaps in the archive/restore lifecycle this branch introduced. The candidate query bounded archived rows and deduplicated to one per server afterwards, so several archived generations stacked on one server consumed the whole budget and every other server the workflow had been published on fell out of the result with no warning. Deduplication moves into SQL so the bound applies to servers, preserving most-recently-updated-per-server. The live-registration check ran before the server lock was acquired, so a concurrent tool create could land in between and the restore would un-archive a second live row for the same server and workflow, violating the partial unique index and rolling back the whole deployment. That check now runs under the lock alongside the tool-name, capacity, and metadata-budget checks it belongs with. * fix(review): address round-three review findings across CLI and server Restore now picks candidate servers by recency: DISTINCT ON forces its own key to lead the sort, so bounding on that statement kept the lexicographically lowest server ids and left a workflow's most recently used servers archived. Deduplication and bounding are now separate stages. CLI: a total miss on tables move reported only in notFound exited 0; unsetting a key or removing a profile mutated the first duplicate INI block while reads merged later ones, so the removal appeared to succeed and did nothing; an import that rejected cells but no rows showed a clean progress line; and the --run-id help implied idempotency it does not provide. Server: a run with no recorded output projection let block-name selectors past the new validation; the billing window comparison still fired on a bound that parsed but failed the shared schema; CSV rejection accounting reached only the streaming path, so buffered and synchronous imports still dropped records silently, through to the Copilot tool that reports them; case-insensitive tag name uniqueness now serializes on the knowledge-base row the delete paths already lock; and a failed sync claim reports the lifecycle reason rather than always claiming a sync is in progress. Reverts an over-scrub from the previous commit: workspace-file-imports is consumed only by Copilot, so naming save_upload and glob there is the correct remediation rather than a leak, and the sweep that guards against leaks now exempts it explicitly. Corrects two contract descriptions that promised a bulk tag save would rename or relocate an occupied slot, which it deliberately no longer does. * fix(cli): remove flags a caller cannot use, and correct three that misled Removes surface that should not have shipped: - `files uploads get` is hidden. Its `--upload-token` was required, and the token is minted and consumed inside a single `files upload`, which completes or aborts its session before returning. Nothing in the CLI could produce the value, so the command answered every invocation by asking for something unobtainable. The same flag is dropped from the two table-import commands, where a CLI-created import is already queryable without it. - The `--no-<flag>` companion that sent JSON null is gone. `--no-X` means "send boolean false" on thirty-seven other flags, and one spelling should not carry two meanings. `--description ''` already clears the displayed value, and the help now warns that the literal word null is stored as text rather than suggesting a substitute, because on the OAuth client fields null revokes a stored grant and an empty string does not. - The document extraction method column and its contract field are reverted. Nothing read them, they were null for every existing document, and the name collided with the parser metadata field that already exists. Corrects flags that misled: the workflow move destination is `--to`, matching its two siblings rather than meaning the opposite of `--folder` one command over; `files list --recursive` is a bare flag like the four folder deletes rather than a twelve-alias string; the dispatch row cap takes a count instead of its wire object; `--yes` no longer claims to be required on commands that accept `--dry-run`; cancelling every run on a table is confirm-gated; and the retry-processing negation, which the route rejects, is suppressed. Extends the guard that missed all of this: it swept only `--x-` prefixes over generated commands, so a header spelled without one was invisible to it. It now derives every header name from the operation table and sweeps the assembled program. * fix(mcp): budget MCP restore against the workflow's live server fanout Restore bounded its candidates at the per-workflow server limit counting archived rows only, never subtracting the memberships the workflow already holds live. The fanout validation a few lines later in the same deploy transaction counts live servers against that same limit, so a workflow with both live and archived registrations could restore past it and roll the whole deployment back. The candidate query now bounds on the remaining headroom, and the budget is re-checked under the server locks and spent once per accepted candidate, so a create that lands between the count and the unarchive cannot push it over. Candidates that do not fit are dropped by recency, matching how the set is already selected, and stay archived with a warning naming the workflow, the server, and the reason — restore still never throws inside the deploy transaction. One residual is left open deliberately: a create on a server outside the candidate set is serialized by neither the locks nor the recount. Closing it would need a workflow-level lock, which would change the ordering every other writer here depends on, and the create path runs its own limit check. * fix(mcp): stop restore spending its budget on servers it cannot restore A server can hold both a live registration and archived ones for the same workflow: the partial unique index constrains only the live row. Such a server was counted twice — once shrinking the restore budget, once consuming one of its slots — before the liveness check under the lock skipped it. While the bound was the full server limit that waste was invisible; once the bound became the remaining headroom, every slot spent that way cost a registration that could have been restored. The candidate query now excludes servers the workflow is already live on, so the budget and the candidate set agree. The exclusion sits on the inner stage, before deduplication and the bound, and is a pre-lock optimisation only: the check under the server lock stays authoritative, because the query can go stale between reading and unarchiving. Candidates rejected for a tool-name collision, the per-server cap, or the metadata budget are still not replaced. That case is only knowable under the lock, so replacing it would mean fetching past the bound and locking servers outside the candidate set, widening an ordering every writer here relies on. |
||
|
|
0c38037bf1 |
fix(knowledge): harden ingestion pipeline (#7077)
* fix(knowledge): harden ingestion pipeline * fix(knowledge): correct bounded ingestion edge cases * fix(knowledge): tighten redaction and chunk validation * fix(knowledge): close bounded ingestion gaps * fix(files): preserve parser complexity limits |
||
|
|
656840a1b1 |
feat(api): make the platform operable headless over v2 (#6912)
* feat(v2): download run output files by API key
Adds GET /api/v2/workflows/{id}/runs/{runId}/files/{fileId}, closing the
async-run loop for headless callers. A run's output carries UserFile URLs
pointing at /api/files/serve/..., which rejects x-api-key outright, so an
async run that produces a file previously had no byte path out for an API
key at all.
The file is addressed by the id the run reported and resolved against the
run's own recorded execution data, from which the storage key is read. The
request never supplies a storage key, so the endpoint cannot be aimed at
bytes the run did not produce. Resolution deliberately reads the
materialized-but-undisplayed recording, because the display projection
strips exactly the `key`/`context` fields a byte read needs.
Also hardens normalizeStartFile to derive a file's storage key only from a
validated internal serve URL, discarding any caller-supplied `key`/`context`.
A workspace API key has no human subject, so the executor resolves its actor
to the workspace billing owner (preprocessing.ts -> resolveSystemBillingAttribution);
verifyFileAccess then authorizes a workspace-context key as that owner, whose
reach is not bounded by the key's workspace. Accepting an attacker-authorable
key made that substitution exploitable as a confused deputy. Normalization is
all-or-nothing, so a forged file now drops the whole files input.
* feat(workflows): one graph-write door, principal-derived audit source, and v2 authoring endpoints
Extract replaceWorkflowNormalizedState as the single persistence primitive for a
workflow graph replace and route both the internal editor save and the Copilot
edit tool through it, so neither can skip state preparation, the row lock, the
lastSynced stamp, or custom-tool extraction by choosing a different entry point.
Derive the audit source from the acting principal instead of hardcoding
'copilot', then widen workflows.variables.apply_operations and
workflows.bulk.move to every principal kind.
Add GET/PUT /api/v2/workflows/{id}/state, POST /operations, /duplicate,
/restore, PATCH /variables, and POST /api/v2/workflows/move over surface-neutral
application use cases; move the edit engine to lib/workflows/editing.
* test(workflows): cover the graph-write primitive, audit source, and the v2 authoring surface
Pin the two-doors fix (preparation runs, the row is locked, custom-tool
extraction is post-commit and best-effort) and the false-audit fix (a session
principal writes source: 'session', a delegated one writes its service). Both
were verified to fail with the fix reverted.
Add the application matrix for replaceWorkflowState, applyWorkflowOperations,
readWorkflowGraph, and restoreWorkflow — role floor, principal-kind rejection
before canonical load, asserted-scope concealment, lock, validation, atomic
conflict, plan gate, and audit-then-notify ordering — plus route tests for
every new endpoint.
* test(workflows): pin the internal graph-write door and the v2 list scope
Characterize saveWorkflowNormalizedState's statuses, messages, and notification
after the persistence extraction, and cover the new scope filter on
GET /api/v2/workflows including a cursor replayed under a different scope.
* feat(api): add v2 block, tool, connector-type, and enrichment catalogs
Adds six read endpoints under /api/v2 that publish Sim's code-defined
catalogs: GET /blocks, GET /blocks/{blockId}, GET /tools,
GET /tools/{toolId}, GET /connector-types, and GET /enrichments.
These read like static reference data and are not. What a caller may
place is decided per workspace by its permission-group integration
allowlist, per organization by which unreleased blocks have been
revealed, per deployment by ALLOWED_INTEGRATIONS, and per workspace
again by the workflows it has deployed as blocks. So all six are plain
defineWorkspaceOperation reads at minimumRole 'read' with
workspaceApiKey 'allow' — the exact policy of credentials.providers.list
— and every response keeps Cache-Control: private, no-store, because an
unrevealed preview block's existence must not leak across organizations
through a shared cache.
Trigger blocks ride as ?capability=trigger rather than a second
endpoint, and workspace custom blocks ride inside /blocks discriminated
by `source`, so "what may I place?" stays a one-call question.
The block projection is extracted out of the Copilot get_blocks_metadata
tool and rewritten onto @/tools/metadata and @/tools/metadata-outputs.
That cuts the tool's own @/tools/registry edge as a side effect: its
module graph drops from 6,756 to 1,318, and the new routes land at
1,673-1,734, next to the shipped /v2/credentials/providers baseline of
1,668.
Supporting changes:
- scripts/sync-tool-metadata.ts derives hostedApiKey ('always' |
'conditional' | 'none') from each tool's `hosting`. The config itself
stays excluded because it holds closures, but "does Sim host the key"
is a first-order authoring question, so the answer is emitted.
- getCopilotToolDescription takes hostedApiKey as an option instead of
reading `hosting` off the tool, so both an executable ToolConfig and
the generated metadata can answer it through one shared derivation.
- principalUserId / allowedIntegrationTypes move out of
lib/credentials/application/provider-catalog.ts into
lib/integrations/principal-scope.server.ts. Two copies of the
workspace integration gate would diverge first on the workspace-key
path, which has no user for permission groups to key on.
- scripts/check-tool-registry-boundary.ts walked page.tsx/layout.tsx
under app/workspace only, so a route importing the executable registry
passed green. It now walks a list of entry sources, seeded with the
four catalog route subtrees and the shared projection barrel. Routes
are covered per subtree rather than wholesale because 122 of ~1,130
route files legitimately execute tools.
Registry sweeps parse every block, tool, connector type, and enrichment
through its published response schema and compare against the wire
round-trip. They caught a real drift while being written: an operation's
inputs were typed as a union of the tool-param and block-input shapes,
and the union resolved to whichever member matched first, silently
dropping a block input's `schema`.
* docs(api): stop publishing a 413 GET /workflows/{id}/state cannot emit
* feat(v2): read upload-session state
Adds GET /api/v2/files/uploads/{uploadId}. Only DELETE was exported, so a
caller that lost track of a transfer could abort it but could not ask
whether the session was still alive, already finalized, or failed — the
resume story was missing.
Runs on a new files.upload.read operation at minimumRole 'read' rather than
reusing uploadCancel, which is a 'write': asking about a session must not
require permission to destroy it. The GET is a control leg like every other,
so it carries the signed upload token and re-authorizes the caller's present
workspace permission through reauthorizeWorkspaceUploadPurpose instead of
resolving the session on its id alone.
* fix(api): reconcile v2 catalog and workflow-authoring integration
Merging the catalog and workflow-authoring branches surfaced four issues
that neither produced in isolation.
- Route and OpenAPI counters were bumped to the same value on both
branches, so git merged them as one change while the merged tree holds
the sum. Corrects the route ratchet to 1142 and the workflows document
to 29 operations (152 total), then regenerates the OpenAPI documents
and the CLI surface from the reconciled contracts.
- The seven new workflow operations were published in the spec but absent
from the workflow API reference groups, which `check:openapi` rejects.
- `route-policies.ts` reached `WorkflowOperationsNotAppliedError` through
`apply-workflow-operations`, dragging the edit engine — and its diff and
comparison dependencies, which reach a client OAuth hook — into every
route that uses the shared workflow error policies. The class moves to
its own leaf module, mirroring `WorkflowImportError`, and each importer
now takes it from there.
- The operations route test shadowed that class inside its module mock, so
`instanceof` matched a fake and the assertion pinned a message the
production class never emits. It now uses the real class and asserts the
real message.
* feat(v2): extract ZIP archives over the public API
Adds POST /api/v2/files/{fileId}/extract and widens files.extract_archive
from principalKinds ['session'] / workspaceApiKey 'deny' to admit personal
and workspace API keys at the unchanged 'write' role.
The widening is an authorization change, so the justification lives in the
operation's TSDoc: extraction grants no capability an API key lacks, since
every file it writes could be created one at a time through files.create and
files.upload.create, both already 'allow' at the same role. It only collapses
many calls into one. The previous ['session'] restriction read as an artifact
of the UI having been the only caller. Delegated services stay out — no
copilot or executor caller exists and admitting one is a separate decision.
The response is counts plus the destination folderPath, never the extracted
files: a large archive would otherwise materialize thousands of objects into
one body. Callers page GET /api/v2/files?folderPath=... instead. The use case
returns the internal display path and the adapter projects it to a v2 path,
keeping the use case surface-neutral.
* feat(v2): extract file text over the public API
Adds GET /api/v2/files/{fileId}/text. Text extraction previously sat behind
checkInternalAuth on /api/files/parse, a route that also mixes in external-URL
fetching, execution-file upload, and multi-file aggregation, so it could not be
reused. The parse call is lifted into a thin application use case instead.
Runs on the existing files.read_content operation unchanged — it is already
workspaceApiKey 'allow' at the read role, and turning bytes it already
authorizes into text grants no further reach.
`degraded` is a required, non-optional boolean on the response. The legacy doc
and ppt parsers deliberately return best-effort or placeholder content rather
than throwing, so an omittable flag would let a client that never checks it
treat guessed text as extracted text. It is reported honestly rather than
converted into an error, because the parsers' behaviour is deliberate and
characterization-tested.
The read is bounded on its input at 25 MiB before extraction rather than on its
output after, given the parsers' documented DoS history; a caller may lower the
ceiling but never raise it.
* feat(v2): restore archived folders and list the archived set
DELETE /api/v2/files/folders archives recursively, so a recursive delete was
unrecoverable over the API: the archived files stayed visible through
GET /api/v2/files?scope=archived, but nothing could rebuild the folder
structure.
Adds POST /api/v2/files/folders/restore, path-addressed like the rest of the
v2 folder family, and a `scope` selector on the folder list so a caller can
find the archived path to hand it.
`scope` extends the files folder-list query rather than the shared
v2ListFoldersQuerySchema: only workspace files have an archived folder set, so
adding it to the shared schema would give tables, workflows, and knowledge a
parameter they ignore. GET /api/v2/files/folders is a FULL_SET_LIST, not paged,
so no cursor binding changes — list-pagination.test.ts passes unchanged.
Restore resolves the archived folder from its path by scanning the archived
set rather than walking the live tree, which by definition does not contain
the folder being restored. The folder-restored analytics hook now reports the
folder actually restored rather than the requested selector, which carries no
id on a path-addressed surface.
* feat(v2): bulk-download a file selection as a zip
Adds GET /api/v2/files/bulk-download, an adapter over the existing
downloadWorkspaceFileItems use case and its internal binary route.
Path collision: a static segment beside [fileId] permanently shadows a file
whose id equals it, and workspaceFileIdSchema does accept [A-Za-z0-9_-]+.
Rather than invent a new shape, this follows the existing bulk-delete sibling:
the hyphenated form cannot be produced by either minted id shape (UUID v4 or
wf_<shortId>), so the shadowed id is unreachable in practice. Documented on
the contract so the reasoning is not lost.
Folders are addressed by path, matching the rest of the v2 file surface. The
paths resolve against the folder set the selection already loads, so it costs
no extra query, and a path matching no folder is rejected rather than silently
dropped — a misspelled folder must not yield a zip of whatever else was
selected. The empty-selection and folder-count guards now account for
folderPaths, which a path-only selection would otherwise have tripped.
Selections are comma-separated only: v2 rejects a query parameter sent more
than once, so a repeated-parameter form would never reach the schema. Pinned by
a test so the contract cannot advertise a form the boundary rejects.
* feat(v2): expose run output files and optional inline bytes on the runs read
GET /api/v2/workflows/{id}/runs/{runId} now reports the files a run produced,
each with the downloadPath that fetches its bytes, and can inline them as
base64 on request.
Gated by includeOutput, matching `output`'s nullability: a caller that did not
ask for output does not receive a file list it did not request. The async
execute request's rejection of includeFileBase64 is deliberately left alone —
at submit time the run has not happened, so there is nothing to inline; reading
a finished run is the first moment the question means anything.
Inlining is capped per file at the executor's 16 MiB inline ceiling, which a
caller may lower but never raise. A file above it answers 413 naming that
file's downloadPath, so the caller is told exactly how to get the bytes rather
than being left stuck.
The descriptor deliberately omits the storage key — files are addressed by id
and the key is re-derived from the run's recording — and omits an expiry, which
the recording does not carry and which would be fabricated if published.
The route becomes headSafe: false, since inlining reads object storage. The
builder enforces that this requires the use case to expose authorize(), so HEAD
still answers from a real authorization rather than from authentication alone.
* feat(v2): permanently delete an archived file
DELETE /api/v2/files/{fileId} only archives — the OpenAPI says its stored bytes
are never removed — so there was no way to actually destroy a file over the API.
Adds the repository primitive, application use case, operation, and
DELETE /api/v2/files/{fileId}/permanent.
A distinct path rather than a flag on the ordinary delete: a query parameter
that turns a recoverable archive into an irreversible destruction is set by
accident, and the two acts carry different minimum roles, which one route
declaration cannot express. The file must already be archived; a live file
answers 409 naming the archive step, so no single request can turn a live file
into lost bytes.
minimumRole 'admin', which forces workspaceApiKey 'deny' since the workspace-key
ceiling is 'write' — the desired policy anyway: unattended credentials should
not destroy bytes.
Row first, then object. The two legs commit independently, so one can survive a
crash between them: deleting the row first leaves at most an orphaned object for
the storage sweep, while the reverse would leave a live row pointing at bytes
that no longer exist — a file that lists and opens but can never be read. A
failed object delete is therefore reported as objectDeleted: false rather than
thrown, because the request has genuinely succeeded once the row is gone. Both
directions are pinned by failure-injection tests, verified to fail when the
order is reversed.
Audited as a distinct FILE_PERMANENTLY_DELETED action, not a reuse of
FILE_DELETED, which records the recoverable archive step.
* feat(api): v2 log analytics, itemized cost, filters, and sortable query
Adds the aggregate and rich-read halves of the public logs surface, and
fixes three defects the existing reads carry.
Aggregate analytics. `GET /api/v2/logs/stats` returns time-bucketed run
counts, success rate, error count, mean latency, and the window bounds,
per workflow and for the workspace. The first-party route was a raw
handler with inline SQL and inline aggregation, so it is split into a
repository (`lib/logs/stats-queries.ts`), a pure aggregator
(`lib/logs/stats.ts`), and an application use case. That route keeps its
legacy authorization — it answers a caller without workspace access with
a zeroed 200, where v2 conceals the workspace as a 404 — and consumes
only the two surface-neutral halves.
`segmentCount` had no `.int()`, `.min()`, or `.max()`, so `0` divided by
zero and `1e9` allocated two billion-element arrays: both caller-reachable
500s. Bounded on both contracts. `workflows` is capped, with the workspace
totals still computed from every workflow and the cut reported as
`workflowsTruncated`.
Detail reads gain the itemized `cost.items` ledger (`null` and `[]` are
distinct answers and both reachable) and `workflowInput`, restoring a
v1→v2 regression.
The list gains `workflowName` and `status` filters, and `includeJobRuns`,
which unions Chat and Sim-agent job runs into the sequence behind a new
`kind` discriminator — without it a job run is indistinguishable from a
run whose workflow was deleted. A filter no job row can answer drops the
branch outright rather than meaning two things across the union.
`POST /api/v2/logs/query` carries the additional sort columns. `GET /logs`
is untouched: its single `order` param rests on there being exactly one
sortable column, and both escapes from that are ruled out, so the rich
read gets its own endpoint — the split the table surface already ships.
It uses the shared keyset scheme with the two nullable sort columns read
through a sentinel, since a keyset cannot compare against null.
`folderPaths` now covers a folder's whole subtree on the public path, as
it already did everywhere else; it previously omitted every nested run
with no error. The path strings did not change, so a folder-scope version
is stamped into the cursor and in-flight tokens restart rather than
silently skipping rows.
Also fixes `folderName`, which ILIKEd `workflow.name` — a copy of the
clause above it — and so searched workflow names instead of folders.
`buildLogSortCursorCondition`'s `IS NULL` disjunct is documented and
pinned: under `NULLS LAST` the null block is only reachable through it,
so removing it as a duplicate-row fix makes those runs unpageable.
Ratchets: route count 1142 -> 1144; logs OpenAPI operations 2 -> 4; total
operations 152 -> 154.
* feat(api): v2 tables run state, dispatch polling, batch update, bulk, archive
Closes the headless gaps on the v2 tables surface.
- Per-cell run state is now readable through an opt-in `includeRunState` on
`GET /rows`, `POST /query`, and `GET /rows/{rowId}`. The default projection
is byte-identical; a page whose sidecar outgrows its byte budget is a 413
rather than a silent truncation.
- Run dispatches are addressable: `GET /tables/dispatches/{dispatchId}`
publishes the column's full four-state domain so polling a finished run is
not a 500, and `GET /tables/{tableId}/dispatches` lists what is in flight.
- `POST /rows/batch-update` takes one distinct patch per row. Its transaction
moved out of the Copilot-only module into a surface-neutral use case both
surfaces now call.
- `GET .../enrichment/{groupId}` publishes the provider cascade, cost, and
timing behind one enrichment cell.
- `POST /tables/bulk-move` and `/bulk-delete` reach the existing bulk use
cases, which now accept folders by canonical path and resolve them inside
the application layer.
- `DELETE` is recoverable: `scope=archived` on the table list plus
`POST /tables/{tableId}/restore`.
* feat(api): expose knowledge chunks, tag writes, archive/restore on v2
Closes the knowledge cluster's remaining public-surface gaps.
Chunks: list/read/create/update/delete/bulk under
`/api/v2/knowledge/{id}/documents/{documentId}/chunks`. `queryChunks` gains
an `id` tiebreaker on every sort so the list pages on a keyset rather than an
offset — `tokenCount` and `enabled` are both non-unique, so a page boundary
inside a run of equal values used to repeat or drop the tied rows. The
internal offset caller is unchanged; the two positioning schemes share one
read.
Tag definitions: create, update, delete, next-slot, usage, and the
document-scoped save and cleanup. Without them a caller could write a tag
value into a slot with no definition and then had no way to name it, so
tag-filtered retrieval was unbuildable end-to-end. `v2KnowledgeTagSchema`
gains `id`, without which PATCH and DELETE are unaddressable. The
document-scoped DELETE is pinned to `action: 'cleanup'`: the domain's `'all'`
deletes the whole knowledge base's tag vocabulary from a document path.
Archive/restore: `GET /api/v2/knowledge/archived` as a sibling route rather
than a `scope` param — the two reads bind different operations and a v2 route
declares one — plus `POST /api/v2/knowledge/{id}/restore`. `knowledge.restore`
is a new workspace operation carrying `delete`'s policy, since an operation's
inverse must not be harder to reach; the internal session route now delegates
its workspace branch to the shared use case and keeps only the legacy personal
one.
Also: `POST .../documents/from-workspace-files` surfaces `addWorkspaceFiles`,
so a file already in workspace storage no longer has to be re-uploaded
byte-for-byte to be indexed; the `chunkingConfig` write widens to the
first-party five-key schema with its refines and separator bounds, while the
response stays `.catchall` so a legacy JSONB row cannot 500; and
`CONNECTOR_MANAGED_RESOURCE_READ_ONLY` joins `FORBIDDEN_DETAIL_CODES` now that
the bare 403 on connector-managed chunk writes is wire-reachable.
Document upsert is deliberately not included.
* feat(api): add v2 credential rotation and a gate-exempt capabilities endpoint
PATCH /api/v2/credentials/{credentialId} rotates service-account secret
material or renames a credential in place, preserving the credential id so
existing workflow, deployment, paused-run, connector, and webhook references
keep working. Re-posting to POST /api/v2/credentials answers 409, and
delete-and-recreate mints a new id, so rotation previously had no door.
The route is adapter-only: updateWorkspaceCredentialUseCase already owned the
rotation, its audit projection, and credentials.update. It gains one additive
assertedWorkspaceId field for the v2 workspace assertion, and the per-principal
credential-type table that deleteCredentialUseCase already applied is lifted
into requireManageableCredentialType so both operations share it. Without it a
personal API key could rename an env_workspace row and toV2Credential's throw
would surface as a caller-reachable 500.
CredentialProviderOperationError now maps to 503 with Retry-After when the
provider is unreachable, instead of the 400 its OrchestrationError('validation')
base projected. A transient outage rendered as a permanent input error invites a
caller to revoke a working credential.
GET /api/v2/meta reports the calling key's rollout cohort, type, and expiry.
It is the one route declaring the new typed gate: 'exempt' option, because the
rollout gate and the unknown-path catch-all answer byte-identical 404s and a
gated /api/v2/meta could never resolve that ambiguity. Authentication still runs
first, so the only fact disclosed is one about the caller's own credential.
* feat(api): publish deployment lifecycle and workflow-MCP v2 surfaces
Adds the four deployment-lifecycle operations v2 was missing, and the
workflow-as-MCP publishing surface, both as adapters over application use
cases that already existed.
Deployment lifecycle:
- PATCH /api/v2/workflows/{id}/versions/{version} relabels a version.
Deliberately not the internal route's body-shape dispatch between
"rename" and "promote to live".
- POST .../versions/{version}/activate promotes a version. Same use case
as rollback under a different transition, on its own path because the
two mean opposite things to a caller.
- POST .../versions/{version}/revert overwrites the draft. Accepts the
literal `active` alongside a version number.
- PATCH /api/v2/workflows/{id}/deployment toggles unauthenticated public
execution.
`workflows.public_api.update` widens from session-only to session plus
personal API key: it is an admin-role change the same accountable human
may make from a script. Workspace keys stay denied. Its EE refusal now
carries PUBLIC_SHARING_NOT_ALLOWED instead of a bare forbidden.
Workflow MCP servers:
- /api/v2/workflow-mcp-servers list, create, update, delete, plus
publish and unpublish of a workflow as a tool. Named apart from
/api/v2/mcp-servers, which registers the external servers Sim calls.
- The six mcp_servers.workflow_deployments operations widen from
['delegated'] to admit sessions and personal API keys; roles and the
workspace-key denial are unchanged.
- The server list gains keyset pagination, matching its external
sibling, since nothing caps how many a workspace publishes.
- Server, tool, and workflow reads move out of the use case into
lib/mcp/queries.
Route ratchet 1150 -> 1160; OpenAPI operations 161 -> 171.
* feat(api): extract chat deployments and publish the v2 surface
Chat deployment was a shipped module with no public API and two
authorization systems: `lib/workflows/application/chat-deployments.ts`
had deploy/undeploy extracted, but only Copilot used them — the REST
routes reimplemented workflow authorization inline, and `PATCH
/api/chat/manage/[id]` additionally owned password encryption, the
auth-type field-clearing matrix, identifier uniqueness, the
redeploy-gating protocol with two 409s, a raw db.update, and a manual
recordAudit.
New `lib/chat-deployments` domain:
- `chat_deployments.list/read/update/delete`, keyed on the deployment
whose workspace is derived by joining its workflow. Creation stays
`workflows.chat.deploy`, which is keyed on the workflow.
- The PATCH extraction, including the field-clearing matrix and the
asynchronous-cutover invariant the route had hand-mirrored from
`performChatDeploy`.
- One `buildChatDeploymentUrl`, replacing three constructions that had
already drifted onto two different host helpers. There is no chat
subdomain, so nothing publishes a host.
- Repository reads moved out of the use cases into
`lib/chat-deployments/queries`.
Internal routes are now adapters over those use cases. `GET /api/chat`
is deliberately not migrated: it scopes by `chat.userId` while every
other chat operation authorizes by workspace admin, and reconciling the
two is a product decision. `PATCH` keeps its 400 for an identifier
collision through a typed `ChatIdentifierInUseError`; v2 reports the
409 the condition actually is.
v2 surface at `/api/v2/chat-deployments`: list, create, read, update,
delete. Workspace-scoped, keyset-paged, and a stored password is never
readable — reads carry `hasPassword` only, and the session-only reveal
endpoint deliberately has no v2 counterpart.
Also: an email- or SSO-gated chat with an empty allow-list is now
refused in the use case rather than only at the internal boundary, since
it is unenterable; and the doc comment on `processHostedKeyCost`
claiming a `usageLog` write is corrected — no such write exists.
Route ratchet 1160 -> 1165; OpenAPI operations 171 -> 176.
* fix(api): close three review findings, two of them caller-reachable
- Run output files are filtered to keys under the run's own execution
prefix. The recording they came from is not a trustworthy key source:
the start block copies every caller-supplied input field verbatim into
its output and `collectUserFilesById` accepts anything carrying the
`UserFile` shape, so a caller could name any storage key and have the
download and base64 paths — neither of which authorizes per file — serve
it back.
- `getBlock` reads own keys only. `BLOCK_REGISTRY` is an object literal,
so `constructor`, `toString` and friends returned inherited functions
that every consumer then treated as a block, turning a path segment into
a 500. `getToolMetadata` already guarded this way.
- A folder-scoped log page no longer unions in every job run in the
workspace. The guard read `filters.folderIds`, which the public surface
never sets — it carries the folder filter in `folderScope` — so the page
contradicted the contract's promise that job runs are dropped whenever a
filter they cannot answer is set.
Also: the log cursor stamps `includeJobRuns` only when it is on, so its
`.default(false)` no longer puts a constant in every fingerprint and
rejects cursors minted before it existed; and the `folderName` subquery is
scoped to the workspace and to workflow folders instead of scanning the
whole `folder` table.
* fix(api): close two more review findings, one an authorization bypass
- `workflows.operations.apply` no longer admits a workspace API key. The
use case authorizes against three per-user policies — the EE permission
config, block visibility, and credential reachability — and all three
take a human subject. An actorless key has none, and both substitutes
fail open: attributing to the workspace billing owner evaluates the
batch as the least-restricted account in the workspace, and passing no
user makes `getUserPermissionConfig` return `null`, which every caller
reads as unrestricted. Either way a workspace constrained by an
allowlist was edited as though it were not. Personal keys keep the
capability, so headless editing is unaffected for a credential that
names a human.
- `GET /workflows/{id}/state` reads its variables through
`parseWorkflowVariables`, and the stored variable response schema drops
the two assertions the column cannot honour. The column has carried a
JSON string and a legacy array as well as the current record, the
realtime `variable.add` op types `type` as `z.any()`, and the parser
writes `name` through verbatim — so the input bounds on the read turned
a stored workflow into a 500 on the endpoint that opens it. The write
schema keeps them, which is where they can still be honoured.
- `GET /workflows?scope=archived` projects folder paths tolerantly.
Archiving a folder cascades onto the workflows inside it but leaves
their `folderId` dangling — which is why restore has to null it — so the
strict projector threw a bare `Error` and took the whole page down with
no cursor able to step past the row.
* fix(files): bind Start-block file keys to the executing workspace
The Start block derived a file's storage key by parsing the caller's own
`url`, which `isInternalFileUrl` matches on any host and
`extractStorageKey` returns verbatim — so a request body could name any
tenant's bytes. The key is now accepted only when its own layout names
the workspace the execution runs in, and every file is dropped when the
execution carries no workspace.
Also bounds `includeFileBase64` with an aggregate response ceiling and a
worker pool instead of an unbounded `Promise.all`, scopes the bulk
download's authorization resource to the workspace when folder paths are
requested, makes the folder-restore selector mutually exclusive at the
type level, and names the bound in the `maxBytes` validation message.
* fix(api): close v2 log review findings
Cursor scope: `scope` on the workflow and table lists carries
`.default('active')`, so it entered every fingerprint as a constant and
refused every cursor minted before the param existed — with the
"cursor does not match the requested filters" 400, which is actively
misleading for a caller that changed nothing. Both now stamp the
default as absent, so only a caller who asked for `archived` gets a new
sequence.
Dashboard stats: `maxWorkflows` capped the response, not the
allocation. Segment series are now densified after the cut instead of
before, so returning 200 series no longer materializes one
`segmentCount`-length array per workflow in the window. The aggregate
still sums every workflow, now from the sparse per-workflow maps.
Cost keyset: `cost_total` is an unconstrained `numeric`, so its anchor
travelled through `Number()` and was compared back at full precision —
rows differing beyond float64 collapsed onto one anchor. Adds
`decimalKey`, which carries the digit string and binds it `::numeric`.
Run detail: `cost_total` is a backfilled projection, so a run predating
the backfill reported `cost: null` even with a real ledger, making
`items` unreachable for exactly the runs the ledger explains. Falls
back to the ledger total.
Also caps the log folder-path index reads at MAX_FOLDERS_PER_WORKSPACE
like every other reader, publishing the folder-tree 413 on the four log
operations; reverts a dead `status` widening in `v2CommaListSchema`;
drops an unread `executionData` select; corrects the segment-count and
searchLogs prose; and replaces the sort-cursor SQL-text assertions with
a two-page walk over a fixture with a null block.
* fix(api): close knowledge v2 review findings
- widen knowledge.list_archived to the delete/restore policy so a workspace
API key can discover what it may restore
- escape LIKE wildcards on the now-public chunk search
- derive tag slot capacity from TAG_SLOT_CONFIG per field type
- type updateKnowledgeBase's chunkingConfig as ChunkingConfig and project
every declared field explicitly
- attribute a restore to the calling surface instead of a literal 'api'
- gate 'knowledge chunks batch-update' behind --yes, since it can delete
- present the tag-cleanup action from the parsed request rather than
faulting on the domain result after the delete committed
- unbind asserted-scope workspaceId from the nested knowledge cursors,
matching the table-row lists
- add executed-SQL coverage for the chunk keyset
* fix(catalog): close the catalog and registry-boundary review findings
The module-graph ratchet treated an entry with no baseline row as
informational, so the six catalog routes and the projection barrel were
unratcheted while the summary still read "within their module-count
baseline". An unbaselined entry now fails --check, the summary counts only
what was actually compared, and the baseline is re-recorded.
The Copilot block-metadata tool — the reason the shared projection exists,
6,756 modules down to 1,321 — was in no guarded subtree. It is now an entry
source and a catalog boundary root.
Catalog behaviour:
- hostedApiKey is gated on the deployment, so a self-hosted install reports
none instead of promising 127 tools' keys it will never supply
- block detail resolves an unversioned base type to its newest version and
projects through the viewer's visibility, so it can no longer 404 a block
the list contains or name it differently
- offset-cursor ordering compares code units rather than the process locale
- projections copy every array they publish instead of handing out the
registries' own
- an options function returning a thenable throws rather than silently
widening the providers-store substitution across the event loop
- a throwing block projection costs the Copilot tool one block, not all of them
- the trigger-kind log returns to debug: chat/manual/api are entry-point
kinds, not authoring defects
Also sweeps the custom-block detail branch against its response schema,
guards each projection module rather than the dead barrel over them, and
drops a provably dead branch in processHostedKeyCost.
* fix(workflows): close v2 workflow-authoring review findings
- Read a blockless draft back as an empty graph. `PUT /state` of
`{ blocks: {}, edges: [] }` — the contract's own published example —
deletes every block row, and the loader answers `null` for a blockless
workflow, so the following `GET /state` answered 404 while the list
endpoint still showed the workflow. Existence is the workflow row's to
decide; the null is now projected as an empty graph.
- Rewrite the `readWorkflowGraph` authorization test so it can fail. It
called `authorize?.()` and asserted only a negative, so deleting
`authorize` or replacing it with a no-op both passed — the invariant the
head-safe `HEAD` path depends on.
- Route `setWorkflowBlockEnabled` through `replaceWorkflowNormalizedState`,
the same door the other two graph writes use, instead of writing the
normalized tables itself without state preparation or custom-tool
extraction.
- Count applied operations directly. Enablement refusals landed in the same
skipped-item array and were subtracted from the operation count, which
`Math.max(applied, 0)` then masked when it went negative.
- Give a `disabled_ancestor` refusal its own member of the published skip
enum instead of reporting it as `block_locked`.
- Refuse an `atomic` batch whose credential or hosted API key would be
stripped, and carry the dropped inputs in the 409 details.
- Publish the whole lint report — `sources`, `sinks`, `orphanBlocks`,
`emptyOutgoingPorts`, `invalidBranchPorts`, `invalidConnectionTargets`,
`fieldIssues`, and the `kind` discriminator on unresolved references —
rather than only free-text reference prose.
- Stop reporting unresolved lint references as `inputValidationErrors`.
`collectUnresolvedReferences` is read-only, so those values stay
persisted; they were double-reported, and falsely as dropped inputs.
- Replace two unfalsifiable negative-principal tests, which used a
principal kind `Exclude`d from `PrincipalKind`, with a reachable one.
- Nits: drop a stranded TSDoc block; assert the membership predicate in the
selector-validator admin test; make the HEAD test assert a representation;
assert the sanitized graph is what `replaceWorkflowState` writes; add a
route test rejecting `baseGraph` in a v2 body; carry
`principalAuditSource` on restore/duplicate/moveBulk audit; unify the two
`base64MaxBytes` ceilings on `MAX_INLINE_MATERIALIZATION_BYTES`.
* fix(api): close seven v2 review findings, one an authorization bypass
Raise mcp_servers.workflow_deployments.update_server to admin: its body
carries isPublic, and a public server executes with no Sim credential, so a
write member could remove authentication from every workflow it publishes.
create_server already grants the same visibility at admin.
Pin the widened operations in registry tests — the six workflow-MCP ones,
the four workflow widenings, and files.extract_archive.
Reject secret fields on a credential that has no rotatable secret instead of
dropping them behind a 200, classify a non-transient provider 4xx as caller
error rather than a retryable outage, and reconcile a provider outage to 503
with Retry-After on all three surfaces.
Give /v2/meta a declarative principal policy through a new defineOperation
factory, carry the key expiry on the auth context instead of reading the
api_key table from the application layer, and make the impossible principal
branch an invariant error rather than a codeless 403.
Enforce the rollout-gate exemption at definition time, against the one
contract path it is reserved for, and remove the gate parameter from the
exported admission helper so the builder is its only door.
* fix(tables): bound the run-state sidecar, and close six v2 review findings
Enforces the 2 MiB run-state ceiling INSIDE the sidecar drain rather than
over its materialized result, refuses the unbounded query form paired with
it, and normalizes the two stored blobs the v2 surface publishes from bare
`as` casts.
- The run-state budget now travels into `loadExecutionsByRow`, which drains
row ids in bounded chunks and refuses before fetching the next one. The
post-hoc `requireBoundedRunState` walk is gone: it measured a spike that
had already happened, and re-serialized every entry to do it.
- Both row reads that accept `includeRunState` cap the page at
`V2_MAX_RUN_STATE_ROW_LIMIT`, and `POST /tables/{id}/query` additionally
refuses the flag paired with `limit: 0`.
- `runState.status` and the enrichment cascade blob are projected onto the
published shape before presentation; both were caller-reachable 500s on a
well-formed read.
- `sim tables bulk-delete` now gates behind `--yes`, and the CLI sweep that
should have caught it covers destructive non-DELETE forms.
- `POST /tables/{id}/restore` is idempotent (200, no audit) like its
knowledge sibling, and bulk folder selection deduplicates after resolution.
- The batch-update backstop keeps the looser Copilot ceiling and says so in
TSDoc: it is a backstop no surface reaches, because the contracts stop a
v2 caller at 1000 and the Copilot tool stops itself at 5000. Each caller
sees the bound that actually applies to it; neither surface's cap moved.
* fix(chat-deployments): close v2 chat review findings
Fixes the chat-deployments slice of the v2 review, several of which are
regressions the application-operation extraction introduced.
- Stop a `500` on schemaless JSONB: the response now declares a stored
shape without bounds and `toV2ChatDeployment` projects
`customizations`, `outputConfigs`, and `allowedEmails` onto it. The
request schemas keep `.strict()` and their bounds.
- Restore the specific validation message on `POST /api/chat` and
`PATCH /api/chat/manage/[id]`, and the deleted test that pinned it.
- Restore `chat_deployments.read` to workspace `admin`; the detail read
serves the visitor gate.
- Narrow the list projection so `chat_deployments.list` can stay a
`read` operation reachable by a workspace API key: `allowedEmails`,
`hasPassword`, and `customizations` are gone from the list entry and
available only from the admin-gated detail read. Serialized field by
field so a field added to the detail shape cannot reach the list by
default.
- Classify create-path failures: `performChatDeploy` carries an
`errorCode`, so an in-flight deployment is a `409` and an invariant
failure a `500` instead of every refusal being a `400`.
- Delete the callerless `GET /api/chat`, which served the encrypted
password column with no response contract.
- Propagate undeploy infrastructure failures instead of concealing them
as `404`, and return `ChatDeploymentView` from both delete paths.
- Name `CHAT_AUTH_MODE_NOT_PERMITTED` on the create path.
- Guard `getBaseUrl` inside `buildChatDeploymentUrl`, which otherwise
throws on a self-host with no `NEXT_PUBLIC_APP_URL`.
- Correct the published allow-list claim: a replacement `allowedEmails`
is applied after the auth-type clear, so it does survive.
- Assert `workspaceId` on the v2 detail routes and reconcile the
concealment TSDoc with what the error policy actually renders.
- Move `resolveActiveWorkspaceApplicationContext` to the workspaces
domain so chat-deployments no longer imports workflow application code.
* test(credentials): pin the reconciled provider-outage status
The internal route alone answered 502 where the v2 surface, the shared
status helper and `PROVIDER_OUTAGE_CODES`' own TSDoc all say 503. The
test pinned the divergence; it now pins the reconciliation, including the
`Retry-After` a 503 carries. Corrects a stale comment that still named
502 as the value callers see.
* fix(executor): restore cloud-storage Start files, dropped by the key rule
The ownership check accepted a key only when it could be parsed out of an
internal `/api/files/serve/...` URL. But the server-side uploader for run
inputs returns a *presigned cloud* URL whenever object storage is
configured, whose path is the bucket key — so every chat-deployment
attachment, API `files[]` payload and generic-webhook file field resolved
no key, and because normalization is all-or-nothing the entire `files`
input was dropped with no error. It passed locally and under vitest only
because the uploader falls back to an internal URL when no object storage
is configured, which is exactly why no test caught it.
The test is ownership, not provenance: a key is accepted when its own
layout names the executing workspace, whether it arrives directly or is
parsed out of the URL. Neither field has to be trusted, since both are
caller-authored and both are held to the same check. A payload whose key
and URL disagree is refused rather than resolved in the caller's favour —
a genuine uploader writes the two consistently, so only a forged pairing
is turned away.
`context` is now derived from the accepted key rather than read from the
payload or the URL's `?context=`, so an owned key can no longer be
labelled with a bucket its bytes do not live in — the hardening the
previous comment claimed but did not perform.
* fix(api): close four defects the fix pass introduced
- `resolveLatest` built a `RegExp` from the caller's block id and read the
registry with a bare lookup, so the catalog detail route — moved onto it
by the version-alias fix — routed around the `ownBlock` guard added for
exactly this. `GET /api/v2/blocks/%5B` was a `SyntaxError` 500 and
`.../constructor` an inherited function. Matched by string comparison
now, the way `tools/tool-ids.ts` resolves the same convention, and read
through `ownBlock`.
- The run-state byte budget was applied inside `queryRows` rather than at
the callers that publish it, so the first-party table grid — which reads
run state at five times the row limit and publishes no ceiling — turned
a large page into a hard failure, with an error naming a parameter it
does not expose. The budget is now an explicit option the public reads
pass and internal callers omit.
- Three graph-write CLI commands shipped ungated because the sweep meant
to catch them matched only the names already enumerated, so it could
never fail. It now forces every non-`GET` operation into a destructive
or non-destructive list, and the three carry confirmations.
- Unbinding `workspaceId` from the knowledge-documents cursor was right on
the merits and wrong in effect: the value is constant per sequence, so
removing it changed the fingerprint and refused every cursor already in
flight. Restored there; the chunks list is new in the same change and
keeps the cleaner reading.
* fix(api): resolve a detail read to a version the viewer can see
`getLatestBlockForViewer` took the newest version and then hid it, which
inverted the contradiction it was written to close: `slack_v2` and
`table_v2` are preview-gated while their v1 deliberately stays in the
toolbar, so an unrevealed viewer got a `404` on a detail read for a type
`GET /api/v2/blocks` was listing in the same breath. It now walks versions
newest-first and answers with the first one visible to that viewer.
Also:
- The chat password guard ran after `performFullDeploy`, so a request that
could never succeed burned a real workflow deployment version and then
answered 400. Its two sibling gate guards already refuse ahead of the
deploy; this one now does too.
- The Copilot sub-block serializer published the registry's own `options`
and `dependsOn` arrays by reference. Pre-existing, but the catalog
projection this parallels copies every array it publishes precisely
because they are process-global and shared by every request.
* fix(api): restore the locked read-modify-write and the password validator
Two findings verified as real regressions against staging, out of ten
checked — the rest were pre-existing, latent, or false.
`setWorkflowBlockEnabled` read the graph outside the row lock and wrote it
back inside a later transaction. The editor's own save takes that same
lock, so an autosave committing in the window was silently discarded: this
operation writes a whole graph, not a delta. The persistence primitive now
accepts a reader that runs after the lock is taken, and the toggle
re-reads and re-decides there. Its lock predicate is also scoped to the
workspace and to a live row again, so a workflow archived mid-flight is
refused rather than written.
The v2 chat-deployment contracts inlined their own password rule twice
instead of using `chatDeploymentPasswordSchema`, losing the refusal of a
whitespace-only password — which the internal contract rejects precisely
because it strands the deployment behind a password the visitor form will
not submit. Both sites use the canonical validator now.
* fix(api): one folder projection, one dynamic-provider list, honest 413s
- `toV2Folder` existed twice, and the second copy had been written without
the name/path invariant — so a row the list read refuses loudly would
have been served with a mismatched pair by the restore read. One
definition, guard included.
- The catalog projection restated `DYNAMIC_MODEL_PROVIDERS` and had
drifted by one member. Derived from the canonical list instead.
- The tables reads documented a `413` for run state that they cannot emit
— the budget became opt-in, and the row limit is the bound now — so the
claim is removed rather than declared. The workflow run read has the
opposite problem: it genuinely emits one, on a single file *or* the
run's inlined total, and declared neither. Now declared, and the
sentence covers both.
- Reclassifies the operations staging added into the destructive sweep, so
the triage stays exhaustive.
* fix(v2): classify storage and uniqueness failures, drop permanent file delete
- remove the permanent file-delete endpoint; the platform offers no such
action in the UI, and its manager wrote outside a transaction with no
storage accounting
- extract a generated document's text from its compiled artifact rather than
its generation source, matching the download path; a `.pdf` source was a
500 and a `.docx` source returned generator JavaScript as clean content
- report a run file whose object retention has already swept as 404 rather
than 500, on both the inline base64 read and the download stream
- report a knowledge tag that loses at a unique index as 409, naming whether
the slot or the display name is taken
- gate `workflows versions revert` behind a CLI confirm; it overwrites the
draft graph and was classified non-destructive
* feat(v2): report lint from both graph writes and add dry-run previews
- `PUT /workflows/{id}/state` now returns the same `lint` report as
`POST /operations`; an agent authoring a graph from scratch needs the
findings at least as much as one editing incrementally
- extract the report into one shared builder so the two writes cannot drift,
and one shared presenter so the wire shape is identical
- skip the credential/tool reference pass when the caller has no human
subject, rather than resolving it against the workspace billing owner:
that would misreport what the workflow can reach and disclose another
person's grants. `lint.notes` says when it was skipped
- add `?dryRun=true` to both graph writes: validates and lints, persists
nothing, records no audit, notifies nobody. A query param, not a body
field, since the body of a PUT is the resource itself
- CLI: a dry run no longer demands `--yes`; requiring confirmation to preview
a change teaches callers to pass `--yes` reflexively
- CLI: name the graph commands for their verbs — `workflows state get`,
`workflows state replace`, `workflows operations apply` — instead of the
derived `state list` / `state update` / `operations create`
- document when to use `rollback` vs `versions/{version}/activate` on both
* chore(docs): sync generated docs manifest for the new CLI pages
* feat(v2): add the missing workflow-MCP reads and align bulk naming
- add `GET /workflow-mcp-servers/{serverId}` and
`GET /workflow-mcp-servers/{serverId}/tools`. The resource could be
PATCHed and DELETEd but never read, and its tools could be published and
unpublished but never listed — the server list reports tool names only, so
nothing published the `workflowId` that addresses a tool for deletion.
Both mirror `mcp-servers` beside them, and carry that family's
workspace-API-key denial rather than the wider `mcp_servers.read` policy
- rename `POST /tables/bulk-move` to `POST /tables/move`, so tables matches
the shipped `files` resource exactly (`move` + `bulk-delete`)
- name the CLI commands for their operations instead of the derived
`... create`: `tables move`, `workflows move`, `tables bulk-delete`, and
`tables rows update-each` for the per-row batch, which sits beside the
existing filter-based `tables rows batch-update`
`POST /tables/{id}/rows/batch-update` keeps its name: a distinct payload per
resource is precisely AIP-234 BatchUpdate, and `bulk-` would have collided
one word away from the filter form.
* fix(v2): correct documented statuses and a caller-reachable 500
- duplicating a workflow into a locked destination folder answered 500:
`FolderLockedError` is a plain Error carrying `status = 423`, which the v2
error policy does not classify. Converted to OrchestrationError('locked')
at the application boundary, matching the bulk-move path
- restore workflow promised a 413 for an oversized folder tree that its
response list never published; the cap is real, so the status now is too
- move workflows and apply variables documented 409/423 they cannot emit:
every per-item lock and conflict is reported in `failed`, not thrown
- bulk download and delete knowledge tag can both 409 and did not say so;
cleanup tag definitions cannot and did say so
- apply workflow operations denies workspace API keys but never documented it
- the dry-run responses are not byte-identical to a committed write:
`needsRedeployment` describes the pre-write state and persistence warnings
cannot appear. Reworded rather than overclaimed
- read file text and get file upload are head-safe, so the "HEAD skips the
effect" sentence did not apply to them
* fix(v2): guard tag field-type changes and publish the 415 every body route can return
- `PATCH /knowledge/{id}/tags/{tagId}` accepted a `fieldType` incompatible
with the slot the tag already occupies. Slots are enumerated per field
type, so a text tag could be relabelled `number` and every later read
would interpret its values as the wrong type. Create checked this; update
now runs the same two checks
- derive `415` from the contract the way `413` already is: the JSON builder
answers UNSUPPORTED_MEDIA_TYPE for any body under a content type it cannot
read, so all 100 body routes could return a status none of them published
- give version activation its own result component instead of publishing it
as `RollbackResult`; the shipped rollback keeps that name
- correct descriptions that promised behaviour the code does not have: a
`processingStatus` field never returned, a `gmail_send` resolution example
that short-circuits, bucket widths that overflow the window, a bulk tag
save that relocates rather than overwrites, and per-server tool names
actually gathered under a page-wide budget
- drop 409 from three knowledge and upload reads that cannot emit it
* docs(v2): correct the upload transfer contract and 16 other published claims
The upload transfer step was documented as Sim's own data plane on every
deployment: "success is 204" and "a failure is the v2 error envelope". That
holds only when Sim stores objects itself. With object storage configured the
URL is the provider's presigned URL, so S3 and GCS answer 200 and Azure 201,
and a failure is the provider's XML — a client written to the old text reads a
successful cloud upload as a failure. Also states that part ETags do not need
retaining: completion takes no body because Sim lists the parts from the
provider itself.
Other corrections, all to shipped descriptions rather than behaviour:
- DELETE table and bulk-delete files archive rather than erase, and neither
said so; bulk delete also cannot emit the 409 it declared
- complete knowledge upload published a 402 only the create leg can raise
- billing status conceals a foreign workspace id as 404, not the 403 its
TSDoc and description both claimed
- audit entries null a folder's resourceId and strip folder ids from metadata
at every level; neither redaction was documented
- details=full adds the workflow summary to workflow runs only, never to job
runs; GET /logs folderPaths covers a subtree like its two siblings; getLog
now carries the retention sentence
- list secrets returns description too, and the logs and resources documents
described only part of what they serve
* improvement(api): consolidate the v2 surface and close seven defects
Endpoint consolidation:
- Fold POST /logs/query into GET /logs; add sortBy/sortOrder, cap the
comma lists, and move the list onto the shared keyset codec
- Fold GET /knowledge/archived into GET /knowledge?scope=archived,
matching files, tables, and workflows
- Re-home chat deployments as a singleton under the workflow they
belong to; keep the workspace-scoped discovery list
- Move the tag-definition writes off the document path onto
/knowledge/{id}/tags, where they already acted
- Nest the table export and dispatch reads under their parent table
Defects:
- Publish isPublicApi on the deployment read; it was write-only, so a
workflow could be opened to unauthenticated execution unauditably
- Stop publishing raw storage keys and an unusable URL in log files
- Classify a chat-identifier unique violation as 409 rather than 500
- Fall back to the root path instead of throwing when a knowledge
base's folder is archived
- Cap bulk-download at the ceiling it actually enforces
- Normalize variables through one helper on both graph write paths
- Fix a folder-name log filter that matched workflow names
Naming and gaps:
- Rename /files/{id}/extract to /unarchive, /rows/find to /rows/search,
/rows/batch-update to /rows/bulk-update, /columns/run to /dispatches
- Type the last six generic [id] path segments
- Add table folder restore and id-addressed dispatch cancel
* chore(audits): record the v2 catalog routes in the boundary baseline
* fix(api): accept a null chat password and correct three published claims
- performChatDeploy validated `password: null` as a password, so the
replace-shaped chat PUT answered 400 for every mode that owns no
password — public (the default), email, and sso. The declared payload
type has always allowed null, and the stored value is cleared by
authType regardless, so null needs no validation of its own. The route
test could not catch it: it mocks the orchestration module and pinned
the exact null the real guard refused.
- Redirect the two docs slugs this branch retired that were genuinely
published: findTableRows and runTableColumns.
- The table folder restore described an idempotent no-op for an already
active folder; it answers 404. Say so, and say where the path comes
from, since the tables folder list cannot yet report archived folders.
- Name the customizations exception to the chat PUT's replace semantics.
- A cursor-binding case used status=error, which is a level and not a
status, so it failed contract validation and never reached the cursor
check. Use an accepted value and pin the reason, not just the status.
* chore(cli): classify the new v2 chat operation as non-destructive
* feat(cli): expose canonical resource URLs
* fix(api): close three caller-reachable failures found by the final probe
- GET /files/{fileId}/text called parseBuffer unguarded, and parseBuffer
signals every failure as a bare Error that no v2 policy classifies. A
zero-byte upload or a mislabelled archive was an unhandled 500. Empty
bytes now answer empty text — a zero-length file has no text — and
unparseable bytes answer 409, matching the rendered-artifact resolver.
- GET /workflows/{workflowId}/state asserted write-side bounds over
stored data. workflow_blocks.name and .type are bare text() and the
realtime rename op accepts z.string(), so a block renamed past 255
characters made the workflow unreadable, and unrepairable, over v2.
The read shape now takes the same input/stored split the variable
schema already had. Stored subflow conditions are coerced in the
loader beside the existing numeric guards.
- GET /knowledge stamped scope into the cursor fingerprint
unconditionally. scope defaults to active and is new on that list, so
every cursor the deployed build handed out would have been refused
with a message saying the caller changed a filter they never sent.
Its siblings already carry the guard and the comment.
Also: POST /workflow-mcp-servers answers 201 like every other v2 create;
GET /logs/stats reuses the log list's entry ceilings; the execute and
resume routes install the media-type-aware 415 they publish; and a
rationale citing an endpoint that never reached the wire is corrected.
* fix(tables): carry the dispatch terminal timestamps through the stale sweep
Staging's abandoned-dispatch recovery builds its own `DispatchRow`, and
this branch had added `completedAt`/`cancelledAt` to that shape for the
id-addressed dispatch read and cancel. The merge was textually clean and
left the new mapping short two fields.
* fix(workflows): deny workspace API keys on the graph replace
`PUT /workflows/{workflowId}/state` stores blocks and their tool wiring
wholesale, but the policies deciding which of those a member may add —
the EE permission config and block visibility — take a human subject.
A workspace API key has none, and both substitutes fail open: the
billing owner is a different, typically less-constrained person, and
passing no user makes the permission lookup return null, which every
caller reads as unrestricted.
That made the replace a second graph-write door storing what its sibling
`POST /workflows/{workflowId}/operations` refuses, which denies workspace
keys for exactly this reason. Both doors now agree. Personal keys keep
the capability, so headless authoring is unaffected for a credential
that names a human.
* chore(api): drop the enrichment catalog endpoint
GET /api/v2/enrichments listed the code-defined table enrichments. The
per-row enrichment run detail stays; only the catalog read goes.
Removes the route, contract, response and query schemas, the semantic
operation, the use case, the projection module, its registry-boundary
entry, and the CLI command. The "not found" and "blank search" cases it
covered are repointed at the connector-type sibling so the shared
behaviour stays tested rather than deleted with it.
* improvement(api): make the workflow operations endpoint self-describing
Two things stood between this endpoint and a caller who has only the
published spec.
The accepted `params` keys existed only in the edit engine's source. The
spec said "the accepted keys depend on the target block type", so a
caller reading it could create a nameless empty block and nothing more —
while the Copilot tool catalog, over the same engine, has always spelled
out the envelope. That guidance now lives in the contract, shared by the
add, edit, and insert_into_subflow parameter schemas so the two surfaces
cannot describe one engine differently: `inputs` keyed by sub-block id,
`retry`/`triggerMode`/`advancedMode` beside it rather than inside it,
`connections` keyed by source handle, and `removeEdges` for dropping one
edge without restating the rest.
A `block_id` that is not already a UUID is replaced with a minted one,
and the mapping was computed and then dropped. A caller could not
reference the block it had just created except by re-reading the graph
and matching on name. The engine now returns it and the response
publishes it as `mintedBlockIds`, with the in-batch versus cross-request
rule stated in the operation description.
* fix(api): close the pre-merge scan's blocking findings
Docs and public wire, all of it permanent surface once released.
- Two published tag groups, Catalog and Meta, had no sidebar entry in any
locale, so six operations shipped unbrowsable. Added to all six, and a
test now fails when a published tag has no entry.
- deleteWorkflowChatDeployment pointed callers at DELETE on /deployment;
the undeploy verb is on /deploy.
- PUT /state still promised workspace API keys a degraded lint pass after
the operation began rejecting them outright. It also lived in a
single-quoted string, so the shared clause would not have interpolated.
- POST /tables/move took targetFolderPath as nullable-but-required, which
rendered the CLI flag as a required `<json|@file>`: `--to /Archive`
failed to parse and omitting it failed outright, while the docs said
"omit for root". Now optional and a plain string, matching
POST /files/move; the route supplies the null the use case wants.
- Table dispatch status and row run state published `cancelled` beside
imports, exports, and job state publishing `canceled`, and the note
explaining the split was wrong about its own sibling. Both new schemas
now publish `canceled`; the stored column is unchanged and mapped at
the presenter. The shipped `cancelled` count field is left alone.
- applyWorkflowVariables can answer 423 and both workflow-MCP deletes can
answer 409; none declared it. Hand-assembled error lists replaced with
the shared sets.
- /files/{fileId}/unarchive became /unzip. `extract` reads as "extract
text" and `unarchive` reads as the inverse of restore on a resource
where archived means soft-deleted; unzip collides with neither and is
what the implementation calls itself.
* improvement(cli,docs): finish the naming and clear the enrichment leftovers
- Four single-record GETs derived to `list` while returning one thing:
meta, a workflow's chat deployment, log stats, and file text. Renamed to
`meta status`, `workflows chat status`, `logs stats`, `files read`,
matching the `workflows deployment status` correction already in this
branch. None of the old spellings shipped.
- Dropped five `renamedFrom` aliases pointing at spellings that never
existed, each of which built a hidden command and a permanent
deprecation warning for argv nobody could have typed. `tables rows find`
keeps its alias — that one really shipped.
- Removed the enrichment catalog from three prose sites left behind when
the endpoint went: the resources spec description, its Catalog tag, and
the contract and pagination-test comments.
- Documented the six new command groups in the CLI index table. That page
is a guide page, so the docs staleness check cannot flag it.
- Published the `customizations` exception to the chat replace semantics.
It was in the route TSDoc and invisible to every caller reading the
spec, which is where the claim "Replace, not merge" is made.
* improvement(cli): use batch- for the tables bulk delete, matching its siblings
The CLI renames a bulk form only when it would collide with its singular
sibling, and uses AWS's `batch-` prefix when it does — `files
batch-delete`, `tables rows batch-delete`, `knowledge chunks
batch-update`. `tables delete` exists, so `tables bulk-delete` was that
same rename reaching for the other word, and the only `bulk-` command on
the surface. No `bulk-` CLI command has ever shipped, so this costs
nothing now and would be permanent later.
`files bulk-download` keeps its name: there is no `files download` to
collide with, and it is one archive rather than N operations. Its config
block now says why it exists at all, since the command is never built —
the builder skips non-JSON response modes, but the contract sweeps still
read the entry and require the folder-path field to be marked.
* fix(workflows): allow operations on blockless drafts
* feat(workflows): add manual and run-from-block execution
* fix(cli): update workflow run description test
* fix(tests): align fixtures with current contracts
* fix(api): derive chat activity from workflow deployment
---------
Co-authored-by: Theodore Li <theo@sim.ai>
|
||
|
|
8104c33bba |
Fix knowledge connector sync follow-up (#6927)
* Fix knowledge connector sync follow-up * Fix connector sync pause race * fix(knowledge): surface connector sync dispatch failures * fix(knowledge): make connector sync recovery durable * fix(knowledge): deduplicate connector sync dispatches * fix(knowledge): preserve pending connector syncs * fix(knowledge): lock connector sync snapshot |
||
|
|
8937bb3550 |
fix(kb): let the server say a connector sync is queued (#6968)
* fix(kb): let the server say a connector sync is queued The connector chip inferred "a sync is coming" from `createdAt` inside a 2-minute window, because nothing on the row distinguished a queued sync from an idle connector until a worker took the lock. The guess was wrong under queue backlog and under client clock skew, and it forced a pile of client state to stand in for it. Adds `pending`, written as the sync is handed to the queue and cleared when a worker takes the lock or the hand-off is found to have been lost. It is a phase of the same lock `syncing` holds, so it opens the lease and takes an ownership token the same way — the lease is what the scheduler ages a stranded queue entry against (`updatedAt` cannot serve: a pending connector is still editable, so any unrelated write would renew the recovery it should trigger), and the token is what proves a late release belongs to this dispatch. Deletes the 2-minute window, the in-flight id sets, the 5-minute cooldown timers and the forced re-render they needed. The cooldown lived in a ref inside a modal, so it evaporated whenever the modal closed; the disable now comes from durable server state and is shared across tabs. Also fixes, all found while tracing the lifecycle: - An on-demand sync on a paused or disabled connector silently resumed it for good. Nothing could put the pause back: success writes `active`, a lost queue entry writes `error`, and the due-sweep keeps syncing that. Refused. - A failed hand-off no longer advances the connector's auto-disable breaker. A queue outage would otherwise increment every connector in the fleet until they all disabled themselves for a fault that was never theirs. - Manual sync on an established connector gave no feedback at all: the poll only ran while the predicate matched, which it never did. - Four over-broad invalidations that refetched every cached chunk page and chunk search in a base when one connector document was excluded. - The dead-process reporter re-sent a PATCH per stale document on every poll. * fix(kb): refuse to start a queued run on a paused connector The queue outlives the decision to sync. Pausing a connector after its run was queued cleared the queue entry's token but left the task itself alive, and the lock CAS accepted any row that was not already `syncing` — so the worker took the paused row and wrote its own terminal `active` over the pause. Moves the rule to the two points that can enforce it: an explicit `LOCKABLE_CONNECTOR_STATUSES` allowlist on the lock acquisition, and the same allowlist on `markSyncPending`, which closes the mirror race where a dispatch already in flight rewrites a just-paused row back to `pending`. Queueing and starting now agree on one rule, and a skipped hand-off is reported as its own outcome rather than a concurrency conflict. Also patches the connector detail cache alongside the list on an optimistic status write, so an already-expanded card starts its own sync poll instead of showing stale history behind the list's spinner. * fix(kb): make a queued sync prove it is the run that was queued `markSyncPending` minted an ownership token but only `releaseFailedDispatch` checked it, so the worker could consume a queue entry that was not its own. A task delayed past its lease is reclaimed and replaced; the status check alone let that stale task take the replacement's entry and run superseded options — a plain sync where the user had just asked for a full resync — while the replacement was turned away as `sync_in_progress`. Carries the token in the task payload and matches it at lock acquisition, the same discipline `holdsSyncLockToken` already applies to the `syncing` phase, extended to the phase before it. A superseded run is now reported as such rather than as a concurrency conflict. The payload field is optional for the rollout window only: tasks already in the queue carry no token, and stranding them would be worse than letting them fall back to the status check for one deploy. * fix(kb): report a paused connector as paused, not superseded Pausing a queued connector releases its token, so testing ownership before status reported every pause-while-queued — the common case — as a superseded dispatch. The mismatch is the symptom there; the status is the reason. * fix(kb): stop a status update landing on a run that already started The update's guards ran against a row read moments earlier and the write carried no compare-and-set, so a worker taking the lock in between meant the write landed on a `syncing` row — overwriting the run's status and, because leaving `pending` also clears the lock columns, wiping the token its heartbeat and terminal write match on. That stranded a sync that had already begun. The write is now conditional on the status the request was authorized against, and a lost race is reported as a conflict rather than "not found". Also restores the in-flight guard on the pause control. The optimistic status flip relabels it Pause -> Resume immediately, so a second click could send `active` before the first pause settled and resume a connector the user meant to pause. Read from the mutation's own pending state rather than the local id set this PR removed — React Query already knows which row is in flight. |
||
|
|
42f6287911 |
feat(byok): add organization-wide key inheritance (#6834)
* feat(byok): add organization key management * feat(byok): inherit organization keys at runtime * feat(byok): add organization scope to BYOK settings * fix(byok): refresh org key state after mutations * fix(byok): hide stale inherited status badges * chore(db): drop colliding byok migration ahead of staging merge Staging independently claimed 0293. Remove ours so the merge is clean; it is regenerated at the next free index right after. * chore(db): regenerate byok migration at 0296 Staging claimed 0293-0295 during the merge; the regenerated SQL is byte-identical to the dropped 0293. * docs(byok): document organization scope, precedence, and the full provider list The BYOK section described workspace-scoped keys only. Add the organization scope, its Enterprise requirement, the per-provider precedence rule, what an entitlement lapse does, and the Pi sandbox exposure. Refresh the provider table from the settings page, which had drifted from 14 to 34 entries. * feat(byok): open organization keys to every organization plan Organization BYOK was gated on Enterprise, but an organization is the only thing that can hold the keys, so every plan that can own an organization should qualify — Pro for Teams, Max for Teams, and Enterprise. Add checkOrgPlan/resolveOrganizationPlan beside the Enterprise pair rather than widening checkEnterprisePlan, so the Enterprise-only gates (Access Control, whitelabeling) are untouched, and restore resolveOrganizationEnterprisePlan to module-private now that BYOK no longer needs it. * perf(byok): cache the organization entitlement, not the key material getBYOKKey runs once per agent block and once per hosted-capable tool call, so a loop over N items resolved N times — and each organization-inheriting resolution paid three sequential billing queries on top of the two key reads. Split the two reads by staleness tolerance. Key rows stay fresh, because revocation must be immediate. The entitlement is a billing gate that tolerates bounded staleness in the harmless direction (a lapsed organization keeps using its own key for <=60s), so cache it per organization with an in-flight share so concurrent blocks issue one query set. The management surfaces keep reading it fresh, so an organization that just upgraded is never told otherwise. Also run the block check and subscription read in parallel inside resolveOrganizationPlan, and carry the resolved scope on BYOKKeyResult so a log line can say whether a run used the workspace's key or an inherited one. * feat(byok): let workspaces store the Z.ai and Cohere keys the runtime reads Both ids were already in the BYOK contract enum and both are resolved at execution time — getApiKeyWithBYOK reaches 'zai' (GLM models are in the hosted catalog, so the BYOK branch runs), and 'cohere' backs both the Embeddings block and Knowledge Base reranking — but neither appeared in the settings list, so there was no way to store the key either path looks for. Cohere had no icon; add one from the official multi-color mark so it stays legible on a light and a dark page. Cohere's embed-v4.0 is kbEligible:false, so the description says 'Embeddings and Knowledge Base reranking' rather than claiming KB embeddings. * improvement(byok): shorten the workspace scope chip to 'Workspace' It sits beside 'Organization', so the scope reads from the pair; 'This' only added width. * fix(byok): do not cache a billing outage as an unentitled organization resolveOrganizationPlan maps a failed billing read to false, which is indistinguishable from a real plan lapse. The entitlement cache stored that, so one transient outage held the gate shut for the full TTL and every inheriting run silently fell back to a metered hosted key — and the cache's rejection path, which exists to prevent exactly this, was unreachable. Give the resolver the onError option its neighbours already have and let the cached read ask for 'throw', so a failure stays out of the cache and the next resolution retries. Behavior for the call that saw the error is unchanged: getBYOKKey still fails closed. Reported by Cursor Bugbot. * fix(byok): propagate the subscription read's failure too The previous commit threaded onError through resolveOrganizationPlan's own catch, but getOrganizationSubscriptionUsable soft-fails to null on its own, so a failed subscription read still arrived as an ordinary 'no usable subscription' and returned a successful false — which the entitlement cache then stored for the full TTL. Thread the option into that call as well. Test it at the billing layer rather than the cache layer: the entitlement test mocks resolveOrganizationPlan wholesale, so it could never have caught this. Verified the new test fails against the previous commit. Reported by Cursor Bugbot. * refactor(byok): cache the entitlement with LRUCache, like copilot entitlements The hand-rolled version reinvented three things the codebase already has a canonical answer for. lru-cache is a declared dependency of apps/sim and lib/copilot/entitlements.ts already caches an entitlement with it — by storing the in-flight Promise, which is what makes concurrent callers collapse onto one resolution with no in-flight bookkeeping at all. TTL and the size bound come from the library. That removes the second Map, the manual eviction (and its interaction with an in-flight entry), and the dead value-while-refreshing state: 23 executable lines. The one thing the library does not cover is dropping a rejected promise so a billing outage is not cached for the TTL, which is kept and pinned by a test that fails without it. TTL expiry is no longer re-tested — that is the library's behavior, not ours, and lru-cache reads its clock at module load so faking timers never moved it. * refactor(byok): coalesce the entitlement read with the shared singleflight lib/concurrency/singleflight.ts is the codebase's coalescing primitive and oauth/credential-service.ts already pairs it with a read-through cache. Adopting that shape fixes a case caching the promise directly did not: a *hung* billing read wedged every caller for the full 60s TTL, where coalesceLocally evicts and rejects at its settle deadline. It also removes the hand-rolled rejection eviction — the cache is written only on the success path, so an outage leaves no entry by construction. The cache now holds booleans, which introduces the one trap worth a test: a truthiness check would read a cached false as a miss and re-query billing on every resolution for lapsed organizations. Pinned. * fix(byok): keep an abandoned entitlement producer from writing the cache coalesceLocally does not cancel a producer it timed out — its docstring says so explicitly — so writing the cache from inside the producer let a late billing result overwrite a fresher answer a retry had already cached, and hold it for a full TTL. Move the write onto the value the caller actually received. A caller that timed out throws before reaching it, so an abandoned producer now resolves into nothing. The test reproduces the overwrite and fails against the previous shape. Reported by Cursor Bugbot. --------- Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local> Co-authored-by: Vikhyath Mondreti <vikhyath@simstudio.ai> |
||
|
|
a99f61bee9 |
feat(api): add v2 resource management endpoints (#6900)
* feat(api): add v2 resource management endpoints * fix(cli): gate destructive v2 commands * fix(test): update v2 request-slice count * feat(cli): add shared workspace profiles |
||
|
|
4f9d5f33b0 |
improvement(search): search every folder, and document real API error bodies (#6861)
* improvement(search): search every folder, and document real API error bodies Search on Files, Tables, and Knowledge was ANDed with the open folder, so a query only ever matched that folder's direct children — and the query was not cleared when you entered a folder, filtering the folder you just opened down to the same matches. A non-empty query now searches the whole workspace, a Location column names each result's folder, and opening a folder ends the search. Also gives GET /api/v2/files a `recursive` flag, and replaces the single shared OpenAPI error example — which showed `BAD_REQUEST` under every status tab — with one real body per status. * fix(search): discard the search term on clear instead of masking it `useSearchFilterValue` returned the debounced term whenever the input was non-empty, so clearing only hid the settled needle. The mask lifted on the next keystroke while the debounce still held the pre-clear term — opening a folder and typing within the window searched the whole workspace for the query the user had just abandoned. A clear now resets the settled term rather than hiding it, adjusted during render so the reset is visible to the render that follows the clear. The initial state is seeded from the first value so a deep-linked `?search=` still filters on the first render. |
||
|
|
6006870f02 |
feat(credentials): add v2 credential lifecycle APIs (#6664)
* feat(credentials): add v2 OAuth connection APIs * fix(credentials): preserve active OAuth connection links * fix(credentials): bind OAuth links to connection intent * feat(credentials): complete v2 credential lifecycle * fix(credentials): make disconnect idempotent * fix(credentials): stabilize oauth draft retries * fix(credentials): bind oauth callbacks to drafts * fix(credentials): fail closed on oauth completion * fix(credentials): bind shopify completion to oauth state * fix(credentials): align custom oauth reconnects * fix(credentials): centralize application authorization * fix(credentials): keep OAuth draft intent immutable * fix(credentials): allow renamed reconnect targets * fix(credentials): close OAuth draft edge cases * fix(credentials): fail closed without breaking auth * fix(credentials): preserve migrated route behavior * feat(credentials): add provider search * fix(credentials): prevent stale secrets and drafts |
||
|
|
cf78946529 |
fix(v2): close seven correctness and honesty gaps found sweeping the API (#6702)
* fix(v2): close seven correctness and honesty gaps found sweeping the API A ten-slice sweep of the live v2 surface turned up no regression from the recent cancellation work, but did surface a set of pre-existing defects where an endpoint either lost data, hid a failure, or reported something that was not true. Each is fixed at the layer that owns the behavior. Terminal execution logs. The two force-fail boundaries wrote `status: 'failed'` without `ended_at` or `total_duration_ms`, so a force-failed run dropped out of every duration-filtered log query — the same defect class already closed for cancellation, still open on its sibling. The cancellation payload factory is generalized to take the status; the cancellation call sites are untouched and still emit a byte-identical row. Custom tools. One malformed row failed the whole page, and because the list is keyset-paginated that row made every page containing it permanently unreachable. The projection now validates against the same contract schema the route builder applies, repairing only what can be repaired without inventing information — a stringified schema, and a missing `type` whose contract admits exactly one value — and omitting with a warning what cannot. Both rows observed in production are recovered rather than discarded. Table filters. `eq`/`ne`/`in`/`nin` compiled a wrongly-typed operand into a containment test that silently matched nothing, so a filter written against the value the write path had stored returned an empty page instead of its rows. The operand is now read through the same column-type registry the write used, and rejected only where that registry refuses it. Range operators already behaved this way; `null` and the cleared-cell sentinel still pass through untouched. Error messages. A custom `error` on a string schema also replaced the wrong-type wording, so supplying a number for a name reported that the name was missing. Messages now distinguish an omitted field from a mistyped one, `topK` names its own bounds, the knowledge search refine reports against a field rather than the whole body, and a workspace id is bounded before it reaches a lookup. Archived file metadata. A soft-deleted file was listed but unreadable, leaving no way to check share state before restoring it. The read takes the same `scope` selector the list already exposes; the default is unchanged, and the parameter relaxes only the `deleted_at` predicate, never the authorization. Cancellation reporting. Cancelling an already-terminal run reported a durable write that never happened. The service now distinguishes the no-op and names the state it observed, and both surfaces present one vocabulary instead of the internal route deriving its own. No claim predicate or write changed. Protocol. A 401 carries a challenge naming the header the API actually reads, and a body that failed to parse is reported as an unsupported media type only when the caller positively declared a non-JSON one — after the read has already failed, so nothing that succeeds today can begin to fail. * fix(v2): correct three regressions this branch introduced, and harden its tests Adversarial review of the previous commit found that three of its "behavior preserving" claims were wrong. Each is corrected here at the layer that owns it. Table filters no longer coerce a `date` operand, and no longer throw. `date` is the one column type whose registry `coerce` is not idempotent — it drops sub-second precision — and the leaf that compiles a filter also builds the unique-constraint and upsert-conflict probes, so re-reading an already-coerced operand could stop it matching the row it was written from and admit a duplicate inside the write transaction with no error. Throwing was the second mistake: the v2 predicate grammar type-checks structure but not operand values, so a rejected operand no longer failed at submission but inside the delete, update, dispatch and cancel runners, where a filter that cannot compile means the cells it started can no longer be cancelled. Coercion is now total — it rewrites what the registry accepts and passes everything else through unchanged, exactly as before. Reviving a force-failed run no longer inherits its terminal duration. Writing `ended_at` and `total_duration_ms` on the force-fail boundary was correct in isolation, but a partial resume flips that row back to `pending` and those columns survived. The preserved value is meant to be the pause checkpoint — the run's active time — and it had become wall clock measured at the failed resume, which the checkpoint rule then faithfully carried into the next terminal write. The revival clears them only for a row that was terminal, so an ordinary paused row keeps the checkpoint it is supposed to keep. Cancelling reports the terminal state it actually observed. Reclassification now requires that nothing else went wrong, so a genuine paused-reconciliation failure survives instead of being rewritten as an already-terminal no-op, and the claim's own row count — not a snapshot read before it — decides whether this cancel terminalized the run or lost a race to something else. The status the snapshot needed rides along on the ownership query that already reads the row, rather than the second read that query's own contract warns against. A custom tool that cannot be projected now answers the same way everywhere: the list omits it, and reading or patching it by id reports it as absent rather than as a server fault. Analytics stops reporting a cancellation for a request that cancelled nothing. The tests around all of this were audited by mutating each fix and checking the suite noticed. Where it did not, the assertion is stronger now: the absent content-type branch is genuinely exercised rather than relying on a header the client library supplies, the duration encoder is pinned to the column it must measure from, execution ownership is pinned to both ids it must match, and the archived-file concealment test proves it conceals the archived read specifically. Two tests that asserted a paused branch they could not observe are gone; the rendered-SQL test that can decide it already covers them. * fix(execution): report a workflow-group cancellation as the write it performed Cancelling a workflow-group run whose log had already been cancelled, but whose cell sidecar still needed reconciliation, durably cancelled that sidecar and then reported `already_cancelled` with `durablyRecorded: false` — because the terminal-status shortcut answered from the entry snapshot alone and never asked what this request had written. The analytics event, which now gates on that field, stopped firing for a cancellation that really happened. The outcome a cancel reports is the same question whichever path answers it, so there is now one vocabulary for it rather than one the direct claim tracked and one the group transition did not. Every group result maps to that outcome through a total map, so a new group result cannot compile without deciding what it wrote, and the reclassification leads with whether this request wrote at all. A group transition that reports itself already cancelled is deliberately mapped as unknown rather than as a no-op: it leaves the sidecar alone but still terminalizes a log that was active, and the result does not say which happened. That costs nothing today, because the only snapshot that would reclassify proves the log was already terminal. * fix(execution): have a workflow-group cancellation report the writes it made Three review findings landed on the same reporting logic, each a different face of one cause: the caller could not see what the group transaction had written, so it inferred. It inferred from an entry snapshot, then from the returned kind, and the remaining blind spot was the kind that covers two different transactions — a repair that terminalizes an active log, and a genuine no-op — which left a cancel that wrote nothing still claiming a durable write when it lost a race. The transaction now reports both writes it can make, each read from that statement's own returning row and recorded immediately before the throw that already depended on it, so the report cannot drift from the write. The caller derives its outcome from those rather than from the kind, and the kind is back to naming the situation instead of standing in for the work. The group path can now always answer whether it wrote. The only remaining unknown is the direct claim when its update throws or is never attempted, which genuinely has no row count to report. |
||
|
|
ab8a64fcae |
fix(v2): close the defects live probing found (#6681)
* fix(v2): close the defects live probing found Staging finally deployed the merged release, so the surface could be exercised for real. Every fix already shipped held up. These are the defects only live traffic surfaced, plus the ones a static sweep had found and left. A cursor named a position in a sequence without naming the sequence. `cursorScopeKey` hashed only the caller's filters, so any two lists filtering on nothing but `workspaceId` produced one fingerprint and accepted each other's tokens: a tables cursor replayed against the knowledge list answered 200 and silently skipped a row. Table rows never reached that check at all, so a cursor from one table paged another. Identity now comes from the route's own contract — method plus resolved path — because a hand-written name is the step an author forgets, and forgetting it is invisible. An unresolved path placeholder throws rather than fingerprinting the template, so a misconfigured route fails on every request instead of an unlucky one. Every token minted before this is refused with an accurate message; they are single-walk and unpersisted. Knowledge search and the document list answered different questions. Search grouped same-tag filters by slot and joined them with OR while the list conjoined every filter, so `gte 9` and `lte 2` on one tag returned nothing from the list and a full billed page from search. Search now conjoins. The OR grouping replaced an explicit `|OR|` mechanism that was deleted outright, was never documented in any contract, and cost the ability to express a range on a single tag; the union it gave is still reachable as separate searches. The search body also accepted an unbounded query that was billed and then silently truncated to the embedding model's window, and ignored the tag-filter cap the list enforces. A body over ten mebibytes was reported as malformed JSON. Next's proxy truncates there, well under this app's fifty-megabyte ceiling, so the parse failed on a body the caller sent whole and the size branch was unreachable. The ceiling is now clamped to what the proxy will pass. Also: a group's output columns accepted a `workflowGroupId` and discarded it; an enrichment group could never gain an output, because a new output coordinate demanded workflow metadata a group with no workflow cannot have; `newOutputColumns` alone reported success and created nothing; a saved view stored layout references to columns that do not exist while refusing the same name in a filter; an MCP server stored `retries: 0` as three and overrode an explicit auth type; a disabled server answered tool discovery with an unclassified fault; rotating a header server's headers left it reading connected; and a run whose workflow was deleted reported the root folder path while also reporting the workflow deleted. Where the honest fix was out of reach, the contract was corrected instead of half-fixing the code: the polled run resource rebuilds `error.code` by matching the persisted message, so it can never report the two codes that need block attribution, and now says so. `OUTPUT_TOO_LARGE` is removed — no path ever emitted it. `triggers` was left alone deliberately. It reads as a closed enum but production holds 43 distinct values, because a webhook run stores its provider id; pinning the enum would refuse legitimate history a log search exists to find. The description now says the vocabulary is open. * fix(v2): clamp explicit body caps to the proxy ceiling too The previous commit clamped the default JSON body cap but left explicit per-route overrides alone, so a route declaring a larger `maxBodyBytes` still fell into the truncation it was meant to report: the four inline workspace-file routes at 70 MB and the deployed-chat route at 220 MB. Next attaches `proxyClientMaxBodySize` to every request and clones the body unconditionally for any non-GET method on a matched path, pushing EOF at ten mebibytes with only a warning, so the handler reads a truncated prefix. Those routes therefore already fail above that size — as a malformed-JSON 400. Clamping the effective limit inside the two body readers makes the same request fail as payload-too-large, quoting the limit actually in force. One existing test asserted the unreachable case, allowing a sixty-mebibyte base64 body; it now asserts what the proxy will forward intact. The inline-file path still advertises fifty mebibytes and cannot exceed the proxy ceiling until that ceiling is raised, which changes buffering for every route and belongs in its own change. * fix(v2): close the two holes the first review round found Both are places where a fix in this branch shut one door and left a smaller one open in the same wall. Letting an enrichment group gain an output meant skipping workflow resolution — but that resolution was the only thing validating a new output, so a PATCH began storing coordinates the runner can never fill. It fills a cell from `result[out.outputId]` and skips an output with no `outputId` at all, while the writer diffs on that same id and the sidebar reads and writes by it; the contract leaves it optional. The regression test added with that fix was itself asserting such a dead coordinate. Create's registry checks are now two shared helpers both paths call, and on update an output is exempt only when an identical binding already existed, so renaming a group whose enrichment has since changed still works while anything added or repointed must name a real output. `mappingUpdates` on an enrichment group now says it is inexpressible rather than resolving an empty workflow id into a missing workflow. The layout-reference check was handed the tolerant column set, so a placeholder minted to keep a dangling filter writable also whitelisted a brand-new layout reference — storing an entry the next read discards, which is the inconsistency the check was added to remove. Layout now resolves against the live columns, which is exactly what pruning keeps, while filters and sorts keep the exemption they need. |
||
|
|
8d319a430a |
fix(v2): close the correctness gaps the release audit found (#6671)
An end-to-end audit of the v0.8.1 release surfaced one regression the release itself introduced and a set of filter/cursor gaps that let a caller's spelling change what a query answered. An `enrichment` workflow group stored no `workflowId`. The public contract invites a caller to omit it, the write persisted caller input through an `as WorkflowGroup` cast that hid the omission from the type checker, and the response schema still required it — so the write committed and then the outbound parse threw. Because the list presenter maps every group through that schema, one such row made GET, PATCH and DELETE on that table's groups fail from then on, with no public way to remove it. The cast is gone rather than papered over, so the same class of omission cannot recur silently. Knowledge tag filters accepted any operator string and then ignored an unrecognized one in opposite directions: the document list dropped the predicate and answered with the whole knowledge base, while search fell through to equality and answered a different question. Both now reject at the boundary. `.strict()` is applied on the v2 chain only — v1 has always stripped unrecognized keys, and the `between`-requires-`valueTo` rule already closes the mis-cased `valueTo` trap on both versions. Cursor scopes bound set-valued filters to the caller's ordering: `all`/`any` clause order and `in`/`nin` operand order in the table predicate, and the raw `resourceType` text on audit logs, whose query splits it into an `inArray`. Audit logs is canonicalized on both sides, because canonicalizing the scope alone would have given two genuinely different result sets one fingerprint. Also: the exposed-header list reached only the fallback CORS policy, so all five matched rules — including the wildcard-origin execute route, the only one that emits `X-Run-Id` — could not hand a browser the run id or a 429's `Retry-After`; a bulk row update reported an uncoercible value only when its filter happened to match; the cost and duration windows accepted an inverted pair and answered it with an empty page; and the sortless runs list advised callers to fix a `sortBy` it rejects. |
||
|
|
6de8ba2504 |
fix(v2): close the correctness gaps an end-to-end audit found (#6655)
* fix(v2): stop a third-party tool description from 500ing MCP discovery
`v2McpToolInputSchema` declared `description: z.string().optional()` inside a
`.catchall(z.unknown())` object, and a declared key beats the catchall. The MCP
SDK's own `ToolSchema.inputSchema` does not declare `description` at all, so any
value — including the JSON `null` a Python server emits for an absent one —
passes its validation and reaches Sim unchecked. The builder's outbound `.parse()`
then threw, and the discovery error policy correctly declines to classify a
Sim-side schema defect, so the endpoint that completes MCP onboarding answered a
bare 500. The key is dropped and left to the catchall; `type`, `properties`, and
`required` stay pinned because the SDK enforces those at least as tightly.
Also in the v2 resources family:
- The single-resource query schemas for MCP servers, skills, custom tools, and
secrets are now `.strict()`, matching every list in the same family. A mistyped
flag was silently ignored behind a 200.
- `openapi/resources.ts` re-derived `RESOURCE_ERRORS` and
`RESOURCE_CONFLICT_ERRORS` inline in 21 of 22 operations. They now import the
shared constants; the generated spec is unchanged, which is the point.
- The internal MCP refresh route stamped `updatedAt` alongside `lastToolsRefresh`.
`updatedAt` means "configuration last changed" and is a public keyset sort, so
a refresh moved rows out from under an in-flight page. `updateServerStatus`
already held that invariant; the route now matches it.
- The discovery cooldown is a typed `McpServerCooldownError` rather than a
substring search for `cooldown`. `McpConnectionError` interpolates the server's
display name into its message, so a server named after the word was reported as
a transient cooldown when its connection had genuinely failed.
* fix(v2): close correctness gaps in the workflows deployment surface
Deploy and rollback bodies were plain objects, so a misspelled key was
stripped rather than rejected. On rollback that is silent misbehavior:
an omitted `version` legitimately means "reactivate the preceding
version", so `{"versoin": 5}` rolled back somewhere else and answered
200. Both v2 bodies, the run-read query, and the versions cursor are now
strict.
Deployment versions are an `integer` column, but the path param, the
versions cursor, and the v1 body each bounded it differently or not at
all — an out-of-range value overflowed the comparison into an
unclassifiable 500. One exported bound now covers all three.
Resume admission raised bare `Error`s for a stale contextId or an
already-resumed run, which the resume surfaces could not classify and
reported as 500. They now use the sibling `ResumeAdmissionError` already
in that file, carrying 404/409/400 and whether an automatic retry can
clear the refusal.
Docs corrections: rollback publishes the 409 its webhook-path conflict
already produces; deploy/undeploy/rollback reject a workspace key with
403, not the concealed 404 they documented; the workflows OpenAPI module
imports the shared error sets instead of re-deriving them; import and
the folder ops explain their folder-tree 413. The export route is marked
`headSafe: false` so a HEAD probe stops filing a WORKFLOW_EXPORTED audit
event for an export that never happened. `runId` is one bounded schema
across the run and log resources.
* fix(v2): conceal knowledge upload existence, tighten knowledge/files bounds
Security: the four knowledge document-upload routes rendered a bare upload
error policy with no resource concealment, while every sibling knowledge route
uses one. Because the use case resolves the knowledge-base context before
workspace authorization, the unconcealed 403 told any valid API-key holder that
a knowledge base exists in a workspace it cannot reach — the exact signal
GET /api/v2/knowledge/{id} withholds by answering 404 either way. All four now
use the composed concealing policy, which also renders the 415/402/413 the
route-local renderer already handled; that duplicate renderer is deleted.
Contracts:
- POST /knowledge/search is strict. It was the only non-strict v2 request body,
so a mis-cased rerankerEnabled or topK returned 200 with the key stripped,
changing what the caller was billed and silently disabling reranking.
- The document list takes limit, cursor, and search from the shared v2 schemas.
search was an unbounded, empty-accepting v1 string, so ?search= answered 200
with a full page here and 400 on GET /knowledge, and the term reached an
unindexed filename LIKE scan with no ceiling.
- The 16 non-strict single-field workspace query slices across both families are
strict, matching GET /knowledge/{id}/tags.
- GET /audit-logs takes workspaceIdSchema instead of a bare string (?workspaceId=
was forwarded as a filter and returned zero rows) and the shared run-window
bounds for startDate/endDate.
Documentation:
- listAuditLogs drops the 404 it has no code path to emit.
- upsertFileShare describes its workspace-key refusal as the 403 it renders;
the operation denies the key by principal kind, which the concealment policy
does not rewrite.
- The 12 body-reading knowledge and files operations publish the 413 their
pre-validation body read raises, and the file list publishes the folder-tree
413 its now-capped path index raises.
Correctness: queryWorkspaceFilePage loads its folder path index under
MAX_FOLDERS_PER_WORKSPACE like the workflow, table, and knowledge lists. An
uncapped index does not fail on truncation, so a real folder outside the read
rows resolved to undefined and answered "Folder not found".
* fix(v2): publish the reachable 413 on body-carrying resources ops
`parseRequest` buffers a JSON body through `parseJsonBody` under
`DEFAULT_MAX_JSON_BODY_BYTES` before any schema runs, and the v2 builders supply
`V2_PARSE_DEFAULTS.payloadTooLargeResponse`, so every operation whose contract
declares a body already answers 413 above the cap. The resources family
published it on none of them. A status a caller cannot see in the spec is a
status they will not handle.
Adds `RESOURCE_BODY_ERRORS` and `RESOURCE_CONFLICT_BODY_ERRORS` to the shared
sets and applies them to the seven affected operations: createMcpServer,
updateMcpServer, createSkill, updateSkill, createCustomTool, updateCustomTool,
and setSecret. All seven are `defineV2JsonRoute` handlers on non-GET methods
with no `parseOptions` override, so the 413 is genuinely reachable on each. The
new sets are opt-in rather than folded into the base sets precisely because
reachability is not automatic — an operation with no body, or one whose payload
reaches it through an uncapped path, would be publishing a response that can
never arrive.
A sweep test pins the invariant across the resources, billing, and logs
documents. It is one-directional by construction: several bodyless operations
publish 413 for their own folder-tree and render ceilings, so the converse would
flag correct documentation.
Also completes the shared-constant consolidation started in
|
||
|
|
29853fbbcf |
improvement(docs): make the API reference read as code and unify its type token (#6653)
* improvement(docs): make the API reference read as code, and unify the type token The API-page font override matched every span/div/p inside the page, which outranks the .font-mono class on specificity, so every parameter name, type, and identifier silently rendered in the body sans face. Exclude .font-mono so code tokens stay monospace. Consolidate the three divergent type-slot treatments — plain scalar, union, and schema reference each carried their own chip definition, differing in size, weight, face, and box height — onto one code token that reuses the docs inline-code recipe and the platform's 20px chip height. Demote the row metadata: 'required' and 'header' were filled pills, 'required' on the error token, making a constraint the loudest element on the page and a page of required parameters read as a page of alarms. Both are now uncontained text, leaving the type token as the only box on the row. Pin the two 'application/json' labels to one treatment; the Request Body and Response headers rendered the same string at different weights and faces. * improvement(docs): mono status-code tabs, and match fumadocs' lucide icons to emcn Status codes in the example panel are numeric literals and render as code everywhere else on the page, including the Response header's own trigger, but fumadocs rendered the strip in the body sans face. Language tabs sit in a separate container and stay sans — those are product names, not code. fumadocs draws a few lucide glyphs on API pages that its client-component overrides do not expose (the heading anchor and the code-block copy button). emcn strokes at 1.55 and lucide at 2, so those icons read heavier than every icon around them; match the weight. * fix(docs): align the auth type chip with every other property row, and wrap example code The auth row collapses its real `<token>` type and renders the chip through ::after, so the span is only a wrapper — but it still matched the type-token rule and kept that rule's border, height, and gap. The border drew a second empty box around the real chip and the gap opened in front of it, because the collapsed text remains an anonymous flex item; together they pushed the chip right by roughly 8px that no other row had. Example-panel code overflowed sideways instead of wrapping: fumadocs sizes the block with `w-max`, so it grew to its longest line inside a 400px scroller and the existing pre-wrap never applied. Cap the width, switch break-all to overflow-wrap anywhere so only unfittable tokens split, and reserve room for the copy button fumadocs floats over the first line. * revert(docs): let example code overflow instead of wrapping Wrapping restarts every continuation line at column zero, and in a JSON body indentation is what carries nesting depth — so a wrapped response misreports its own structure. A hanging indent keeps the depth but needs the shiki lines forced from flex rows to blocks, which breaks the line rhythm. Removes the pre-wrap rules rather than repointing them: fumadocs sizes the block with w-max, so the previous rule never took effect and overflow was already the behaviour on the page. * fix(docs): tighten array type tokens and keep the union separator legible An `array<T>` slot holds its angle brackets as bare text nodes, which become anonymous flex items, so the slot's gap prised `array<` and `>` away from the type they wrap. Drop the gap and let the union separator carry its own margin; this also makes the auth row's gap override redundant. The separator was dimmed twice, by a muted token and again by opacity, which on the dark chip fill left `string | null` reading as `string null`. * fix(docs): restore the hidden API key description, and drop dead API-reference CSS The rule hiding the trailing `In: header` line matched `p:has(> code)`, which is a shape, not a target — every scheme description in our specs cites a status code, so the whole explanation of personal vs workspace-scoped keys was display:none on every API reference page. Match the last child instead, and shorten the description to one line now that it renders. The dropdown trigger's hover rule had been left below a new id-qualified base rule that outranked it, so the trigger could no longer change colour on hover. Removes what does not run: the four `::-webkit-scrollbar` rules (specifying a non-auto scrollbar-width makes Chromium ignore them, and Firefox never had them) and an `order: 2` block whose selectors and declaration the type-token rule above it already carried. Names the two values the API reference repeats — the monospace stack, written out eleven times, and the 12.5px code size, written nine — as --font-mono-stack and --text-code. Also drops four !important declarations that already won on specificity, a --text-muted fallback that can never fire, and a lucide selector subsumed by the one beside it. * refactor(docs): define the API-reference chrome once, and cut the commentary The metadata face — size, leading, weight, mono stack — was written out in seven rules that a comment asked future readers to keep in sync by hand; it is now one rule those seven consume, each adding only its own colour, content, and order. The auth row's chip likewise re-derived all eleven declarations of the type token and now joins that rule, keeping only its label. Comments were running longer than the rules they documented — 88 added comment lines against 73 declarations. Trimmed to the load-bearing facts: cascade traps, browser behaviour, and the bugs a rule prevents. Dropped the block narrating why the wrap rules were reverted, which duplicated its own commit message. Also retires a scrollbar token left unreferenced by the webkit removal, moves the last two fumadocs colours in our own components onto platform tokens, and brings the callout icon to 1.55 so the docs really do have one icon weight. * fix(docs): keep the union separator in the type token's own face The `|` between union members is a classless span, so the page-wide `span:not(.font-mono)` rule assigned it the body sans face while the members beside it stayed mono — one chip rendering in two faces. Applies the inherit reset to every descendant of a type token rather than just its links, so anything fumadocs nests there later is covered too. |
||
|
|
1fa40b8118 |
feat(v2): complete and align the v2 API surface (#6643)
* fix(v2): close four validation holes in the logs and billing surfaces
Each of these answered a caller-supplied value with a 500 or a silently
wrong result instead of a 400.
- `GET /api/v2/logs` accepted any string as `startDate`/`endDate`. The
route constructs a `Date` from it, so `?startDate=abc` reached the
driver's timestamp mapper as an `Invalid Date` and 500'd. Both bounds
now carry `.datetime()`, matching the sibling run list so one timestamp
works on both collections. This narrows the accepted set: a date without
a time and an offset-bearing timestamp are now rejected, and the field
descriptions say "UTC ISO 8601" rather than overpromising "ISO 8601".
- `v2BillingStatusQuerySchema` was the only non-strict query schema in its
family, so a mis-cased `workspaceID` was stripped and the caller got
account-scope billing in place of the workspace scope it asked for — a
wrong answer about money, served as a 200.
- An unresolvable `cursor` on `/api/v2/billing/logs` applied no cursor
condition and restarted the sequence at page 1 while still reporting
`hasMore`, so a pager holding a cursor across a deploy loops over the
first page and counts the same credits on every lap. It is now a 400.
The message does not reuse `INVALID_CURSOR_MESSAGE`, which names
`sortBy`/`sortOrder` params this collection does not accept.
- The logs `status` field disagrees with the run resources for the same
run: the run projection overlays `paused` from `paused_executions`,
so an ordinary human-in-the-loop pause reads `paused` there and
`pending` here. Reconciling would mean joining `paused_executions` in
this read and silently moving live runs between two buckets of a
shipped field, so the divergence is documented on the contract instead.
* feat(v2): expose the MCP tool plane and page the MCP server list
Registering an MCP server through v2 dead-ended: nothing on the public
surface ever ran tool discovery, so connectionStatus, toolCount, lastError,
and lastToolsRefresh stayed at their registration defaults and there was no
way to read a server's tools without opening the UI.
Adds GET /api/v2/mcp-servers/{id}/tools over a thin use case composed from
the existing mcp_servers.tools.discover operation, resolveServerContext, and
mcpService.discoverServerTools. It is personal-API-key-only — discovery
resolves the acting user's own OAuth credentials, which a workspace key
cannot supply — and the contract says so rather than letting callers meet an
unexplained 403. Discovery failures are classified instead of collapsing
into a 500: an unreachable or cooling-down server is a retryable 503, a
stale OAuth grant is a 401.
Also pages GET /api/v2/mcp-servers. It was the one unbounded list on the v2
surface, classified full-set on a bounded-by-construction rationale that
only holds for folder lists; nothing caps how many servers a workspace
registers.
* feat(v2/tables): strict row bodies, a filtered row count, and round-trippable required columns
Three tables gaps from the v2 capability evaluation.
Strictness. Every v2 tables request body is now `.strict()`. The row family
was the whole hole: `POST /query` sent v1's `filter` key answered 200 with a
fully unfiltered page, because Zod strips unknown keys unless told not to. The
same laxity covered the row create/update/delete/upsert/find bodies, the
run and cancel-runs bodies, the enrichment body, and — outside the row family
but the same class — the column delete, view create/update, and export bodies.
A contract sweep now walks every body-bearing tables contract and fails if one
of them stops rejecting an unrecognized key.
Filtered row count. `POST /api/v2/tables/{tableId}/query/count` answers the
question v1's `includeTotal`/`totalCount` answered and the `{data, nextCursor}`
envelope has nowhere to put: how many rows a predicate matches. It binds the
existing `queryTableRows` use case with `includeTotal: true, limit: 1` — no new
domain logic and the same `tables.rows.query` read policy. The use case types
`totalCount` as nullable because paged callers can decline it; this route always
asks for it, so a null is treated as a broken invariant rather than presented as
a fabricated zero.
Required columns. `required` is accepted on create-table, add-column, and
update-column, matching v1. v2 emitted the flag on every read while stripping it
from every write, so a column could not round-trip. Enforcement was already
complete: turning it on over rows with null, missing, or empty cells is rejected
by the domain.
* test(skills): pin the workspace-API-key split as structural, not accidental
A workspace API key can create a skill it can then never update or delete,
which no sibling resource does — so the asymmetry reads like an oversight
worth widening. It is not. Skill edits are authorized by the per-skill
editor row belonging to the acting user, which is why update/upsert/delete
declare a 'read' floor rather than 'write': workspace role is not the
authority. A workspace key carries no user subject, so allowing one replaces
a 403 with an unclassified PrincipalSubjectUserRequiredError that the v2
surface renders as a caller-reachable 500.
Records the reason on the registry and pins it, so the next reader finds the
argument instead of flipping the flag.
* feat(v2): read deployment state, and undo a file delete
Two v2 reads that existed only as a side effect of a mutation.
`GET /api/v2/workflows/{id}/deployment` publishes the state the deploy,
undeploy, and rollback responses carry, plus `needsRedeployment` — which
those responses structurally cannot carry, because they answer at the
moment the draft and the live version are equal. A caller that lost the
mutation response, or that polls from another process, had no way to ask.
Reuses `readWorkflowDeploymentStatus` behind `workflows.read`, the same
use case the internal status and deploy GETs already adapt.
`DELETE /api/v2/files/{fileId}` was a soft delete with no way to see what
it archived and no way to reverse it. `GET /api/v2/files?scope=archived`
pages the archived set and `deletedAt` on the file resource dates each
one; `POST /api/v2/files/{fileId}/restore` reverses the delete through
the existing `files.restore` operation. Restore is not a pure undo — it
returns the file to the root and renames it on a collision — so the use
case now reads the file back and both the response and the OpenAPI
description say what actually came back rather than what was deleted.
`scope=all` is rejected on the list for the reason the internal contract
already gives: it drops the `deleted_at` predicate and cannot use the
partial index. `scope=archived` combined with `folderPath` 404s when the
containing folder was archived too, which the contract documents.
* fix(v2): keep the unresolvable-cursor rejection a 400 on every surface
The cursor rejection lived in shared billing core but was an OrchestrationError
only, which the session-only GET /api/users/me/usage-logs cannot project: that
route is raw withRouteHandler and readTypedError matches instanceof HttpError,
so any signed-in caller typing ?cursor=x got a 500. UnknownUsageCursorError is
an HttpError carrying the OrchestrationError as its cause, so the v2 route still
renders BAD_REQUEST off the cause chain and the internal route answers 400.
Also closes the other half of the run-list parity: an inverted window on
GET /api/v2/logs is now a 400 instead of a silently empty page.
* fix(v2/tables): sweep union bodies per member and name the shapes on a rows 400
Review follow-ups on the strictness work.
The sweep was vacuous on the one union body it covers. Parsing
`{ notAContractField: true }` against `v2CreateTableRowsBodySchema` and looking
for `unrecognized_keys` anywhere in the issue tree is satisfied by either member
alone, so dropping `.strict()` from the single-row branch shipped green —
reproduced, 36/36 passing with the regression in place. The sweep now flattens a
union body into its members and asserts each one separately; removing `.strict()`
from either branch now fails a case that names it.
`POST /rows` answered an unknown key with `Invalid input`, the exact message the
v2 conventions name as failing the actionable-error rule, because a union
surfaces `invalid_union` first. The union now carries a message naming both
accepted shapes; the per-member failures still ride along in `details`.
Two TSDoc corrections. The `required` docstring claimed the domain rejects
turning the flag on over rows with empty cells — true of the update path, false
of add-column, which applies the flag as given (the same shape `unique` already
had here). And `.strict()` binds the top level only, so the view `config` object
and the shared sort-spec elements still strip unknown keys; both docstrings now
say so instead of implying full coverage.
* fix(v2): classify MCP discovery failures by type, not by substring
The tool-discovery error policy consumed categorizeError's status, whose
fallback is a substring match on the upstream message. Three consequences,
all caller-visible:
- A ZodError from the builder's own response `.parse` contains `invalid_type`,
so a Sim-side response-schema defect answered 400 "Invalid request
parameters" and suppressed the builder's 500 and its unhandled-error log.
- An upstream `Invalid params` or `not found` became the caller's 400/404 on a
request the contract had already validated.
- A stale OAuth grant to the third-party server answered 401, the status this
surface reserves for a missing or invalid Sim API key, so a client would
rotate a credential that was never the problem.
The policy now dispatches on the MCP error families and returns null for
anything else. Reauthorization is a 409 carrying
`details.code: MCP_SERVER_REAUTHORIZATION_REQUIRED`; an unreachable, slow, or
cooling-down server is a 503 with a constant message.
Also: widen the shared server path-param description now that it covers tool
listing, map the list query explicitly so no undeclared `cursor` reaches the
use-case input, and document the endpoint's write side effects.
* merge: bring in the MCP tool plane workstream
* feat(v2): make knowledge tags usable and let documents be updated
v2 accepted tag slots on upload and filtered search by tag display name,
but no response ever returned a tag value and nothing listed the
vocabulary, so a shipped feature dead-ended in the public API. A document
that failed processing could only be deleted and re-uploaded, and
retiring 500 documents cost 500 requests.
- GET /api/v2/knowledge/{id}/tags returns the vocabulary (display name,
slot, field type) as a full-set list.
- Document list and detail responses carry `tags`, keyed by display name
exactly as search keys its result metadata. Writes stay slot-keyed; the
tags endpoint is the mapping and the contract documents the split.
- PATCH /api/v2/knowledge/{id}/documents/{documentId} renames, enables,
disables, retags, or requeues processing. Derived indexing state is not
writable: asserting `processingStatus` on an unindexed document would
corrupt search. A retry may not ride along with field updates.
- PATCH /api/v2/knowledge/{id}/documents bulk-enables or bulk-disables.
Bulk delete is deliberately absent — that operation records no semantic
audit, and a public bulk delete would empty a knowledge base leaving no
DOCUMENT_DELETED entries.
- The document list accepts the same name-based `tagFilters` as search;
the name-to-slot resolver moves out of search into a shared helper, and
the filters are stamped into the offset cursor scope so a replayed
cursor cannot cross a filter change.
- Search accepts `rerankerEnabled`, `rerankerModel`, `rerankerInputCount`
and returns `rerankerScore`; `rerankerApiKey` and `skipUsageBilling`
stay unexposed. Every result now names its `knowledgeBaseId`.
knowledge.tags.list flips from workspaceApiKey 'deny' to 'allow' (and
gains the workspace_api_key principal kind) so it matches the sibling
reads knowledge.documents.list / read / search. The vocabulary is
required input for two operations a workspace key can already perform.
Every tag write stays human-delegated.
* fix(v2): name every 403 cause, unfork boolean params, close nested strictness holes
Four cross-cutting consistency gaps on the v2 public surface.
**403s now carry a machine-readable cause.** The conventions skill mandated
`error.details.code` on 403 and nothing emitted one, so a client had to
string-match prose to tell "raise this member's role" from "this workspace
refuses personal keys" from "buy an enterprise plan" — four different
remedies behind one status, and every message reword a silent break. The
vocabulary is a closed set, `FORBIDDEN_DETAIL_CODES`, with a `Record` of
descriptions beside it that the generated OpenAPI 403 description is built
from, so a code cannot reach the wire unpublished. Refusals throw
`ForbiddenOperationError` in the domain and `v2CaughtOrchestrationError` —
the function every v2 error policy falls through to — attaches the code, so a
route cannot forget it. The audit-log resolver distinguished four causes and
collapsed them into one; it now names each.
Cross-tenant refusals deliberately get no code: they are concealed as 404 and
naming their cause would hand back the existence signal the concealment
withholds.
**Two boolean query params rejoin the majority.** `?includeDeparted` and
`?includeOutput` were `'true'`/`'false'` string enums inherited from the
internal shapes they reused, while four sibling params were real booleans.
Both move to `booleanQueryFlagSchema`, which still coerces both strings — a
strict widening, so an existing caller is unaffected, and the spec stops
telling callers to send a string.
**Two nested strictness holes close.** `.strict()` binds the top level only,
so `sort: [{ field, direction, nulls: 'last' }]` was answered 200 with the
null-ordering request dropped, and an unknown key inside a saved view's
`config` was accepted and discarded — the headline `filter` bug one level
down. `sortSpecSchema`'s element and both view-config schemas are now strict.
Safe on the read side because `normalizeStoredViewConfig` projects the
schemaless stored blob onto the declared keys first, so a legacy row cannot
turn into a 500.
The two sort dialects stay as they are. `/logs` and `/workflows/{id}/runs`
have one sortable column, so there is no `sortBy` to pair with; renaming
`order` breaks every caller and an alias is a second spelling of one thing
with undefined precedence. Both contracts and the skill now state the rule.
* style: format the files the workspace-scoped lint gate does not reach
`turbo run lint:check` runs `biome check .` per workspace, so `scripts/` at the
repo root is outside the graph and four changed files were unformatted — one of
them a merge artifact from reconciling the route baseline across branches.
* fix(v2): collapse the four knowledge document projections onto one null-tolerant summary
Extracts toV2DocumentSummary in app/api/v2/knowledge/utils.ts and composes the
list, upload-acknowledgement and detail presenters from it. toV2TaggedDocument
serialized uploadedAt with a bare .toISOString(), so a document with no upload
timestamp threw where every sibling returned null and the contract declares the
field nullable.
Also consolidates the two Zod strictness walkers onto one shared introspection
helper that unwraps wrappers and expands unions, closing the hole where a
union-shaped schema answered null and was skipped by the pagination sweep.
* fix(v2): stop HEAD driving MCP discovery, and unbreak the updatedAt keyset page
B1: Next aliases HEAD onto GET, which RFC 9110 permits only because GET is safe.
The MCP tool-discovery GET is not: it opens a live connection to the registered
endpoint and writes the outcome onto the server row. The v2 JSON builder gains a
headSafe option, default true, and the discovery route declares itself unsafe —
a HEAD is authenticated and rate-limited, then answered bodiless.
B2: a discovery status write stamped updatedAt, which this branch added as a
keyset sort, so any concurrent discovery duplicated and skipped servers across a
caller's pages. Discovery liveness already has lastConnected, lastToolsRefresh,
lastError and statusConfig.
B4: a public refresh now skips the positive cache but keeps the failure cooldown,
so it cannot be used to drive a connection attempt per request at a failing
endpoint. An explicit user action on their own server keeps the full bypass.
B6: the consecutive-failure counter is incremented SQL-side rather than read,
incremented and written back, and the success branch carries the same workspace,
liveness and staleness guard the failure branch already had.
* fix(v2): bound the bulk update echo, close the search leak, and make the docs true
B3: a selectAll bulk document update echoed every changed identifier, which the
request does not bound — a 100k-document knowledge base produced a multi-megabyte
array, materialized and then element-wise validated. The use case now reports
whether the selection was unbounded and the presenter omits the echo.
A1: the knowledge search presenter spread the whole use-case result, which also
carries userId, workspaceId, a cost breakdown and a live secret-trace registry.
Only Zod's default key-stripping kept them off the wire. Projected explicitly.
P1-a: GET /knowledge/{id}/tags advertised all 17 slots while the document PATCH
accepted only the seven text ones. The writer already coerces every slot type,
so the PATCH now takes all 17 in their declared types, with a 400 where a
malformed value used to silently clear the tag.
P1-b: both new PATCHes deny workspace API keys and now say so.
P1-c: the two table query reads declare maxBodyBytes and now document the 413.
P1-d: getWorkflowDeploymentV2 loses its legacy suffix.
C3: deletes two orchestration error mappers with no callers that mapped
'forbidden' with no details.
D2: a stored null in table_views.config survived the pick and failed the
response schema.
Also folds the six 'bounded set' paraphrases onto one FULL_SET_LIST constant,
shares the run-window date bound between the logs and runs lists so their
documented parity is enforced rather than asserted, adds the missing barrel
export for FORBIDDEN_DETAIL_CODE_DESCRIPTIONS, and strictens two response
schemas whose peers were already strict.
Migrates 40 v2 route tests onto the shared @sim/testing harness: 26 asserted a
rateLimitSubjectIds shape v2 auth never returns, 26 asserted the wrong
refillRate, 33 could not exercise their 401 path at all, and 6 hard-wired the
rollout gate to null.
* fix(mcp): bound the connect handshake, and stop the 403 description over-claiming
B5: the connect clamp was getMaxExecutionTimeout(), the workflow ceiling of
seven days, so the real bound became the server row's own timeout — which the
registration contract permits up to 300s — times the connect retries. A slow
server could hold a Node request for roughly twenty minutes. Connecting is not a
workflow run, so the handshake now shares the one-minute ceiling tools/list
already applies to itself.
C2: the generated 403 description asserted that error.details.code names the
cause on every 403. Nine domain refusals still throw a bare forbidden
OrchestrationError and reach the wire codeless, so the wording now says 'where
the cause is one a caller can act on'. Reparenting those throws is left as a
deliberate change: one of them is a cross-tenant refusal that belongs in the
codeless class and would change its status.
* chore: reconcile the route ratchet with staging
* style: sort imports and format the three files biome flagged
* fix(openapi): import the forbidden-code constants from their module, not the application barrel
The barrel also re-exports the authorized use-case layer, which loads
@sim/db at import time. That pulled a database connection into the
OpenAPI spec check, so check:audits failed wherever DATABASE_URL is
absent, including CI.
|
||
|
|
81108d5a4e |
fix(v2): serve HEAD, advertise PATCH, and document the reachable 403 (#6623)
* fix(v2): serve HEAD, advertise PATCH, and document the reachable 403 Three HTTP-semantics defects on the v2 surface, all found by probing the published contract rather than the happy path. **HEAD answered 500 on every v2 endpoint.** Next implements a missing `HEAD` export by aliasing it onto `GET` and dropping the body when it sends, so a route's `GET` legitimately runs with `request.method === 'HEAD'`. The builders' method guard compared that against the contract's declared method and threw, so `HEAD /api/v2/workflows` and every sibling replied 500 — which is what health checkers, uptime monitors, link checkers, and some CDNs send, all of them reading the API as hard-down. RFC 9110 §9.3.2 makes HEAD identical to GET but for the body, which is exactly what running the GET path produces. Fixed once in `methodMatchesContract`, shared by all five route builders; every other mismatch stays a hard error so a handler exported under the wrong verb still fails loudly. **CORS advertised `GET,POST,OPTIONS,PUT,DELETE`** while the v2 spec has 17 `PATCH` operations, so a browser preflight for any of them was rejected. It also advertised `PUT`, which two operations use — the shape of a hand-maintained list outgrown by its surface. The list stays hand-written because middleware cannot import the contract tree without pulling Zod into the edge bundle, but it is now pinned by a test that sweeps the real contracts and fails on any method it omits. **Six operations omitted a 403 their siblings documented** — three knowledge reads and three file-upload operations. Traced from the code rather than the spec: `requirePermission` throws `NoWorkspaceAccessError` for no access at all (concealed as 404) but `InsufficientWorkspacePermissionsError` for access below `minimumRole` (a real 403), and `PersonalApiKeysDisabledError` reaches every operation a personal API key can call. So 403 was reachable on all six and the omission was an accident of hand-assembled error lists, not a policy. They now use the shared `RESOURCE_ERRORS` / `RESOURCE_CONFLICT_ERRORS` sets, and two operations spelling those same sets by hand were normalized onto them. All 128 documented operations now declare 403. The rules for HEAD, for the 403/404 split, and for using the shared error sets are recorded in `.agents/skills/v2-api-conventions/SKILL.md`. * test(proxy): update the CORS policy assertion to the served method list `proxy.test.ts` pinned the previous hand-written method string, so widening `resolveApiCorsPolicy` to advertise PATCH and HEAD left it asserting a list the middleware no longer returns. The literal is kept rather than imported from `proxy.ts` so the test still pins the exact wire value independently of the implementation. * refactor(v2): retire the error sets that could omit Forbidden The three knowledge reads and three upload operations lost their `403` by assembling `[...VALIDATED_ERRORS, ...]` by hand, and `VALIDATED_ERRORS` / `STANDARD_ERRORS` were the only exported sets that omit `Forbidden`. Migrating the last consumers to the shared `RESOURCE_*` sets left both unreferenced, so deleting them turns the fix from a one-time cleanup into an invariant: there is no longer a building block from which a workspace-scoped operation can assemble an error list without `Forbidden`. Regenerating the specs produces no diff, so the migration is output-neutral. Also folds `method-match.test.ts` into `definition.test.ts` to match the repo's `feature.ts` -> `feature.test.ts` convention, types `contractMethod` as `HttpMethod` so a contract declaring `HEAD` is unrepresentable, and drops the duplicated Next-aliasing rationale so `methodMatchesContract`'s TSDoc is its single home. * fix(cors): expose the API response headers a browser client needs Without `Access-Control-Expose-Headers` a browser can read only the six CORS-safelisted response headers, so the rate-limit budget, the `Retry-After` a 429 or 503 asks the caller to observe, and the request/run correlation ids were all on the wire but invisible to `fetch()`. Server-to-server callers were unaffected, which is why it went unnoticed. Exposed on the default `/api` policy only. The per-route `CORS_RULES` entries are wildcard-origin public endpoints and opt in individually if they ever need it, so this does not widen what an anonymous cross-origin caller can read from them. |
||
|
|
6541a22aa6 |
fix(v2): tell a caller when to come back on every failure meant to be retried (#6625)
* fix(v2): tell a caller when to come back on every failure meant to be retried Three related gaps in retry signalling, found auditing the v2 surface against RFC 9110/6585 and against how Stripe, GitHub and Google's AIPs handle the same problems. **No 503 carried `Retry-After`.** Every one of them — the three route builders' `unhandledErrorResponse`, the execute and resume routes, and `serviceFailureResponse` — funnels through `v2Error`, so the default lands there, keyed on the response *status*: `Retry-After` is defined against the status, and the status is the only half of the code/status pair a client sees. A caller that supplies its own value still wins. RFC 9110 §15.6.4 makes this a `MAY` rather than a `SHOULD`, so it is a deliberate improvement, not a conformance fix: without it a client's only defensible policy on a 503 is an immediate retry, and Sim raises 503 exactly when a dependency is too degraded to absorb one. **A 429 that already knew its wait threw it away.** The admission descriptors declare `retryAfterSeconds` per denial, but mapping a descriptor onto a preprocess error copied only `statusCode`, `code` and `retryable`. A concurrency denial therefore reached the client as a bare 429 with no `Retry-After` despite the policy layer having named the wait five seconds earlier. The value now travels `descriptor.retryAfterSeconds` → `PreprocessExecutionError.retryAfterMs` → `ExecuteWorkflowServiceFailure.retryAfterMs` → `serviceFailureResponse`, so the transport reads a number the policy owns instead of re-guessing one. The 503 default is now only the floor for paths with no policy signal. **One failure must not advise a retry at all.** `ASYNC_ENQUEUE_AMBIGUOUS` is a 503 whose enqueue may have succeeded — it deliberately retains its execution-ID claim because a job may already exist. Telling that caller to come back in five seconds invites a client with no `X-Run-Id` to start, and bill, a second run of the same workflow. It opts out via `omitRetryAfter` and returns the run id so the caller reconciles instead. `ADMISSION_RETRY_AFTER_SECONDS` is reused rather than restated, so the execute route's capacity 429 and every other surface's 503 cannot drift apart. Also records the audit in `.agents/skills/v2-api-conventions/SKILL.md`: the retry rule, the cursor-tampering invariants, and reasoned rejections of RFC 9457 problem+json, the `RateLimit-*` draft fields, renaming `X-RateLimit-*` under RFC 6648, 422-for-semantic-validation, `Location` on 201, ETag/`If-Match`, and `merge-patch+json` — each with the spec text and the industry evidence, so they are not re-litigated. `Deprecation`/`Sunset` on v1 is left open pending a retirement date, which is a product decision. * docs(v2): name the one 503 that omits Retry-After in the shared contract The shared ServiceUnavailable description claimed every 503 carries the header, which the ASYNC_ENQUEUE_AMBIGUOUS response deliberately does not. It now says the header is normally present and names that exception, so the published contract matches the runtime behaviour for all 128 operations. |
||
|
|
5cf60f6a41 |
fix(v2): give every collection one pagination contract and close four envelope holes (#6620)
* fix(v2): give every collection one pagination contract and close four envelope holes
A fractional `limit` reached Postgres as `LIMIT 2.5` and answered 500 on both
`GET /workflows` and `GET /audit-logs`: each list re-declared the param inline,
and these two copies lost their `.int()`. The same divergence left `limit`
validated five different ways and five collections emitting `nextCursor` while
accepting no `limit` at all, or accepting one and silently discarding it.
Adds `v2PaginationFields()` in `contracts/v2/shared.ts` — a bounded integer
`limit` and an opaque `cursor` — and adopts it across all 17 paged lists, so the
family cannot drift again. `/files`, `/logs` and `/tables` keep the truncate-and-
clamp leniency they published, now as an explicit named mode rather than three
hand-rolled copies.
Gives `/skills`, `/custom-tools`, `/secrets`, `/credentials` and `/knowledge`
real pagination using the existing cursor codecs: a keyset for the four whose
page comes from one ordered SQL read, and the offset cursor for `/skills`, whose
merge of the static builtin registry into DB rows cannot be expressed as a SQL
keyset. Each keyset sort now ends in a unique `id`; knowledge tie-broke on
`createdAt`, which cannot separate rows sharing a millisecond.
Two correctness fixes pagination forced: the secrets visibility filter moved from
a post-query JS pass into SQL, because trimming rows after the page is cut
returns fewer than `limit` while `nextCursor` claims more; and the skills list
stopped selecting the 50k-char `content` column only to discard it.
Also restores the canonical error envelope where it had holes: a malformed JSON
body returned a bare `{"error":string}` because the envelope was a per-route
opt-in only 8 of 77 routes remembered, and an unknown `/api/v2` path returned an
HTML 404. Both are now defaults — `V2_PARSE_DEFAULTS` on the builders and the two
raw routes, and a catch-all whose body is byte-identical to the rollout gate's so
an unknown path stays indistinguishable from an ungated one.
Consolidates the keyset paging block (`resumeKeyset`/`keysetPage` in
`list-query.ts`) that had been open-coded in six modules, and folds the bespoke
`InvalidWorkflowListCursorError` into the `OrchestrationError` every other list
already used.
Prevention: the contract sweep in `list-pagination.test.ts` now also asserts that
every paged list rejects a fractional `limit`, that every list query is
`.strict()`, and that the three clamping lists still truncate. The fractional-
limit assertion is what caught `/audit-logs`. Documented in
`.agents/skills/v2-api-conventions/SKILL.md`.
405 responses still carry no `Allow` header — Next.js generates those before any
handler runs. Recorded as a known gap.
* fix(v2): bind the offset cursor to the query state it counts positions in
An offset names a position in one exact sequence. `GET /skills` accepted a bare
`{offset}` cursor and applied it to whatever sequence the next request asked
for, so following `nextCursor` with a different `search`, `sortBy` or
`sortOrder` silently skipped rows, repeated them, or landed past the end and
returned an empty page while the cursor implied more.
Fixed in the codec rather than the route so the sibling could not keep the gap:
`decodeOffsetCursor` now takes a scope stamp and rejects a cursor minted under a
different one, which is what `decodeSortedCursor` has always done for keysets.
`offsetCursorScope()` builds the stamp from every param that filters or orders
the sequence; `limit` is excluded because it selects how much of the sequence to
return, not what the sequence is, so paging with a different page size still
works.
`GET /knowledge/{id}/documents` had the identical latent gap and gets the same
treatment — the compiler surfaced it as soon as the signature changed.
|
||
|
|
7c05e36049 |
fix(api): close five defects found auditing the v2 migration against main (#6575)
* fix(tables): stop a column retype from nulling empty-string cells A type conversion rewrote every cell holding '' to null. Main only nulled a blank the target type could not read; '' is a real stored value that both string and json columns accept, so string->json and json->string silently destroyed those cells. Worse on a required target: countEmptyCells matches only a missing key, SQL NULL, or '[]', so '' passes the required guard and the rewrite then wrote null behind a constraint that had just succeeded. The per-cell decision is now the pure retypeCellRewrite, restoring main's rule: null a blank only when the target cannot read it, otherwise coerce. * fix(execution): release the concurrency slot when a group cancel is refused The stop-the-work effects (durable Redis abort record, queue-job cancel, in-process abort) all fire before the workflow-group sidecar is consulted, and none can be undone. When the sidecar refuses the claim we throw a conflict, which skipped releaseExecutionSlot and stranded the plan concurrency reservation until it expired. Every conflict return is a terminal-or-absent state - a missing log row, a log already completed or errored, or a terminal cell - so a refusal never means the run is still executing. The slot is released before the throw, keeping the exact success && !isPausedCancellationPath predicate rather than a blanket finally that would free reservations for live runs. * fix(uploads): recover an ambiguous PUT instead of discarding the object Main recovered an upload whose bytes committed but whose response was lost, via a verify endpoint. The session client retries the PUT instead, but every provider now signs a create-only precondition, so the retry returns 409/412, is classified non-retryable, and the session aborts - deleting the object that had already landed. A transient blip on the final ack cost the whole upload. A conflict on a retry attempt is now treated as our own earlier PUT having committed, and completion proceeds. That is safe because completeUploadSession independently verifies the object through assertObjectIdentity, which rejects on uploadId mismatch before anything durable is registered. A first-attempt conflict still fails loudly. * fix(folders): enforce the workspace folder ceiling on the create path Readers bound the active path index at MAX_FOLDERS_PER_WORKSPACE and throw once a workspace exceeds it, but POST /api/folders reached createFolder, which has no maxFolderRows field and never counts. A workspace could therefore be driven past the ceiling, after which the 27 capped read sites failed on a state the product had allowed. createFolder now asserts room inside its transaction, right after the mutation lock, so the count cannot be raced. The refusal is a typed conflict rendering 409 with an actionable message rather than a 500. The check counts rows directly instead of loading the path index, so an already-over-cap workspace gets a clean refusal rather than a read error, and no reader gained a cap. folderMutationStatus also gained the payload_too_large mapping it was missing, which had been rendering a delete-cascade cap breach as an unexplained 500. * fix(skills): route internal skill writes through the shared use cases The internal route made the workspace authorization decision itself, never consulting the skills operation policy, never loading canonical workspace context, and recording an audit entry with no operation id or actor projection. v2 and Copilot already went through the use cases; only this surface did not. GET/POST/DELETE now authenticate, parse, call the shared use case, and present. Request and response shapes are unchanged. Two behavior changes fall out: a write against a deleted workspace is now refused with 404 rather than accepted, and permission-denial text matches the rest of the platform. Legacy internal-JWT auth is dropped because no principal kind expresses that caller and nothing calls it: the whole repo references /api/skills only in two comments, no tool declares an internalRoute to it, and the executor reads skills through a direct listSkills call rather than over HTTP. * fix(folders): enforce the workspace ceiling on the remaining create paths Folder duplication, admin workspace import, and workspace forking all inserted folders without consulting the ceiling that 27 read sites enforce, so any of them could leave a workspace whose reads then fail. Each now asserts room for the rows it is about to add rather than one at a time: duplication measures the whole subtree up front, forking counts its bulk insert, and import counts per segment because that is genuinely one row. assertFolderCollectionHasRoom gained an additionalRows notion for the bulk case, and short-circuits when nothing is being added so an over-cap workspace still reads and still syncs. Duplication deliberately does not take the folder mutation lock. Holding it across the copy would block folder creation workspace-wide for an unbounded time - there is no cap on workflows per subtree and duplicateWorkflow runs sequentially - and narrowing it is impossible because an advisory transaction lock cannot be released early; splitting the transaction would leave a half-copied tree on failure. A rare few-row overshoot near the ceiling is the better trade, and it matches what forking already does. A test asserts the lock is absent so re-adding it is a visible decision. Admin import gained the transaction and lock it never had. Its folder-full refusal escapes the per-workflow result list, because a full tree is a property of the workspace and would otherwise be buried as N failures behind a 200. The fork and promote routes had no catch at all, and withRouteHandler only classifies HttpError, so a refusal rendered as an opaque 500 - twice over, since drizzle wraps the throw. Both now project a classified conflict as 409 and rethrow anything unclassified. * fix(uploads): bound the signed PUT lifetime and advertise its real expiry A single-PUT transfer was signed for the whole 24h upload-session TTL, because expiresAt was reused as both the session lifetime and the signing lifetime. Multipart part URLs in the same file kept 1h, and the pre-migration presigned route signed every PUT for 1h, so the widening was unintended rather than a policy change. No provider clamps below 24h. The PUT presign is now clamped at the provider boundary by a shared UPLOAD_URL_TTL_MS, which the part-URL path also uses so the two cannot drift. An expired PUT URL is deliberately not recoverable: unlike multipart, which re-signs per part call because its progress is durable, a PUT is not resumable, so an expired URL and an interrupted PUT have identical recovery. Nothing leaks, since every provider signs a create-only precondition. Clamping alone would have made the contract lie: the URL would die an hour before the session's advertised expiresAt, with nothing telling an integrator why the 403 happened. The PUT transfer now carries its own expiresAt, mirroring the multipart part-URL field. It is provider-dependent on purpose - cloud transfers report the clamped signature expiry, while the local data plane has no signature and admits against the session, so reporting an hour there would have been a new inaccuracy in the other direction. * chore: delete the dead presigned-upload and skill-adapter paths The presigned upload routes and the internal skills adapters were both replaced during the v2 migration, leaving their implementations behind with no callers. Removed generatePresignedUploadUrl and verifyPresignedUploadReceipt with their three provider helpers, QUOTA_EXEMPT_STORAGE_CONTEXTS and the types it orphaned, and the performCreateSkill/performUpdateSkill/performDeleteSkill adapters with recordSkillEvent and statusForSkillOrchestrationError. Each was verified unreachable across apps, packages, scripts and ee, including barrel re-exports and string access, not just direct imports. recordSkillEvent needed the closest look, since deleting an audit writer can silently drop coverage. The use cases declare the same action, resource, and description, and the framework adds the operation and actor the old helper lacked; recordAudit back-fills actorName and actorEmail from the user table when both are omitted, so the one field the helper passed is not lost. The self-hosting architecture doc described a directUploadSupported flag on an endpoint that no longer exists, and now describes the upload-session flow that replaced it. * refactor(folders): keep the cheap resource facts out of the schema graph Reading a folder resource type's label or its lock support meant importing folderResourceConfig, which imports the db schema for every table it serves and from there reaches lib/table/service, the executor, and the tool registry. That mattered as soon as lib/folders/queries needed a label: queries is reached from workspace-file-manager, which is reached from the files and chat pages, so one import edge put roughly 4,700 modules into those page graphs and broke the tool-registry boundary audit. Labels and lock support now live in a leaf module that imports only a type, and config composes them so there is still one source of truth. The three folder routes that pulled the whole config in for a single boolean read the leaf instead. * fix(skills): apply an upsert batch in one transaction The internal skills route looped the batch, calling an independently committing use case per item. A rejection on a later item left the earlier ones written and audited while the request reported failure - the compound-mutation rule in CLAUDE.md exists for exactly this. No new transaction plumbing was needed: upsertSkills already wraps its whole item loop in one db.transaction, so the partial commit came from calling it N times rather than once. upsertSkillBatch now validates and per-skill authorizes every item before issuing a single write, and createSkill and updateSkill became thin wrappers over it so v2 and Copilot keep one authority for the rules. The compound operation declares the read floor that skills.update already used, and the use case additionally authorizes skills.create when any item lacks an id, still ahead of every write. A read-only member who is a skill editor keeps their edit, and creates are not authorized more loosely than before. Audit projects one entry per committed skill, and analytics moved after the commit so nothing is reported for a rolled-back item. Note metadata.operation for these writes is now skills.upsert rather than skills.create/update; the action field still carries the distinction. * fix(security): close two disclosure gaps and finish the slot-leak fix The payer-pool gate only covered the workspace branch. A personal API key that omits workspaceId takes the account branch, where getHighestPrioritySubscription resolves an organization subscription from any member row regardless of role - so a plain member read the organization-wide credit and storage pool by dropping one query parameter. The account branch is now gated by the same authority, and the storage pool is not queried when it may not be disclosed. Forcing that branch self-scoped instead would have downgraded plan, period, and status, which is what a member needs to see whether the org is blocked. GET /api/v1/logs/executions/[executionId] emitted the workflow snapshot raw, carrying password sub-block values and oauth-input credential ids. It now shares the sanitizer the v2 read already used, extracted so there is one implementation rather than two. Env-var references are still preserved. cancelWorkflowGroupExecution itself was unguarded, so an unexpected throw from its transaction escaped ahead of every release site - the same reservation leak this branch set out to close, still open on the adjacent path. It now releases through the shared predicate and rethrows, because a failed transition means the cell state is unknown and a success-shaped answer would be a lie. The comment claiming the abort record cannot be taken back was false and now states the real reason: a refusal is always a terminal-or-absent state. * fix(v2-api): cover every persisted run status and every capped body The workflow-runs endpoints carried the same omission the logs contract had: the execution logger persists redacting, the run schemas did not list it, and because validation is whole-response one such row returned 500 for an entire page. Both schemas now derive from PersistedWorkflowExecutionStatus behind the same AssertNever gate, so a future status is a type error rather than a production 500. The single-run read keeps its extra queued value, which only it can observe. That schema was also serving as the run-list status filter. Widening it would have accepted a filter value the application input cannot express, so the reported set and the accepted filter are now separate schemas. Routes declaring maxBodyBytes without payloadTooLargeResponse fell back to a bare string with no error code and no private cache header. Rather than patch the four, the default moved into the builders - all three had the hole - which covers 58 body-bearing handlers, and a route override still wins. The five per-route overrides that merely restated the default are gone. Also documents the 413 on the one knowledge route that has a real body cap, adds the rollout gate's 404 to the last v2 operation missing it, and rewords the nextCursor description, which read as though every list were a full-set list. * fix(api): make the shared traits and lifetimes single-sourced The folder resource-traits leaf composed labels into config but restated lock support independently, so the routes reading the trait and the orchestration reading the config could disagree about which resources lock. Config now composes both, and supportsLocking is required rather than optional so a new resource type cannot silently omit it. The upload commit claimed the PUT clamp and the multipart part URLs shared a constant and could not drift. That was true only of the advertised expiry - the three provider signers each hardcoded an hour, so changing the constant would have moved what we advertise while leaving what we sign, recreating exactly the mismatch the clamp removed. Each provider now receives the lifetime in its own unit from the one constant. Table restore hand-rolled its status map and returned the driver message verbatim at 500, leaking the failed statement and its bound parameters - the same defect this branch closed at nine other sites. It and import-csv now use the shared projection; import-csv's result type also had to carry the lock the classifier already set, so a 423 can name it. Deletes v2RowWriteError, which had no callers and would have rendered a locked table as 400 by discarding the 423 it was handed. |
||
|
|
9b9f4ee596 |
fix(v2-api): close three secret disclosures, make the surface consistent, and align docs with signatures (#6560)
* fix(v2-api): close two secret disclosures and align docs with signatures
Two P0 disclosures, five correctness bugs, and the standardization and
guard work that came out of auditing them.
**Secret disclosure — workflow version state.** `GET /api/v2/workflows/{id}/
versions/{version}` served the deployed graph unsanitized, so a read-role
workspace API key received plaintext block-password values and OAuth
credential ids. The sibling export route has always sanitized. Every other v2
response is protected structurally because the builder re-parses it, but this
field is `z.custom<WorkflowState>()` — a predicate that validates nothing —
which is why it survived earlier audits. Sanitization now lives in the use
case, secure by default, with a named `includeCredentialValues` opt-in that
only the session-authed deploy-preview route sets.
**Secret disclosure — MCP headers.** The internal list and update routes
returned custom `Authorization` headers verbatim to any read-role member;
headers are stored unencrypted. Values are now gated on write permission and
projected through one shared helper. The settings UI genuinely prefills from
them, so blanking outright would wipe headers on unrelated edits — write-only
headers plus encryption at rest are the follow-up.
Correctness:
- v2 execute ignored `X-Sim-Via`, resetting the call chain on every hop and
defeating the recursion guard. Wired on both the keyed and anonymous paths.
- v2 knowledge search accepted `searchMode` and dropped it, silently serving
vector-only results for a hybrid request, and allowed 50MB bodies where
internal caps at 2MiB.
- v2 run cancel never released the plan concurrency slot and half-cancelled
group runs; a group conflict now returns 409 instead of reporting success.
- v2 table row writes stamped no secret provenance, so the next internal read
reported the whole page incomplete. `secretProvenance` is now required on
the primitives, making the next omission a compile error.
- Folder conflicts and malformed paths returned 500; they are 409/404/400 now.
`FolderPathError` splits from `FolderHierarchyError` so a corrupt stored
tree stays a 500 and stays in 5xx alerting.
Standardization and documentation:
- `PUT /files/{id}/share` -> PATCH. The resource is not round-trippable
(`hasPassword`, never the password), so merge-on-omission is the only
implementable semantics.
- ~40 spec truthfulness fixes: a 410 the API cannot emit, eight 423s with no
lock guard, ~30 reachable-but-undocumented 404/400/413s, and six inverted
field claims. Eleven operations that always reject a workspace key now say
so — four of them answer 404, so a workspace key was told the resource did
not exist.
- `NAME_PATTERN` lost its `/i` through `z.toJSONSchema`, publishing 15
patterns that reject names the runtime accepts. Every generated client
rejected any capitalized table or column name, and two of the spec's own
examples failed the spec's own schema.
Guards, so these classes cannot recur:
- `check:route-verbs` (new) cross-checks all 212 builder routes' exported verb
and path against their contract. The builders only compare at runtime, so a
half-done rename previously passed CI and 500'd in production.
- Example validation now runs against the published JSON Schema with formats
on, covering 225 nodes instead of 100 — this is what caught the regex bug.
- The list-pagination sweep is union-aware and fails loudly on a schema it
cannot introspect, rather than counting it compliant.
* refactor(v2-api)!: flatten the single-resource response envelope
BREAKING: 31 endpoints that returned `{ data: { <resource>: T } }` now return
`{ data: T }`.
This corrects drift, not a design decision. PR #5273 added skills, custom
tools, MCP servers, secrets, and knowledge nested while adding workflows,
files, and logs flat — and in the same commit wrote the `v2/shared.ts`
docblock declaring `single resource: { data: T }` is the standard. The nested
half appears to have been modelled on the v2 tables surface (#6067), which
landed twelve days earlier. Lists were already `{ data: T[], nextCursor }`, so
flat single-resource is what actually matches them; nesting made every client
destructure a layer that carries nothing.
Doing it now because the cost only grows: `v2-api` is still dark-launched, so
today this breaks no one. After GA it needs a deprecation window.
Payloads that carry real information were deliberately left alone — this was a
classification exercise, not a mechanical sweep. Unchanged: delete
acknowledgements (`{ id, deleted }`, `{ path, deleted, deletedItems }`), the
knowledge search envelope (which echoes query, knowledgeBaseIds, topK and
totalResults alongside hits), upload payloads carrying signed tokens and
transfer instructions, bulk-operation counts, `{ row, operation }` upserts,
named acknowledgement scalars (`{ dispatchId }`, `{ cancelled }`), and
`{ columns: [...] }` — a collection, where a bare `{ data: T[] }` would be
indistinguishable from the list envelope but without `nextCursor`.
Also flattened the two file-share responses, which were not in the original
survey: leaving them would have put one resource in two shapes on one path.
`GET /files/{id}/share` now returns `{ "data": null }` when a file has never
been shared.
No consumer is affected. Both SDKs touch exactly two v2 endpoints — execute
and run status — and both were already flat. No docs MDX, client hook, or
internal caller reads a changed response; Copilot table tools call the
application use cases directly rather than the HTTP surface.
The shared `v2FolderSchema` is untouched: every folder flatten was achievable
at the response site, which is itself evidence flat was the intended shape.
* fix(v2-api): close a third secret disclosure and make concealment coherent
**Secret disclosure — run snapshot.** `GET /api/v2/logs/{runId}` returned
`workflowState` straight from `workflowExecutionSnapshots.stateData`, which is
the workflow graph: `blocks[].subBlocks[].value` holds `password: true` field
values and `oauth-input` credential ids. Nothing on that path sanitized it, and
the field was typed `z.unknown()`, so the builder's response parse stripped
nothing. A read-role workspace API key could read plaintext credentials.
This is the third instance of one pattern, and the pattern is the finding: the
builder protects every response by re-parsing it, so the only fields that can
leak are the ones typed `z.unknown()` or `z.custom()`. Both prior disclosures
sat behind exactly such a field. The snapshot is now sanitized in the use case
and the field is typed object-or-null. An inventory of every remaining
`z.unknown()` in the v2 contracts is in the PR description; two carry data with
no projection behind them and are named there as follow-ups.
**Concealment was bypassable.** `createV2ResourceConcealmentPolicy` rewrites
resource-authorization failures to 404 so a caller cannot probe for existence.
Workflows and files applied it on every verb; tables and knowledge applied it
only on reads. A caller could therefore probe with PATCH, read the 403, and
learn the resource exists — the read-side concealment bought nothing. Nine
mutation sites now conceal, plus the three table-column verbs, which were
inconsistent with their own sibling sub-resources.
`lib/logs/api/route-policies.ts` was a second, divergent implementation that
sniffed `response.status === 403` and so also swallowed workspace-policy
denials the canonical helper deliberately preserves. It now uses the helper. A
third such sniff survives in the upload-control helper and is noted as a
follow-up.
Also:
- `DELETE /tables/{tableId}/rows/{rowId}` returned the bulk `{deletedCount,
deletedRowIds}` shape while nine sibling single-resource deletes return
`{id, deleted}`. It now matches them.
- Nine operations can 404 on an unknown folder path and did not document it;
`createWorkflow` could 413 on an oversized folder tree and did not; getting a
run can 409 when trace data was truncated and did not.
- `queryTableRows` documented a 413 it cannot emit and `resumeWorkflowRun` a
423 with no lock guard anywhere in its path — the same un-producible-status
class already cleared for 410 elsewhere.
- Execute's 409 description covered only the run-id case after the
recursion-guard fix added a second cause, and named a code the route does not
emit: the wire carries `error.code: CONFLICT` with the specific cause in
`error.details.code`. `x-sim-via` is now a declared request header.
- Deploy and rollback published examples that were impossible: `isDeployed:
true` beside `activeDeployment: null`, where the route computes the former
from the latter.
- `afterRowId`/`beforeRowId` were published on row insert and silently dropped
by the route, so a positional insert became a tail append.
- A generated document whose script fails permanently answered "still being
generated, try again" forever; the underlying cause is now preserved.
* docs(v2-api): correct eleven false or misleading spec claims
Structural parity between contracts and specs is CI-enforced; semantic truth is
not. These are claims the spec made that the code does not honour.
Outright false:
- `DELETE /files/{fileId}` said it deletes "the stored bytes". It archives:
the row is retained with a deletion timestamp and the bytes are never
removed. Restore exists, but only on the internal API, so the description now
says so rather than implying v2 offers it.
- Execute documented `409 EXECUTION_ID_CONFLICT` in three places. The wire
carries `error.code: CONFLICT` with `error.details.code: RUN_ID_CONFLICT`;
only v1 ever emitted the documented string.
- The files spec claimed every endpoint uses the canonical envelopes while
`GET /files/{fileId}` returns octet-stream.
- The shared timestamp rule justified itself with a rendering claim that is
false — 29 bare-form sites publish `format: date-time` identically. The real
difference is runtime validation, so the rule now says that. It was softened
rather than enforced: responses are re-parsed, so adding `.datetime()` to a
field whose producer can emit a non-ISO string turns a working read into a
500, and that could not be proven for all 29 without a much larger audit.
Misleading:
- The billing ledger silently defaults to a 30-day window, so a client
paginating to `nextCursor: null` believes it has the whole ledger.
- Deleting a connector-backed knowledge document does not delete its chunks —
the row survives as excluded and the embeddings remain.
- `listTables` said "all tables"; it is keyset-paged with a default limit.
- `GET /files/{id}/share` omitted the `data: null` never-shared case its own
schema and example already declare.
- The share PATCH matrix omitted two hard 400s, so following it literally
against a never-shared file fails.
- Five knowledge operations render a canonical folder path back and can 413 on
an oversized tree without carrying the sentence that says so.
Also: the upload-control helper was a third implementation of concealment by
sniffing `response.status === 403`, which masks workspace-policy denials the
canonical helper deliberately preserves. It now uses the shared policy, so
those denials keep their 403. And the shared docblock's search-field
enumeration was presented as exhaustive while omitting two lists, and its
error-envelope claim omitted the two upload data-plane routes that emit a bare
`{error: string}` — both now carry the carve-out the CI allowlist already had.
* test(v2-api): align upload concealment test with cross-tenant-only semantics
#6557 narrowed `createV2ResourceConcealmentPolicy` to conceal only the three
cross-tenant authorization classes, deliberately letting a same-workspace
policy denial keep its 403 so the caller learns why. My test predated that and
asserted a workspace-key denial was concealed as 404.
Split into two cases that pin the distinction rather than paper over it: a
cross-tenant reach conceals, a workspace-key policy denial does not.
* fix(v2-api): accept the redacting log status and envelope the knowledge-search 413
The v2 log presenters parsed status against a five-value enum, but the
execution logger persists a sixth, redacting, while a finished run's output
is scrubbed. Any such row failed the response parse; on the list route one
row 500'd the whole page. The enum is now derived from
PersistedWorkflowExecutionStatus with a compile-time exhaustiveness
assertion, so a future status is a type error rather than a production 500.
POST /api/v2/knowledge/search declared maxBodyBytes without
payloadTooLargeResponse, so its 413 returned a bare string instead of the v2
error envelope. It now matches the sibling deploy/rollback routes.
* fix(uploads): restore archive extraction folder parity
Archive extraction into workspace files/ was rewritten onto the authorized
application-operation boundary, and three behavioral regressions came with
that move. Together they broke every archive containing a subdirectory, and
100% of copilot extract() calls (materialize-file always passes
rootFolderSegments: [baseName], and its catch only handles ArchiveError).
1. Non-canonical folder path. The extractor joined the folder segments with
"/" and passed the result as `path` to createWorkspaceFileFolderOperation.
That path reaches requireNonRootFolderPath -> parseFolderPath, which
requires a leading "/" and byte-for-byte canonical per-segment encoding,
so "bundle/data" threw FolderPathError before anything was written — and
a folder name containing a space or a reserved character would still have
thrown after merely prefixing a slash.
2. exactName: true. createWorkspaceFileFromBuffer was told to demand the
exact leaf name, which sets maxAttempts = 1 and raises FileConflictError
when the name already exists. The extractor's rollback then deleted every
file written so far, so one colliding name destroyed the whole
extraction. Reachable today for flat archives through the unzip action of
POST /api/tools/file/manage. Restored to auto-suffixing via
allocateUniqueWorkspaceFileName.
3. Wrong folder primitive. createWorkspaceFileFolderAtPath creates exactly
one leaf, conflicts on an existing path, and requires the parent to exist
already. The extractor never creates intermediates and caches by full
path, so the first nested entry asked for a folder whose parent was never
created. The correct semantics are ensureWorkspaceFileFolderPath: walk
every segment, reuse what exists, create only what is missing.
Rather than bypass the operation boundary by calling the manager primitive
directly, this adds ensureWorkspaceFileFolderPathOperation — an authorized
application use case under files.folders.create that expresses "ensure this
whole chain exists" — and routes the extractor through it with raw decoded
segments, so no path string is built and no encoding can be malformed.
archive.test.ts previously mocked the folder operation and asserted the
broken shape (path: 'bundle'), which is why this shipped. The suite now
fakes the workspace-file store in memory while enforcing the real rules:
folder paths run through the production parseFolderPath family, the
create-one-leaf operation conflicts and requires a parent, and exactName
governs conflict vs auto-suffix. Nested, reuse, encoded-name, and collision
cases are covered and each fails against the pre-fix code.
* chore(files): tidy archive extraction cleanup
* fix(uploads): roll back folders archive extraction created
Extraction now materializes folders before uploading files, but the failure
path only deleted the extracted files — every folder the call created was left
behind. That is not cosmetic: `materialize_file` guards re-extraction by looking
up the root folder path and refusing when it has any child, so a half-extracted
nested archive turned every retry into "already extracted — delete that folder
first" until a human cleaned up the tree by hand.
The rollback must delete only folders this call actually inserted, never one it
reused: extracting into an existing path is normal (a sibling entry, an earlier
successful extraction), and deleting a pre-existing folder would destroy
unrelated user data. `ensureWorkspaceFileFolderPath` already distinguishes the
two while walking the segment chain, so it (and its application operation) now
reports `createdFolderIds` alongside the leaf id. The extractor accumulates
those ids in creation order and, on failure, deletes them in reverse — parents
are recorded before their children, so reverse order is deepest-first and a
parent is never removed out from under a child. Folder cleanup is best-effort
like the existing file cleanup, so a cleanup failure never masks the original
error.
* fix(billing): withhold the payer credit pool from v2 status readers
`GET /api/v2/billing/status` resolved the workspace's payer and projected
that payer's pooled allowances — credits used, credit limit, credits
remaining, and the payer entity's storage usage and quota — to any caller
holding only `read` on the workspace, including a personal API key. The
payer pool is shared across every workspace that payer funds, and the
platform already treats it as privileged: the workspace credit-availability
surface computes `canViewPayerPool` from `canManageWorkspaceBilling` and
substitutes member-scoped or null figures for everyone else. The new
versioned endpoint had no equivalent gate.
`credits` and `storage` are now projected only to a caller who may manage
the resolved payer's billing: the billed account holder of a personally
hosted workspace, an admin of the hosting organization, or a workspace API
key, which only a workspace admin can provision. The endpoint stays at
`read` so a plain member keeps the plan, period, and standing the workspace
UI already shows them, and an exceeded pooled limit still reports as
`limit_exceeded` without disclosing the numbers behind it. Both fields are
nullable on the wire and in the regenerated OpenAPI spec.
The decision lives in the application use case, resolved from canonical
workspace state, not in the route: billing authority is payer identity and
organization role, which the workspace permission ladder cannot express —
a plain workspace `admin` is deliberately not enough.
* chore(api): remove the unused public API route builder and dead endpoint labels
`withPublicApiRouteHandler` and 27 `ApiEndpoint` union members landed together
in #5273, but the v2 surface shipped on `defineV2JsonRoute` + `v2RateLimits`
instead. The builder had no production caller — only its own test — and the v2
rate limiter never reads an `ApiEndpoint` label, so those members were never
emitted to telemetry by symbol or by string literal.
Remaining members are exactly the labels a v1 route passes to `checkRateLimit`
or `authenticateRequest`. Drops the now-unreachable `hasZodUsage` branch from
the API validation audit; no ratchet metric moves (route total stays 1093).
* fix(billing): deny the payer pool to actor-less workspace API keys
The first pass gated `credits` and `storage` on billing authority for
personal API keys but let a `workspace_api_key` principal through
unconditionally, which left the excluded role a way back in. Any workspace
`admin` may mint a workspace API key, and a workspace `admin` is
deliberately not a billing manager, so an admin who reads `null` as
themselves could mint a key and read the full pool with it. On an
organization-hosted workspace that pool is the organization's, spanning
workspaces the admin has no standing in.
Billing authority is payer identity or an organization admin role — a
property of a person. A workspace API key is deliberately actor-less, so it
can never satisfy it and now reads both fields as `null`. Attributing the
key to its creator was rejected: it would launder the same workspace-admin
role, it breaks when the creator's authority is revoked while the key lives
on, and substituting a key's owner for the acting principal is what the
application operation boundary forbids. The reasoning sits in TSDoc at the
decision point.
The key keeps the plan, period, and standing it needs to monitor a
workspace, including `limit_exceeded` and `billing_blocked`. No in-repo
caller reads `credits` or `storage` from this endpoint. The payer storage
pool is now read only once disclosure is authorized, so a caller who may
not see it no longer triggers the query at all.
* fix(folders): bound the workflow folderId-branch path index reads
`createWorkflow` and `updateWorkflow` each resolve a folder two ways inside one
function. The folderPath branch goes through `resolveWorkflowFolderPath`, which
loads the path index with `maxRows: MAX_FOLDERS_PER_WORKSPACE`; the folderId
branch loaded it with no bound at all, issuing a `SELECT` over every active
folder row in the workspace. In `updateWorkflow` the unbounded read and the
bounded fallback sit thirty lines apart in the same function.
Passes the cap at both sites, matching the read sites that already opt in.
Exceeding it throws `FolderCollectionLimitExceededError` rather than truncating,
because a partial path index resolves real folder paths to `undefined` and
re-roots resources at the workspace root.
`maxRows` deliberately stays opt-in rather than becoming the default. Folder
creation does not refuse at the same ceiling on every path — `POST /api/folders`
goes through the `createFolder` name/parentId variant, which passes no
`maxFolderRows`, so the count guard in `executeCreateFolderAtPath` never runs
and a workspace can already hold more than `MAX_FOLDERS_PER_WORKSPACE` folders.
Defaulting the bound would make every path-index consumer throw for a state the
product allows to exist. Reconciling reader and writer is a separate change with
a user-facing limit, not a chore.
* chore(billing): tidy payer-pool concealment cleanup
* fix(api): reject an undecodable offset cursor on v2 table rows
GET /api/v2/tables/{tableId}/rows coerced an undecodable pagination cursor to
offset 0 and re-served page one. A client paging forward reads that as a fresh
first page and can loop over it forever. Every sibling v2 cursor list — logs,
files, workflows, workflow runs, workflow versions, workspace members, tables,
knowledge documents — already rejects with a validation error instead.
Extracts the offset-cursor decode both offset-paginated v2 routes had inlined
into `decodeOffsetCursor`, next to the existing `decodeSortedCursor`, so the
reject-don't-restart rule has one home.
* fix(api): restore v1 table error-response parity and stop internal message leak
The v1 table routes were rewritten to consume `lib/table/orchestration`
results, and two response behaviors drifted from what the live API returned.
Information disclosure: an unclassified failure's `outcome.error` carries
whatever text the fault happened to have. Drizzle wraps a throw raised inside
a transaction in an error whose own message is the failed statement and its
bound parameters, so `DELETE /api/v1/tables/{tableId}` and
`DELETE /api/v1/tables/{tableId}/rows/{rowId}` returned that verbatim in the
500 body to any API-key holder. Previously these returned a fixed generic
string.
Lost `lock` field: the 423 body used to be `{ error, lock }`. The delete,
row-delete, and column-update routes (v1 and internal) dropped the lock kind
the orchestration result already computes, leaving clients unable to tell
which lock to clear.
Both are fixed at one altitude: `orchestrationOutcomeErrorResponse` in
`app/api/table/utils.ts` is now the only way a table route projects an
orchestration failure onto the wire. It renders the route's fallback for an
unclassified failure and the real message for a classified one (validation,
not-found, conflict, locked keep their specific text), and carries `lock` on a
423. A future route cannot reintroduce either bug by hand-spelling the body.
Duplicate table names on `POST /api/v1/tables` keep answering 409 rather than
reverting to the previous 400. 409 is the correct semantic, and every other v1
duplicate-name surface (knowledge, files, workflow import) already answers 409;
the tables 400 was the outlier. v1 tables appears in no published OpenAPI
document and no in-repo client branches on the status, so the compatibility
cost is limited to a caller matching 400 specifically for a name collision.
* fix(skills): only reject a built-in name collision on an actual rename
The built-in-name guard ran on every update that carried a `name`, without
comparing it to the skill's current persisted name. Skills created before the
guard existed can legitimately carry a built-in's name (they simply shadowed
the built-in at read time), and the skill modal always submits the full object
including the unchanged name — so every save of such a skill returned 400 with
"The skill name ... is reserved by a built-in skill", with no way to fix it
short of renaming.
Move the guard in `updateSkill` to after the canonical row is loaded and run it
only when the submitted name differs from the current one. Creating a skill
with a built-in name, and renaming an existing skill into one, are still
rejected. The check stays in the shared orchestration primitive because that is
the only layer both the internal `/api/skills` adapter (via `performUpdateSkill`)
and `updateSkillUseCase` (v2 + Copilot) pass through, and it is where the
current name is in hand.
* chore(tables): tidy v1 error projection cleanup
* chore(skills): tidy collision guard cleanup
|
||
|
|
6fdb1459c4 |
fix(v2-api): standardization (#6542)
* fix(v2-api): stop leaking resolved secrets in logs and serving doc source Two regressions shipped with the v2 API (#5273) where v2 diverged from the v1 path it replaced, plus the hardening that fell out of auditing them. **v2 logs bypassed secret redaction.** `getPublicLog` and `listPublicLogs` called raw `materializeExecutionData`, while every other reader — v1 list and detail, CSV export, `fetch-log-detail`, both data-drain sources — calls `materializeExecutionDataForDisplay`, which applies the resolved-secret provenance projection. Both v2 routes then serialize `traceSpans` and `finalOutput` straight onto the wire, so unredacted secrets could reach the public API. Swapped to the display projection and threaded the principal's subject user into the read context. **v2 file download served generation source.** `GET /api/v2/files/{fileId}` streamed `file.key` raw. AI-generated docs store their generation source as the primary file, so a raw download yields source text under a `.pdf` name — a file the recipient cannot open. Generated docs now resolve to their compiled artifact; ordinary uploads still stream and are never materialized, gated on the recorded generation-source type rather than the extension. The resolve is capped at MAX_RENDERED_DOCUMENT_BYTES, and a still-compiling artifact returns a retryable 409 rather than a 500. Also in this change: - Reconcile the two v2 verbs that used PUT for PATCH semantics: `PUT /v2/knowledge/{id}` and `PUT /v2/tables/{tableId}/rows` are both all-optional partial updates. Breaking for API-key clients, but the surface is dark-launched behind the `v2-api` gate and no in-repo caller issues PUT. - Close the OpenAPI coverage blind spot that hid two routes: contract discovery was a non-recursive read of the flat `contracts/v2/` directory, so a contract in a subdirectory — or beside its non-v2 siblings, which is where the uploads contracts live — escaped the gate. The sweep is now recursive over the whole contracts tree, and the two upload data-plane routes are named in an explicit allowlist with reasons and staleness guards. - Extract `needsRenderedArtifact` so the "recorded type is authoritative, extension is fallback" rule has one home instead of being duplicated. - Extract `DocCompileUserError` into a leaf module so recognizing it no longer drags `app/api/**` and `next/server` into application modules. - Correct the stale pagination docstring in `contracts/v2/shared.ts` and pin the paged/full-set split in a test so it cannot drift again. * fix(v2-api): absolute imports for the extracted doc-compile error Review follow-up. - Use the `@/lib/...` alias for `doc-compile-error` in the three modules that imported it relatively. The repo requires absolute imports, and having all four consumers share one specifier also removes any chance of two module instances resolving apart and breaking `instanceof`. - Memoize the v2 list-pagination sweep. It re-imported the whole contracts tree once per test and timed out against the default 10s limit under load; it now sweeps once and declares an explicit timeout. Its failure message also still pointed at an enumeration in `v2/shared.ts` that this branch replaced with a pointer to the test itself. * fix(v2-api): correct three inaccurate claims found in verification None of these change behavior; each is a comment or test-config assertion that was not true as written. - The artifact resolver's TSDoc implied the byte cap prevents an oversized artifact being materialized. It does not: the artifact-store fetch is not streaming-bounded, so the bytes are resident before the ceiling rejects them. Say what it actually guarantees. - `v2/shared.ts` pointed at per-contract documentation for the two lists that still filter in memory. Neither contract documents it, so name the two lists and what they do inline instead of pointing at a page that does not exist. - The knowledge update contract said "every field of the body is optional"; `workspaceId` is required. Narrow the claim to mutable fields. - Scope the pagination sweep's extended timeout to the one test that pays for it, so a genuine hang in the other two surfaces in 10s rather than 60s. |
||
|
|
263e3ca67e |
improvement(external-endpoints): v2 versions with clean signatures + updated docs based on openapi spec (#5273)
* v0.6.29: login improvements, posthog telemetry (#4026) * feat(posthog): Add tracking on mothership abort (#4023) Co-authored-by: Theodore Li <theo@sim.ai> * fix(login): fix captcha headers for manual login (#4025) * fix(signup): fix turnstile key loading * fix(login): fix captcha header passing * Catch user already exists, remove login form captcha * improvement(external-endpoints): v2 versions with clean signatures + updated docs * feat(usage): accept X-API-Key on usage-logs list + export /api/users/me/usage-logs and /export now use checkHybridAuth — the same auth /api/users/me/usage-limits already accepts — so external monitors can read summary.bySourceCredits (the source breakdown of usage-limits' aggregate currentPeriodCost) instead of estimating Copilot spend by subtraction. Workspace-scoped keys are pinned to their own workspace's slice of the ledger: the filter defaults to the key's workspace and an explicit mismatch 403s. Both endpoints documented in openapi-core.json. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(billing): dedicated v2 usage endpoints; keep internal usage routes session-only Replaces the earlier X-API-Key enablement on /api/users/me/usage-logs with a dedicated public surface, so the internal Billing-settings endpoints can evolve with the UI while external monitors get a stable versioned contract: - GET /api/v2/billing/usage — current-billing-period summary with bySourceCredits (the source breakdown external monitors need to watch e.g. Copilot consumption without estimating by subtraction), plus limitCredits and plan - GET /api/v2/billing/usage/logs — cursor-paged credit ledger in the v2 envelope - workspace-scoped keys are pinned to their own workspace's slice; personal keys read the account ledger The public wire is credits-only: usage-logs rows now carry a hasCost boolean instead of dollarCost (the Billing UI only needed the >0 signal), and the rateLimit block is removed from the usage-limits response and docs (deploy-modal tab relabeled accordingly). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(docs): validate OpenAPI specs against the Zod contracts in CI The specs in apps/docs are hand-authored because they carry what Zod never defines — error envelopes, status codes, prose, examples — so they can't be generated; check:openapi validates them instead: - spec integrity: $refs resolve, operationIds unique, 2xx documented, no orphaned component schemas - v2 conventions: every /api/v2 operation documents 401 + 429 and every 4xx/5xx resolves to the canonical { error: { code, message } } envelope - contract cross-check: contracts are auto-discovered from lib/api/contracts/v2 (each carries its method + path); doc<->contract coverage both ways, query/body/response field diffs via z.toJSONSchema - examples: documented request/response examples must parse with the matching contract's actual Zod schemas First run caught real drift, fixed here: 16 stale orphaned schemas in the core spec, the v2 billing ops referencing v1-shaped error components, deploy/rollback examples missing the required nullable lifecycle keys, CreateTableBody missing folderId, a legacy-grammar delete-rows example, and four knowledge document ops missing their required workspaceId query param. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * fix(docs): recursive field diff in check:openapi + the deep drift it found A mutation test showed the doc<->contract field diff only compared top-level properties, so a typo inside the { data } envelope passed. The diff now descends through matching object properties and array items (both sides must expose a property set — passthrough contracts and prose-only docs end the descent instead of false-positive), with the Zod JSON-schema root doubling as the $defs context. Deep drift it immediately caught, fixed here: select-column config (options/multiple) missing from every tables column schema, AddColumnBody hand-rolling a third column shape (now composed from ColumnInput, with position/workflowGroupId as the per-op extensions the contracts actually admit), chunking strategyOptions undocumented, and the deployment lifecycle fields (activeDeployment/latestDeploymentAttempt) missing from DeploymentState. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * fix(security): close the triggerType rate-limit bypass on workflow execute Caller-supplied triggerType flowed unchecked into preprocessExecution, whose checkRateLimit default turns OFF for 'manual'/'chat' — so any API-key caller, and any anonymous public-API caller billed to the workspace owner, could execute unthrottled by sending {"triggerType":"manual"} (async runs also skipped the worker-side check via admissionCompleted). External callers may now only send the redundant 'api' value; internal JWT callers ('workflow'/'mcp') are unaffected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * refactor(execution): extract enqueue/status/cancel into shared libs Prepares the v2 execution surface: handleAsyncExecution's queue logic moves to lib/workflows/executor/enqueue-execution.ts (slot/claim semantics encoded in a discriminated outcome, not HTTP statuses), the execution-status read to execution-status.ts, and the order-sensitive cancel machinery to lib/execution/cancel-workflow-execution.ts. The v1 routes re-render identically — their suites pass unmodified. Also: preprocessExecution gains rateLimitCounter ('sync'|'async') and its 429 now carries code RATE_LIMIT_EXCEEDED + retryAfterMs (previously indistinguishable from the concurrency 429 and Retry-After was discarded); and the duplicate cancel contract in contracts/logs.ts is unified on the full 5-value reason enum — its narrower copy made requestJson throw a client ZodError when cancelling a paused HITL run. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(execution): callable execution service + structured error classifier executeWorkflowService composes the same libs the v1 route holds inline (call-chain guard, execution-id claim, LoggingSession, preprocessing, deployed-state load + file-field processing, timeout-bound executeWorkflowCore, output hydration/compaction) for the deployed-state caller class — the seam the v2 execute route and in-process internal callers share, making the HTTP endpoint syntactic sugar. classifyExecutionError stops discarding the block context that buildBlockExecutionError already attaches at throw sites: failed runs now yield {message, code, blockId, blockName, blockType} with a stable append-only code enum (TIMEOUT/CANCELLED/USAGE_LIMIT_EXCEEDED/ INVALID_INPUT/BLOCK_EXECUTION_FAILED/CHILD_WORKFLOW_FAILED/ OUTPUT_TOO_LARGE/EXECUTION_FAILED), so callers route on error class instead of substring-matching messages — the single place raw errors are interpreted. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(api): POST /api/v2/workflows/[id]/execute Thin route over executeWorkflowService: X-API-Key or anonymous public-API auth (sync/stream only for anonymous), strict body with body-flag async (no mode headers on v2), SSE passthrough for stream, and the execution resource response — executionId always present, in-band run failures are status:'failed' with the structured {message, code, blockId, blockName, blockType} error, sync timeout is status:'failed' + TIMEOUT instead of v1's 408, and a Response block's payload stays inside output (authors never control response status/headers on this origin). Async debits the async bucket and the 202 statusUrl points at the v2 executions resource. Adds CLIENT_CLOSED_REQUEST/SERVICE_UNAVAILABLE to the v2 error codes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(api): v2 executions status + cancel with queued backfill GET /api/v2/workflows/[id]/executions/[executionId] is the single status URL for sync and async runs: before the async worker writes the durable log row, status is backfilled from the job queue (deterministic job id) as 'queued'/'running' — closing v1's 202-to-pickup 404 window — and failed runs carry the structured error object. POST .../cancel renders the shared cancellation lib in the v2 envelope with the tightened 5-value reason enum. Both authenticate via the shared resolveV2WorkflowAccess (X-API-Key, authz masked as 404, allowPersonalApiKeys honored). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(execution): workflow tool + MCP bridge run in-process workflow_executor (workflow-as-agent-tool) short-circuits in executeTool through WorkflowBlockHandler — the same invocation boundary canvas child workflows use — mirroring the deployed_block_executor precedent. The MCP serve bridge calls executeWorkflowService directly instead of fetching its own execute endpoint; deployment-version pinning, MCP response-size rejection, and the actor override become typed options instead of header sniffing. Both callers drop the double admission slot and duplicate top-level log row the HTTP hop cost, and failed child runs now surface the structured error + child executionId so parents and MCP clients can route on error class and hand providers a reproducible handle. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(infra): CORS + CSP coverage for the v2 execute path /api/v2/workflows/:id/execute gets the same wildcard-origin, credential-free CORS policy as v1 (the default credentialed policy would block browser API-key calls and open a cookie CSRF surface) with X-Sim-Stream-Protocol allowed and no X-Execution-Mode (async is body-selected on v2), plus the COEP/COOP/CSP header block. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(ui): deploy modal + copilot advertise the v2 execute surface All 20 API-tab snippets move to POST /api/v2/workflows/{id}/execute with the nested {"input": ...} body, async as the "async": true body flag (X-Execution-Mode gone), status polling against the v2 executions resource, the third tab renamed Usage and pointed at /api/v2/billing/usage, and {data} envelope unwraps in the printed responses. Fixes the latent baseUrl derivation (endpoint.split('/api/workflows/')) that would have silently built garbage URLs under a v2 endpoint, and deletes dead code (exampleCommand across 3 sites, getAsyncExampleTitle). Copilot deploy/manage/serializer endpoint builders and the api_trigger bestPractices example follow (the latter also drops its hardcoded staging host). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * docs(api): document the v2 execution surface Adds execute, execution status, and cancel to openapi-v2-workflows.json with the structured ExecutionError schema (append-only code enum + block attribution) and the ExecutionResource contract, documenting the rules that differ from v1: modes are body-selected, a failed run is HTTP 200 with status 'failed', an executionId always means data (never the error envelope), queued status is visible immediately, and Response-block payloads stay inside output. Registers the three pages in the generated workflows meta.json and bumps the route-count baseline. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * feat(api): gate the whole /api/v2 surface behind one flag; UI stays on v1 Every v2 route now runs exactly one check immediately after auth — v2ApiGateError — and answers 404 when the `v2-api` flag is off, so the surface is invisible until it is deliberately rolled out. The gate is keyed on userId only: a workspace/org-keyed check would have to read membership for a caller-supplied id before authorization runs, and its 404-vs-403 split would leak cohort membership (the trap the per-domain table gate worked around by running late). The two executions routes inherit it from the shared access resolver; the tables-specific gate is removed so no route checks twice. `tables-v2-api` stays, now gating only the internal predicate-grammar route /api/table/[tableId]/query — note v2 tables routes move to the unified flag, so enabling them is a `v2-api` decision now. Reverts the deploy modal, copilot handlers, and api_trigger example to the v1 execute endpoint: v1 works unchanged, and the UI must not advertise a surface most users would get a 404 from. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CiHhAk2R1NryaS3R8n2yFz * fix(executor): restore child-cost aggregation dropped by the staging merge Staging's custom-block rewrite deleted `aggregateChildCost` from workflow-handler.ts, and git merged that file cleanly — but this branch's workflow-tool-runner.ts, added for the v2 execute migration, still imports it. A silent semantic conflict: no marker, broken build. Taking staging's rewrite is correct, so the helper is defined locally in its one remaining consumer rather than resurrected in the file staging just rewrote. Same four lines over the still-exported `calculateCostSummary`, so a failed child workflow keeps billing the hosted-key spend it consumed instead of reporting $0. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(tables): make lib/table/orchestration the single implementation (#6134) * refactor(orchestration): move the shared error contract out of lib/workflows OrchestrationErrorCode and statusForOrchestrationError are the contract every lib/[resource]/orchestration module returns against, but they lived inside the workflows module, so resource-neutral code (lib/folders) already had to import from a workflow path. Moved to lib/core/orchestration/types. Adds a 'locked' class mapping to 423. Both tables and workflows have a lock that forbids a mutation, and each caller was translating that to a status itself. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(tables): make lib/table/orchestration the single implementation Column update was implemented four times — the UI route, v1, v2, and the copilot table tool — each calling the same column services but owning its own guards, error mapping, and audit. The copies had drifted, and the drift was the bug: v2 was missing both guards, only the copilot copy minted stable option ids, and only v1/v2 audited. performUpdateTableColumn, performDeleteTable, and performDeleteTableRow now own that logic; all ten call sites reduce to auth, parse, call, render. The guards are asserted once in lib/table/orchestration rather than four times against four routes. Behavior this consolidates, previously true on only some paths: - The typeChanging guard. updateColumnType early-returns on an unchanged type and drops any options sent with it, so restating the current type alongside new options silently discarded them. v2 had no guard at all and, since its contract shares v1's body schema, accepted options and ignored them. - The select-unique guard. Each write is its own locked transaction, so a rename or type change paired with a constraint write that is going to fail commits first and then throws, half-applying the schema change. - Stable select-option ids. Cells reference the option id, so an edit that re-sends an option by name has to reuse it or every cell holding it is orphaned. Only the copilot path did this; normalizeSelectOptionsInput moves to lib/table/select-options and now covers every caller. It preserves a supplied id, so it is a no-op for the fully-formed options the HTTP contracts accept. - required forwarded into the type and options writes, so a conversion validates against the constraint the same request is setting. - An audit on every successful update. The UI route and the copilot tool emitted none. - Single-row delete through the row service. v2 did a raw db.delete, skipping assertRowDelete and deleteOrderedRow, so a delete-locked table returned 200 and the row-count bookkeeping never ran. - The delete actor handed to deleteTable, which audits only when a row was actually archived. v1 and v2 omitted it and audited themselves outside that check, emitting TABLE_DELETED for a no-op delete of an archived table. Failure classes come back as OrchestrationErrorCode; v2 renders them through a new v2ErrorForOrchestration, mirroring statusForOrchestrationError on the v1 and UI surfaces, so a given failure maps to the same status everywhere. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(tables): bind the column-update tests to the orchestration function The base's route tests assert which column service each payload reaches — the behavior that now lives in performUpdateTableColumn. They mocked the `@/lib/table` barrel; the orchestration module imports the service directly, so they mock that too and keep asserting the same thing through the extracted implementation. The orchestration tests move onto the base's semantics: writes address the stable column id, a rename rides inside the write it accompanies rather than running first, and the currency guards replace the non-select options guard the service now owns. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(copilot): drop the column-type import the delegation made dead Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(tables): move the audit log out of the table service `lib/table/service.ts` wrote its own audit rows, so whether an operation was audited depended on which function a caller reached for rather than on a user having performed it. That is what let v1 and v2 audit a no-op delete, and what made `deleteTable`'s optional `actingUserId` double as an audit opt-out flag. Worse, most sites fell back to `actingUserId ?? createdBy`, so an unattributed call was logged against the table's *creator*. The copilot `mv` path passed no actor at all: renaming someone else's table recorded them as the renamer. Audit now lives in the orchestration functions — performDeleteTable, performRenameTable, performMoveTableToFolder, performUpdateTableLocks — and the services just write. Internal callers (folder cascade, import rollback) keep calling the service and are silent by construction rather than by remembering to omit an argument. Two services now return what the audit needs: `deleteTable` reports whether it actually archived a row, so a repeat delete logs nothing; `updateTableLocks` returns the before/after locks, since only the locked write can observe the transition its description names. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(tables): restore audit provenance and conflict status in orchestration Moving the audits into the orchestration functions dropped three things the routes had been carrying, and added one the orchestration now owns twice. - The v1 and v2 column-update routes passed `request` to `recordAudit`, so their audit rows recorded the caller's IP and user-agent. The orchestration function had no way to receive it. Every table orchestration function now takes an optional `OrchestrationRequestContext` and every HTTP route forwards it; the copilot and VFS callers, which have no request, omit it. - `classifyTableMutation` matched `TableConflictError` on "already exists" appearing in the message and reported it as `validation`, turning the UI route's 409 on a duplicate table rename into a 400. It now matches the type, the way `performRestoreTable` already did. - `captureServerEvent` ran on every delete while the audit was gated on a row actually being archived, so a repeat delete of an archived table still reported `table_deleted`. Both now hang off the same evidence. - The copilot delete path kept its own `captureServerEvent` from when the service did not emit one, double-counting every copilot table delete. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YGzbVDZpe2dEALbu2BUU8a * fix(tables): say which type a no-op column update restated A copilot `update_column` payload whose only content was the column's current type used to return success with the live schema, while the v1, v2, and UI routes rejected the same payload with "No updates specified". Delegating to `performUpdateTableColumn` unified them onto the routes' rejection — correct, but the message tells the caller its request was empty when it named a type. The orchestration function now reports the same thing `updateColumnType` reports when it loses this race concurrently: the column is already that type, re-issue without the type change. An empty payload still reads "No updates specified". Drops the copilot's `outcome.table ?? tableForUpdate` fallback with it — the comment described the no-op that can no longer reach that line, and a success always carries a table. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YGzbVDZpe2dEALbu2BUU8a * refactor(tables): classify failures by type instead of by message text The table module decided HTTP statuses by searching error messages for phrases. `VALIDATION_MESSAGE_FRAGMENTS` and `ROW_WRITE_ERROR_PATTERNS` held 32 substrings between them, and fifteen more lists were inlined in routes — 83 matchers over 17 files, each its own copy of the guesswork and already drifted apart. It made message wording load-bearing: `TableRowLimitError`'s own doc comment noted that its text had to contain "row limit" for a route to answer 400, and adding "already exists" to a rename message silently demoted a 409 to a 400 (the bug fixed one commit ago, by adding another special case). Services now throw `OrchestrationError`, which carries the transport-neutral `OrchestrationErrorCode` the layers above already speak. Classification is one `instanceof` in `orchestrationErrorResponse` (UI + v1) and `v2CaughtOrchestrationError` (v2). Every pattern list is gone. Wording is free to change; an unclassified error still becomes a generic 500, which is what an unexpected fault should be. `asOrchestrationError` walks the `cause` chain rather than testing the caught value directly: drizzle wraps a throw raised inside a transaction callback in a `DrizzleQueryError` whose own message is the failed SQL, so a bare `instanceof` would drop every failure raised inside `withLockedTable`. That is the same reason `rootErrorMessage` had to dig for a root cause before. Three throws stay bare `Error` deliberately — `Table ID mismatch`, `Workspace ID mismatch`, and `Failed to build upsert conflict predicate` are internal invariants no consumer classified, and they keep falling through to a 500. `Insufficient capacity` was in the pattern list with no producer anywhere in the codebase. Status changes, all deliberate: - `'forbidden'` joins the code union so the table-row-limit ceiling keeps its 403; without it this refactor would have flattened it to 400. - import-async's table-limit rejection: 400 -> 403, matching the two other create routes it had drifted from. - Renaming a table to an invalid name: 500 -> 400. `validateTableName` messages don't contain "Invalid", so no matcher ever caught them. - Restoring a table that isn't archived, or into an archived workspace: 500 -> 400. - A duplicate *column* name stays `validation`/400 rather than becoming a 409 like a duplicate table name. Both v1 and the orchestration have always answered 400 for it; changing a published status is not this refactor's job. The twelve tests that changed were asserting the substring mechanism itself, constructing plain `Error`s with magic strings. They now assert the real contract, plus new cases pinning that identical wording carrying no classification stays internal and keeps its message off the wire. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YGzbVDZpe2dEALbu2BUU8a --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(api): add v2 endpoints for MCP servers, skills, custom tools, folders, and credentials (#6150) * feat(api): add v2 endpoints for MCP servers, skills, custom tools, folders, and credentials * fix(api): correct credential role, skill permission bar, MCP url identity, and custom-tool conflict mapping * fix(api): align credential mutation gating, provider-outage status, and unique-violation conflicts * fix(api): close unique-violation, revival, orphan-write, and env-rename gaps * fix(api): treat every provider-outage code as unavailable on create and update * fix(credentials): use the shared outage predicate on the session update path * fix(contracts): anchor the predicate double-cast annotation to the cast `check:api-validation:strict` counted 9 unannotated double-casts against a baseline of 8, failing CI. The predicate leaf schema was annotated, but the annotation sat above the declaration while the checker anchors on the line carrying the cast — five lines below, at the close of the object literal. The scanner walks back at most three lines and stops at the first non-comment one, so it hit `value: z.unknown().optional(),` and never saw the reason. Splitting the object schema from the cast puts them adjacent, so the existing reason binds. No behavior change — the cast, the schema, and the reasoning are unchanged. Also lowers the rawJsonReads ratchet 6 -> 5 to match the current count, which had drifted down; leaving it high lets a removed raw read silently come back. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(skills): point the orchestration error contract at its moved module #6150 branched before #6134, so skill-lifecycle.ts imports @/lib/workflows/orchestration/types — the module #6134 moved to @/lib/core/orchestration/types. Git merged a file deletion on one side with a new file referencing it on the other: no textual conflict, broken build. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(knowledge): make lib/knowledge/orchestration the single implementation (#6154) * refactor(knowledge): make lib/knowledge/orchestration the single implementation Knowledge base create was implemented four times — the internal route, v1, v2, and the copilot tool — and the orchestration around the shared write had drifted. Extract it the same way lib/table/orchestration was: services write, orchestration decides which writes run, guards them, audits them, and returns a transport-neutral failure. Behavior converged, not preserved: - One chunking default (DEFAULT_CHUNKING_CONFIG). The agent defaulted minSize to 1 against the API's 100, so identical input produced differently-chunked knowledge bases depending on who created it. The agent path now chunks at 100. - Every successful mutation is audited inside the orchestration function. The copilot tool called recordAudit zero times, so agent-created knowledge bases, document uploads, updates and deletes left no audit trail at all. - Failures classify by class, not by message text. The knowledge service errors are OrchestrationError subclasses and storage-quota rejections throw a shared StorageLimitExceededError, replacing four separate message greps for "already exists" / "does not have permission" / "storage limit". delete_connector reported the opposite of what happened. It reached the route through an internal HTTP self-call that sent no query string, so the route's keep-documents default always applied while the agent told the user the documents had been removed. The self-call is gone — all four connector operations run in-process — and the orchestration returns the real counts. Also: - OrchestrationErrorCode gains 'payload_too_large' (413 / PAYLOAD_TOO_LARGE). Without it, dropping the storage-limit message match would have regressed the documented 413 on knowledge base create and document upload to a 500. - messageForOrchestrationError renders a route's own wording for an unclassified fault, so a driver's message no longer reaches the client on a 500. - v1 and v2 knowledge base update now forward actorUserId, which the service requires for a workspace move; both omitted it. - The connector DELETE route reads deleteDocuments through parseRequest. Its contract declared z.boolean(), which would have rejected the string a query param actually is. - Drop the 409 from POST /api/v2/knowledge/{id}/documents in the OpenAPI spec. Nothing on the upload path throws a conflict; it was only ever reachable by the message match this change removes. Behavior change worth noting: a v1/v2 PUT carrying only the workspaceId scope field and no actual updates now returns 400 rather than 200 with the unchanged knowledge base. Deliberately deferred: document update remains internal-only. Extracting performUpdateKnowledgeDocument makes exposing it on v1/v2 a contract and a route away, but that is a new public surface rather than part of this consolidation. * fix(knowledge): make connector create atomic and stop flattening failures Review round 1 on #6154. - Resolve the billing payer before the connector is committed, not after. A malformed attribution header rejected post-commit left a live connector behind a 500, and a retry created a duplicate plus duplicate sync work. Manual sync resolves before writing its audit for the same reason. - Let the source-config validator carry its own failure class. Collapsing every rejection to `validation` flattened the connector PATCH route's 401 (stale stored credential) and 409 (missing workspace context) into a 400. - Add `unauthorized` to OrchestrationErrorCode. It is the class that 401 was already expressing on this route, and the v2 vocabulary already had UNAUTHORIZED; only the shared union was missing it. - Report a knowledge base that exists but failed to archive as failed, with the reason, rather than as not found. The copilot delete loop folded every non-not-found failure into `notFound`, telling the user it was never there. - Route copilot failures through the same message helper the HTTP surfaces use, so an unclassified fault's raw text (a driver's failed SQL) no longer reaches the agent verbatim while the UI and public APIs get the generic wording. * feat(api): expand the public v2 files surface (#6160) * feat(api): expand the public v2 files surface Adds folder support, rename/restore, move, bulk archive, share, and content replace to /api/v2/files, so managing files by API no longer stops at upload + download + archive-one. Routes are thin: auth -> parse -> perform* -> serialize. Share and content replace get their orchestration extracted first so the session routes and the public ones cannot diverge on the effective-authType resolution, the EE public-sharing gate, or the storage-quota classification. Presigned upload stays session-only: presign does an advisory quota check and the real debit happens in the separate register step, so a caller that never registers leaves unaccounted bytes with no reaper. The buffered multipart path debits inside uploadWorkspaceFile's own transaction. * fix(files): classify folder and content failures instead of 500ing them Bugbot round 1. The v2 routes map errorCode straight to a status, so every manager failure that arrived unclassified became a 500 for what is really a caller-fixable 400 or 404. - Folder manager throws OrchestrationError: missing target/folder -> not_found, reparent cycle / self-parent / restore-into-archived-workspace -> validation. - File manager does the same for the in-transaction 'File not found' paths that the earlier pass missed. - updateWorkspaceFileContent's outer catch re-wrapped everything in a bare Error, which stripped the class off StorageLimitExceededError and the new not_found alike. It now rethrows a classified failure untouched and attaches cause to the generic wrap, so asOrchestrationError can still walk the chain. - Every remaining perform* gained the asOrchestrationError branch. - renameWorkspaceFile returned the pre-update read, so the v2 PATCH reported a stale updatedAt; it now returns the timestamp it actually wrote. Docs: upload auto-suffixes a duplicate name rather than rejecting it, matching the in-app uploader. The description claimed 409 and was simply wrong. * fix(files): surface a failed upload read-back as the real error getWorkspaceFile swallows a query failure and returns null unless throwOnError is set, so a transient blip on the post-upload read reported as 'file could not be read back'. Distinguish the two: a real null after a just-committed write is an invariant break, a query failure is itself. * revert(api): drop the dedicated v2 file-folder routes File folders already live in the shared folder table as resourceType 'file' (#6045 cut them over, #6051 dropped workspace_file_folders), and the remaining file-specific folder machinery is being folded into the generic folder engine. Publishing /api/v2/files/folders/** would pin that transitional split into a public contract we'd then have to keep or break. Files stay folder-aware — folderId/folderPath on the projection, folderId on upload, and the move route — because a folder id is a folder.id and survives the unification untouched. Folder management belongs on /api/v2/folders once that surface serves resourceType 'file'; until then there is no v2 way to enumerate file folders, which is the deliberate gap. The orchestration classification fixes stay: the internal routes and the copilot file-folder tools still call those perform* functions. * fix(files): classify upload failures instead of matching their wording Bugbot round 2. uploadWorkspaceFile had the same outer-catch rewrap that updateWorkspaceFileContent did, so a blown storage quota reached the route as a bare Error and the v2 handler recovered the status by substring-matching the message. Any rewording silently demoted a 413 to a 500. - uploadWorkspaceFile rethrows a classified failure untouched and attaches cause to the generic wrap. - FileConflictError is now an OrchestrationError('conflict'), so a duplicate name classifies like every other conflict. Its 'FILE_EXISTS' discriminator had no readers and is gone; the instanceof checks elsewhere still hold. - The v2 upload handler uses v2CaughtOrchestrationError, dropping all three string matches. Also documents that bulk-archive is best-effort: unknown or already-archived ids are skipped rather than failing the call, and deletedItems is what actually happened. That asymmetry with the single-id DELETE was undocumented. * feat(api): add search, filtering, and sorting to the v2 list endpoints (#6189) * feat(api): add search, filtering, and sorting to the v2 list endpoints One convention across every v2 list, documented on lib/api/contracts/v2/shared.ts: `search` (case-insensitive substring on the resource's natural name field), `sortBy` + `sortOrder` (per-resource enum, never a free string), and enumerated resource-specific filters. Reuses the sortBy/sortOrder pair v2 logs and v2 knowledge-documents already ship rather than inventing a third dialect alongside the Logs filters and the Tables predicate grammar. Every filter and sort is pushed into SQL. GET /api/v2/files previously read the whole scope and sorted/sliced it in JS; it now goes through a new queryWorkspaceFiles that filters, orders, and bounds the page in one query. Cursors are stamped with the sort they were minted under, so replaying one under a different sort is a 400 instead of silently duplicated or skipped rows. * fix(api): validate v2 cursor key values and compare timestamps at ms precision Two review findings, fixed at the root by making a keyset key own its cursor codec instead of hand-writing a decoder per sort. Cursor key values are caller-controlled, and matching the sort stamp and key count was not enough: an unparseable timestamp or a non-numeric size reached the query as an Invalid Date or NaN and surfaced as a 500. Each key now type- checks its own value and rejects a cursor it cannot hold, which both routes render as the documented 400. Timestamp keys now order and compare on date_trunc('milliseconds', col). Postgres keeps microseconds and defaultNow() populates them, but a cursor value round-trips through a millisecond-only JS Date — comparing the raw column against the truncated value re-admitted the page's own last row, duplicating it and stalling pagination outright at a page size of one. Reachable today via workspace_files.updated_at, which insertFileMetadata leaves to defaultNow(). * feat(api): complete the v2 workflows resource with versions and CRUD (#6184) * feat(api): complete the v2 workflows resource with versions and CRUD Adds version listing/detail plus create, update, and delete to the v2 workflows surface, which previously covered only execution and deployment. - GET /api/v2/workflows/[id]/versions — cursor-paginated, newest first - GET /api/v2/workflows/[id]/versions/[version] — version + pinned state - POST /api/v2/workflows, PATCH and DELETE /api/v2/workflows/[id] All six delegate to the existing orchestration and persistence helpers; no new domain logic. * fix(api): check folder containment before lock state; reject malformed version cursors assertFolderMutable walks a folder's ancestor chain without filtering on workspace, so inspecting it before containment let a caller tell a locked folder in someone else's workspace (423) from a nonexistent one (400). Create and update now assert containment first, matching the ordering import-workflow.ts already uses. A version cursor that decodes to JSON without a numeric version filtered every row out and returned an empty page with nextCursor null, which reads as a clean end-of-list. Malformed cursors are now a 400. * refactor(api): page workflow versions in the persistence helper listWorkflowVersions read every version row and the route filtered and sliced the result in memory, so the response was bounded but the query was not. It now takes optional limit/afterVersion, turning the cursor into a real keyset query; the route asks for limit + 1 and only trims the has-more probe. Both params are optional, so the internal, v1 admin, and copilot callers are unchanged. Also restores the untouched GET handler in [id]/route.ts to its original formatting — collapsing its signature had re-indented the whole body and buried the actual additions in whitespace churn. * feat(api): expand v2 tables with stateless multipart transfers (#6188) * feat(api): expand the public v2 tables surface Adds 16 operations so a v2 caller can do what the internal surface can: rename/move/lock a table, restore it, manage saved views, run enrichment columns, look up rows, and import/export with observable job control. Extracts lib/table/orchestration/import.ts (performTableCsvImport, performCreateTableFromCsv) and lib/table/export-stream.ts from the first-party routes, then repoints those routes at them, so v1 and v2 cannot drift on what an import or export actually does. events/stream, metadata and dispatches stay internal — they are editor state, not public API. * fix(api): make v2 table PATCH all-or-nothing and name the lock in every 423 Greptile P1: PATCH applied locks, rename and move as three sequential transactions, so a folder rejected mid-request left the earlier writes persisted while the response reported failure — and the schema-changed signal was skipped, leaving open clients on stale state. Every rejectable condition now runs before the first write, and the signal fires whenever anything did land. Cursor: v2TableLockError dropped the lock kind, so async import, column run, enrichment and table mutations returned a bare LOCKED. A table has four independent locks, so the caller could not tell which to clear. * fix(api): report the lock kind on classified 423s too, not just thrown ones The previous commit named the lock only where the rejection was thrown and caught at the route boundary. Where it instead arrives as a classified `errorCode: 'locked'` outcome — delete table, delete row, update column, and the table mutations — the kind was dropped, so those 423s stayed unactionable while their neighbours improved. The orchestration results now carry `lock`, and a shared `v2TableOrchestrationError` renders both arrival paths into the same `{ code, message, details: { lock } }` body. `details` is omitted rather than sent null when the kind is unknown, so a caller branching on it sees absence instead of a phantom value. * fix(api): make async table imports observable, not just startable `POST /import-async` pointed callers at `GET /api/v2/tables/jobs` to track progress, but that endpoint filters to `type = 'export'` — imports are derived onto the table itself, one write job at a time, and exports get a separate list precisely because they are excluded from that derivation. The public Table shape omitted those derived fields, so an async import could be started and cancelled but never observed to completion, failure, or progress. That is the gap the import/export/job-control set was meant to close. Table now carries `job` — id, type, status, rowsProcessed, error, or null when idle — and the import-async docs point at the table rather than the export list. * feat(api): make v2 table PATCH state which operations landed on failure Greptile held the PR at 4/5 on the residual non-atomicity and named two acceptable resolutions: make PATCH atomic, or have the contract adopt and expose partial-success explicitly. Atomicity would mean threading one transaction through renameTable, moveTableToFolder and updateTableLocks — three shared service functions with four non-test callers including the first-party route and two copilot tools — and deferring their per-operation audits to commit time. That is a refactor of shared write paths well outside this PR. So the contract states it instead. Every rejectable condition is already pre-validated, so a failure here is a genuine fault; when one follows a successful operation the error now carries `details.applied` listing what is live. Absent when nothing applied, so its presence always means "these changes took effect despite the error". Documented on the operation. `v2ErrorForOrchestration` gained the optional `details` this needs. * fix(api): make table lock flags read-only on the public v2 surface The new PATCH /api/v2/tables/[tableId] accepted a `locks` object, gated on workspace admin plus the table-locks feature. That still lets an API key clear the guard placed there to stop it: `write` is the floor for the endpoint, and admin keys are ordinary API keys, so a lock is no longer a boundary the key cannot cross. Locks stay readable on the table resource and enforcement is unchanged (a locked verb still returns 423). Changing one is now a first-party admin action only. The v2 body is declared here rather than reusing the first-party updateTableBodySchema, which keeps its `locks` field so the UI can still toggle them. It is .strict(), so a request carrying `locks` is rejected with a 400 naming the field instead of silently succeeding without applying it. * fix(api): keep reporting applied operations when the PATCH re-read fails The composite table PATCH promises that `error.details.applied` names the operations that are live despite an error, but `applied` was scoped inside the try. A rename or move that committed and was then followed by a throw in the final re-read — or a re-read finding the table archived — returned a bare 500/404 with no details, telling the caller nothing had landed. It would then retry into a duplicate-name conflict or repeat the move. `applied` is now function-scoped so every post-write exit carries it: the 404 on a missing re-read, a thrown lock error, a classified orchestration error, and the generic 500. `v2TableLockError` gains the same `extraDetails` parameter `v2TableOrchestrationError` already had. * feat(api): add workflow group writes to the v2 tables surface v2 exposed GET /groups but none of the writes, so the public API could run an enrichment or workflow column and read its binding, but never create one. A caller could add a plain data column and trigger the machine; wiring the two together still required the UI. Adds POST/PATCH/DELETE on /api/v2/tables/[tableId]/groups. The group is the unit that fills columns — one group feeds several — so creating one creates its output columns in the same call, matching the first-party shape rather than inverting it onto the column endpoint. Four departures from the first-party body, all public-surface concerns: - group.id is optional and server-generated. The UI mints an id to render optimistically; a public caller has no such need and a client-chosen id is a collision waiting to happen. - outputColumns[].workflowGroupId is dropped from the body and stamped from the resolved group, so it cannot disagree with it. - autoRun defaults to false. First-party defaults true so a UI add fills cells immediately; here it would make one POST fan out a metered run across every existing row. - A group naming neither a workflowId (type manual) nor an enrichmentId (type enrichment) is a 400 rather than a half-specified group the route has to guess about. Also rejects an outputColumns entry no group output feeds — the two arrays are joined by column name, and the first-party client builds both from one picker so it cannot desync, but a public caller can. Workspace containment on workflowId is asserted before it is persisted, on create and on any update that re-points the group; without it a table becomes a way to invoke workflows the key cannot otherwise reach. * improvement(api): make v2 table import and export async-only Drops the three synchronous entry points: POST /tables/[tableId]/import, POST /tables/import-csv, and GET /tables/[tableId]/export. Sync import tied a write to the lifetime of an HTTP request. The body *was* the data, so it carried a 10 MB cap that Next silently truncates past — a partial import reporting success. It also had no job, so a timeout mid-write left rows in place with nothing to poll and nothing to cancel. The async path reads the file from storage instead: upload via POST /api/v2/files for a key, start with POST /import-async, watch GET /tables/[tableId] -> job, stop with POST /job/cancel. Sync export carried no such hazard, but one shape per operation beats two: with both removed the surface has exactly one way to move a table in or out, and the CLI wraps the extra calls. This also removes the last multipart handling in v2 tables. Those were the only routes bypassing parseRequest — form fields were parsed by hand against separate form schemas, outside the contract system every other v2 write goes through. Create-a-table-from-CSV is now two calls: POST /tables, then /import-async with createColumns. csvImportModeSchema is append|replace, so there is no single-call create. Route baseline 1064 -> 1061. * docs(api): correct the import-async note about upload size limits The docstring claimed there is no synchronous upload endpoint and so no request-body size cliff. Both are wrong: POST /api/v2/files is a synchronous multipart upload with a 100 MB cap, and it is the only v2 upload path (presigned is deliberately absent). What async-only actually bought: the cap went 10 MB -> 100 MB, it fails on an explicit size check and a bounded body read rather than a proxy cap that silently truncates, authorization completes before any body is buffered, and the table write is a job that can be watched and cancelled. * feat(api): unify file and table transfers * improvement(api): make multipart transfers stateless * fix(api): make table import completion retries idempotent * feat(v2-tables): paginate the table list `GET /api/v2/tables` returned every table in the workspace in one response — it used the cursor envelope but hardcoded `nextCursor: null`, and had no `limit`. That was defensible when tables were only created through the UI; `POST /api/v2/tables` is public now, so a script can create them in bulk and the list has no way to ask for less. Adds `queryTables` alongside `listTables` rather than changing it, so the internal callers that genuinely want the whole scope are untouched — the same split `queryWorkspaceFiles` / `listWorkspaceFiles` already uses. Filter, order and slice all run in the query, so a `search` never costs a full-workspace read. A cursor whose values don't bind raises a validation error instead of being coerced to "no filter", which would have silently served page 1 under a resumed cursor. The keyset closes on `id` so a page boundary inside a run of equal names or timestamps stays stable. The shared `LimitQuery` doc component said "Maximum rows to return"; it now serves the table list too, so the wording is resource-neutral. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(api): add multipart knowledge document uploads * fix(api): keep usage admission at knowledge upload session creation * feat(knowledge): wire knowledge base uploads to multipart sessions * fix(knowledge): refuse to abort an upload once a document is bound * fix(uploads): prevent multipart cleanup races * Unify file creation and signed upload sessions (#6264) * feat(uploads): unify signed upload sessions * fix(uploads): preserve attachment storage semantics * feat(files): add authored file creation * fix(uploads): omit hoisted S3 metadata headers * feat(api): add file metadata endpoint * improvement(api): scope folders to resource paths (#6284) * improvement(api): scope folders to resource paths * fix(files): serialize folder resolution with uploads * fix(files): release folder lock before upload setup * fix(api): normalize folder paths and unblock resource mutations * fix(api): make resource cleanup and metadata consistent * improvement(uploads): persist multipart sessions in postgres * fix(db): store table row trigger timestamps in UTC * improvement(api): default folder deletion to non-recursive * fix(billing): unify chat usage source * improvement(logs): expose trace spans on log detail * fix(logs): parse list trace spans * improvement(api): replace workflow jobs with execution resources (#6294) * improvement(api): replace workflow jobs with execution resources * fix(api): preserve legacy jobs while preferring v2 executions * fix(api): make execution polling resume-aware * fix(ui): hide async examples for public workflows * fix(api): bridge resume queue visibility lag * feat(api): add v2 workflow resume endpoint * fix(api): project pending resume attempts * fix(api): prefer terminal logs over stale resumes * improvement(api): unify v2 resource query layers (#6319) * improvement(api): unify v2 resource query layers * fix(api): address v2 review findings * fix(api): preserve cancelled queue status * fix(api): guard cancelled job transitions * fix(api): close v2 resume and log gaps * feat(api): rename v2 executions to runs * feat(api): split credentials and secrets * feat(api): add workspace metadata and email attribution * improvement(api): consolidate public v2 route handling * improvement(files): centralize operations across APIs and Copilot (#6392) * improvement(files): unify rename authorization * chore(skills): add file operation migration guide * improvement(files): consolidate file operation authorization * improvement(files): extract shared operation foundation * improvement(api): simplify internal route declarations * improvement(files): centralize application authorization * refactor(api): share workspace file name validation * refactor(files): centralize copilot application calls * docs(skills): generalize application operation migration * improvement(api): centralize remaining v2 resource operations (#6412) * improvement(api): centralize v2 resource operations * fix(api): preserve custom tool conflict errors * improvement(api): migrate policy-sensitive v2 reads (#6410) * improvement(workflows): centralize v2 application operations (#6411) * refactor(api): migrate v2 knowledge operations (#6413) * refactor(api): migrate v2 knowledge operations * fix(knowledge): fail upload completion on dispatch errors * fix(knowledge): preserve upload retry and VFS errors * improvement(tables): centralize v2 application operations (#6414) * improvement(tables): centralize v2 application operations * fix(tables): preserve run validation and signals * feat(auth): add scoped internal executor delegation (#6459) * feat(auth): add scoped internal executor delegation * fix(auth): derive delegation lifetime from one timestamp * Include share status in file metadata * feat(auth): centralize delegated identity policy (#6462) * improvement(copilot): consolidate application adapters (#6450) * improvement(api): harden application route boundaries (#6451) * improvement(api): harden application route boundaries * fix(folders): reject creates at workspace cap * fix(knowledge): enforce trusted workspace scope (#6452) * fix(knowledge): enforce trusted workspace scope * refactor(knowledge): declare v2 body lifecycle * finish knowledge application migration * refactor(knowledge): compose copilot batch commands * fix(knowledge): parse connector query flags * fix(knowledge): finalize partial batch effects * fix(knowledge): align merged application boundaries * fix(knowledge): close application boundary review gaps * style(knowledge): satisfy branch biome checks * fix(knowledge): page connector documents in editor * refactor: enforce Copilot table application boundary (#6453) * refactor: enforce copilot table application boundary * fix(tables): finish application boundary migration * fix(tables): restore scoped copilot imports * fix(tables): compose copilot commands atomically * fix(tables): preserve workflow group scheduling * fix(tables): complete fixed copilot composition * fix(tables): reject enrichment output mutation * fix(tables): complete authorized application boundary * fix(workflows): migrate Copilot application boundary (#6455) * fix(workflows): migrate Copilot application boundary * fix(workflows): finish delegated application migration * fix(workflows): encode VFS folder aliases * fix(workflows): close application composition gaps * fix(workflows): preserve VFS validation errors * fix(workflows): complete application boundary migration * test(workflows): format canonical binding coverage * fix(workflows): scope executor metadata reads * fix(workflows): bind executor metadata targets * improvement(skills): align application operation guidance (#6532) * feat(api): expose v2 resource owners * fix(api): distinguish visible resource authorization failures (#6537) * feat(api): generate v2 OpenAPI from contracts (#6509) * feat(api): generate v2 OpenAPI from contracts * fix(api): preserve string boolean wire defaults * fix(api): document file download headers * fix(docs): use TypeScript CLI with Next.js * fix(docs): avoid client-rendered theme script * fix(api): document departed audit default * feat(api): replace legacy core docs with v2 * feat(api): generate v2 OpenAPI from contracts * feat(api): refine generated v2 OpenAPI docs * fix(docs): align localized v2 execution examples * fix(ci): restore Helm diff and sync audit mock * fix CI regressions after staging merge --------- Co-authored-by: Waleed <walif6@gmail.com> Co-authored-by: Theodore Li <theodoreqili@gmail.com> Co-authored-by: Siddharth Ganesan <33737564+Sg312@users.noreply.github.com> Co-authored-by: Theodore Li <theo@sim.ai> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |