69 Commits
Author SHA1 Message Date
Waleed 5bef3d8a3b fix(db): give push-managed databases the bytewise order_key collation (#10372) 2026-11-24 11:10:39 -08:00
Waleed 287a110ebf chore(cleanup): remove dead chart options, the playground and legacy chat routes; contract retired DB objects (#10269)
* chore(cleanup): remove dead chart options, the playground and legacy chat routes; contract retired DB objects

* fix(cleanup): address review findings

* fix(emcn): drop the folder title and selection callback nothing reads

* fix(egress): name both allowlists in the removed-variable startup error

* chore(docs): refresh the compatibility baseline for changed pages

* improvement(cleanup): drop dead folder plumbing and stale names left by the removals
2026-11-20 19:06:41 -08:00
Waleed 74eca43677 improvement(ci): turn off crash durability on throwaway CI postgres (#10251)
* improvement(ci): turn off crash durability on throwaway CI postgres

* fix(ci): keep synchronous_commit on and scope durability tuning to e2e jobs
2026-11-20 13:13:01 -08:00
Waleed 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 62872bd29b.

* chore: regenerate the OpenAPI spec and MCP operations for the workspace-key description

* docs(cli): document exit 13 (AUTH_REQUIRED), exit 9 and the 429 resend policy

Both exited 1 before this branch. State which requests are resent (every GET and the
all-or-nothing source writes), the 6-retry count and the one-minute wait cap, in the
scripting exit-code section, troubleshooting, the CLI reference preamble, the README and the
source agent guides.

* fix(workspace-source): managed table rows guard a delete and a column renamed on the server

An --allow-delete of an undeclared managed table whose rows were written
since the base deleted those unseen edits; it is now E_APPLY_STALE. A rows
edit on a table whose declaration is unchanged while the server renamed or
removed one of its columns wrote the cells by names the table no longer
has, silently dropping them; it is now E_APPLY_STALE.

* fix(workspace-source): a stored() tool or MCP server deleted on the server stays deleted

An unchanged directory whose tool code or MCP header is stored() was
refused (E_APPLY_STALE / E_TOOL_STORED_MISSING / E_MCP_STORED_MISSING)
once the resource was deleted on the server, blocking every other kind.
It now reads as I_SERVER_DELETED like any other deleted resource.

* docs(workflow-sdk): document a child workflow's output shape

runWorkflow's result is the child's first response block output ({ data, status, headers }),
else its last block's output, so a response body field is result.data.field; a deployed parent
runs the child's deployed version. Stated in INDEX.md's How it runs, the runWorkflow TSDoc, the
agents example and the agent guide.

* fix(workflow-code): round-trip stored container edges source cannot draw

Stored workflows hold container edges the canvas never draws: a loop or
parallel start edge to a block outside it (the editing engine keeps one when it
extracts a block, and the executor runs it as the container's exit), an end edge
into the container's own child, and an error edge from a container. Source
printed the first two through p.to()/x.to() and every one through onError, and
compile refused them (E_EDGE_SCOPE, E_ERROR_PORT_UNSUPPORTED), so such a workflow
could not apply its own source back.

The printer now writes a mismatched container edge as edge() with its stored
handle, compiled with W_SUBFLOW_HANDLE_SCOPE (the warning names the exit form),
and compile keeps an error edge from a block with no error port when the stored
workflow holds it (W_ERROR_PORT_STORED). The corpus gains both edge shapes.

* fix(editing): keep a stored error edge the engine no longer adds

Since the engine refuses new error edges from loops and parallels, an edit that
re-sends a container's connections dropped the error edge it already stored.
Error edges the graph held before the batch are kept; only new ones are
refused.

* test(workflow-source): stored mismatched container edges survive every write path

The extract and move-into-loop regressions now assert the engine keeps the
edge and source round-trips it; a stored container error edge survives an
engine edit that re-sends its connections; and an integration check writes a
loop start edge to an outside block through PUT /state, edits through the
engine, and applies the source back unchanged.

* fix(workspace-source): type the in-use scan rows for the query builder

* fix(tables): accept a required column on a table with rows again outside workspace source

facb1c4f4d made every surface refuse adding a required column that existing rows
leave empty, which turned a call third-party integrations make on the v1 and v2
table APIs into a 400. The refusal is now an addTableColumn option only
workspace-source apply sets, so its plan and apply agree while the table APIs,
Copilot and undo keep staging's behaviour. Restores staging's undo hook,
OpenAPI description and contract comment.

* fix: attempt every independent side effect of a fan-out after one fails

The shared mapWithConcurrency starts nothing after a failure, where the apps/sim
helper it replaced kept starting the rest. For fan-outs of independent side
effects that left Slack targets undispatched, tombstones and cancellation
writes unwritten, stale-dispatch cancel events unsent, project file retirements
and chat image sweeps unrun. mapEachWithConcurrency attempts every item, then
throws the first failure; those callers use it.

* chore(e2e): name the workspace source e2e report variable like its siblings

WORKSPACE_SOURCE_REPORT_PATH becomes WORKSPACE_SOURCE_E2E_REPORT_PATH, matching every other
source e2e's <SUITE>_E2E_* variables; the CI http-e2e script passes the new name.

* feat(workflow-code): warn on a condition or router branch no edge leaves

W_BRANCH_UNWIRED names the branch and the wiring that fixes it. A branch the stored workflow
already leaves unwired is not reported, and check fails on it only for a block the lock does not
bind, so existing workflows keep checking clean.

* fix(workflow-code): read a Start block's untouched blank input row as no fields

Every new workflow's Start block is seeded with one unnamed string field, which execution skips,
so `get` on a fresh workflow printed `inputFormat: { '': 'string' }`. A list holding only that
starter field now canonicalizes as empty and prints `inputFormat: {}`; an unchanged apply keeps
the stored field byte for byte, and a blank field beside named ones still prints as stored.

* fix(workflow-source): fingerprint a stored workflow the same for every reader

The sf1 fingerprint hashed the reader's canonical model, which names a
credential the reader may see by key and one they may not see by id, so a
member applying source a teammate read got a false 409. It now hashes every
credential by its stored id. A credential key the reader cannot resolve,
standing where the stored workflow holds a credential they cannot see, keeps
the stored credential whatever the key (W_APPLY_CREDENTIAL_KEPT), so an
unchanged or edited teammate source applies without confirming any key.

* fix(workflow-source): refuse workflow names and descriptions v2 refuses

Source could set an empty or whitespace name, a name over 255 characters or
a description over 50,000, which v2 create and update refuse. The plan now
refuses the fields a write sets with E_WORKFLOW_META_INVALID at the header,
reading the limits from the v2 workflow contract.

* fix(workspace-source): keep unkeyed managed rows out of source, and check required fills at plan

A row the table grid's "add row" makes has an empty key cell, so a get printed it as a line the
apply refuses (E_TABLE_ROWS): get -> apply of an unchanged directory failed. Such a row has nothing
a line can match it by, so it is no longer managed: a get leaves it out of the rows file with
I_TABLE_ROWS_UNKEYED, neither rows fingerprint counts it, and the keyed write never removes it.

Making a column required trusted the declared rows to fill it even when no rows write was planned,
so a row added in the UI made the apply fail mid-reshape. The declared rows now stand for the
table only when a managed rows write is planned, and the rows that write keeps (unkeyed ones) are
checked too.

* fix(workspace-source): compare managed rows with the base under the key it recorded

Changing a managed table's rows key and editing a row in one apply was a false E_APPLY_STALE: the
server's rows were fingerprinted under the new key and compared with a base fingerprinted under
the old one. The staleness check now reads the server under the key the table is still marked by.

* fix(workspace-source): a reader's concealed MCP get applies back unchanged

A get by a member who may not rewrite headers prints every literal header value as stored(); the
plan resolved each stored() to a keyed hash, while a value that is not a credential prints (and
fingerprints) as its text, so a writer applying that directory unchanged always planned a header
update. stored() now resolves to the value as a get prints it.

* fix(workflow-source): answer a racing source rename with SOURCE_NAME_TAKEN

Two source renames onto one name in one folder both passed the name SELECT;
the second hit the unique index and answered 500. The commit now maps that
unique violation to WorkflowSourceNameTakenError, and the apply route answers
it, like the create route, with 409 SOURCE_NAME_TAKEN.

* fix(workspace-source): an unchanged file the server can no longer hand to source is a no-op

A declared file edited past the blob cap in the Files tab, or one an older file moved beside it
now takes the path of by letter case, refused the whole apply of an unchanged directory
(E_FILE_TOO_LARGE / E_FILE_PATH_COLLISION). Unchanged since the get that read it, the declaration
now leaves the file as the server has it (I_SERVER_CHANGED); a directory that changes it is still
refused.

* fix(workflow-source): report a dry run's needsRedeployment for the draft it would write

A dry run answered needsRedeployment for the draft as stored, so an edit of a
draft in step with its deployment said false and a revert said true. A dry run
that would change the draft now compares the draft it would write with the
active deployment; a no-op or refused dry run still reports the stored draft.

* fix(workflow-source): record no refused apply for a plan-only evaluation

A workspace plan or dry run evaluates each workflow planOnly, so planning a
locked workflow recorded workflow_source_applied ok:false although nothing was
applied. A planOnly run records nothing; the commit that follows records its
own outcome.

* fix(workspace-source): a knowledge document replace that stops partway resumes without losing tags

A replace uploaded the replacement under the document's own name, then carried the old one's tags
and deleted it. Stopped after the upload, the next apply deleted the old document without
carrying its tags; stopped and then edited again, the two same-named documents read as a server
change (E_APPLY_STALE) until deduplicated by hand, since nothing told the replacement from a
document uploaded twice in the UI.

The replacement is now uploaded under a name that names the old document, takes its tags, the old
one is deleted, and the replacement is renamed. The next apply finishes a stopped replace whose
replacement holds the declared bytes (tags carried, old deleted, renamed), or removes the
replacement and replaces again; a replacement left before its rename stands for its name. The
duplicate-by-hash rule this replaces is gone: an unmarked duplicate is ambiguous, as any other.

* test(workflow-code): compare n with 8n in the growth check, so allocation noise on a slow runner stays far from the quadratic bound

* fix(workflow-source): never keep a hidden credential over a key the apply binds

A credential key the enclosing workspace apply binds in the same run is not an
unknown key, so it resolves to that credential rather than keeping the stored
one.

* test(workflow-code): read and write input-format rows through their real shape in the API-built round trip

* fix(workflow-code): keep a hidden credential on a block the source renames

compileSource now returns the stored model it compiled against, re-keyed by the
source's renames, and keptCredentials pairs compiled blocks with it, so a member
who cannot see a credential can rename the block holding it.

* fix(sim-cli): offline check passes stored container error edges, cycles and branches on bound blocks

The offline check compiles without the stored workflow, so it refused an
onError on a loop or parallel and a cycle that a get printed and the server
keeps, and told the agent to delete them. compileWorkflow takes storedUnread:
an edge between two lock-bound blocks may be stored, so it reports
W_ERROR_PORT_STORED / W_EDGE_CYCLE saying an apply keeps it only if the stored
workflow holds it, and the error stays for a new block. E_ERROR_PORT_UNSUPPORTED
hints no longer say to remove the edge. W_BRANCH_UNWIRED never fails the check
on a bound block, --strict included, matching its stored exemption.

* fix(serializer): never evaluate a viewer-scoped default on the server

* fix(sim-cli): keep a downloaded workflow's stored inputs typed in workspace.d.ts

* fix(sim-cli): exit 13 when the server refuses a stored login's refresh token

* fix(workflow-code): offline check binds a block renamed in source through its lock ident

storedUnread now takes the lock, and compile counts a source block whose ident is one vacated
lock entry's as bound (lockIdentRenames, materialize's lock-ident rule, shared with
compileSource), so a renamed block's stored container error edge or stored cycle warns offline
as the server accepts it.

* fix(sim-cli): regenerate workspace.d.ts from local workflow inputs on a workflows check

A per-folder `sim workflows source check` in a workspace directory already
compiled every workflow's Start inputs for its child-call findings but left
workspace.d.ts on the stored inputs, so a parent mapping an input added to the
child since the get failed tsc with an excess-property error. It now refreshes
workspace.d.ts the way `sim workspaces source check` does.

* fix(workflows): refuse new edge cycles in the editing engine as edge_cycle skips

The edit engine (Copilot edits, v2 operations) could create an edge that
closes a cycle, which the canvas and realtime refuse and the executor
cannot run. createValidatedEdge now runs the shared wouldCreateCycle check
and reports a refused edge as an edge_cycle skipped item. Edges the
workflow already stored are exempt, so a stored cycle survives unrelated
edits and restated connections. Publishes edge_cycle in the v2 skipped-item
enum and regenerates the OpenAPI document and CLI types.

* fix(workflow-code): declare lock and base as type aliases so they fit the open generated API types

* feat(mothership): sync the workflow-code entitlement into the generated protocol

* test(workflow-source): stamp updatedAt on direct block writes so a migrate-on-read save cannot undo them
2026-11-19 12:51:01 -08:00
Waleed e137d82691 fix(db): bootstrap Projects for development push databases that predate them (#9611)
* fix(db): bootstrap Projects for development push databases that predate them

A push-managed database with workspaces but no Project schema could never pass
the schema-push guard: push cannot backfill workspace.project_id, and the
guard refuses every unenforced Project state. Under SIM_DEV_DB_PUSH=1 the
pre-push reconciler now replays migrations 0394 and 0406 (the foundation
commits atomically with the rollout marker) and runs the registered
0032_project_membership script migration on its single session, recording it
as the migration runner does. An interrupted bootstrap resumes; every other
unenforced state still refuses with the same message.

The pinned drizzle-kit patch also adds unique constraints before foreign keys,
so a composite foreign key on a new unique constraint of an existing table no
longer fails, and in the noninteractive push policy it answers the
unique-constraint truncate prompt with its non-destructive choice.

* fix(db): push the schema before the Project migration reads it

The bootstrap ran 0032_project_membership before Drizzle pushed anything, so a
development database from before a column the migration reads (such as the
fork parent) failed after committing the expansion, on every retry.

--prepare now only replays the expansion. push.ts then runs one Drizzle push
with workspace.project_id still nullable (SIM_DB_PUSH_PROJECT_BOOTSTRAP=1),
runs the migration through reconcile-project-membership.ts --bootstrap, and
finishes with the ordinary push. The connector and rollout marker are kept out
of Drizzle's diff until the migration retires them. A fresh bootstrap also
requires that no public table carries a project_id column.

* fix(db): pin the Project bootstrap to the public schema

The replayed migration SQL and the script runner name tables unqualified, so a
connection search path that lists another schema first created the Project
foundation outside public. The refusal snapshot now also covers folders and
Projects.
2026-11-02 21:06:43 -08:00
Waleed 20fb744f2d chore(search): retire legacy search knowledge base projection rows in place (#9511)
* chore(search): retire legacy search knowledge base projection rows in place

* fix(search): keep the purge on its locked session and refresh the dev projection function

- Re-check the session advisory lock inside every purge batch: the client reconnects silently after a dropped connection, and the new backend does not hold the old one's lock
- Build the purge client without the sslmode/sslrootcert URL parameters, enforcing them as ssl verify-full; postgres.js forwards sslrootcert as a startup parameter the server rejects
- Pin the purge connection's search_path to public, pg_temp
- Reinstall sync_embedding_search() on a dev push that already recorded 0016, since push runs no versioned migration

* test(search): expect no vector candidates for a dormant search index

A Search knowledge base's chunk writes now delete its candidate rows, so an explicit vector search of one finds nothing; hybrid search still decides access on the document

* chore(search): renumber the projection retirement migration to 0449 after staging's 0448

* fix(search): lock each purge batch's rows before deleting them by tuple id

A concurrent update could move every chosen row to a new tuple id before the delete, so the batch deleted nothing and the purge reported the knowledge base finished with rows left. The batch now locks its rows in one statement and deletes them in the next, whose snapshot sees the current versions

* test(search): bound the wait for the purge to block on the updated rows

* fix(search): refuse the purge until migration 0449 is live

- --execute checks that public.sync_embedding_search has the retiring body and its embedding_search_sync trigger is enabled; before that, chunk writes keep projecting the rows a purge deletes. The dry run reports the same check
- One whitespace-insensitive matcher for the live function source, shared by the preflight and the integration parity tests; drop the unit test that compared the migration file text
- --help adds the rebuild precautions: wait out an anti-wraparound autovacuum, bound maintenance_work_mem, clean up a failed concurrent reindex

* fix(search): require the purge preflight's trigger to fire and call the retiring function

- embedding_search_sync must be enabled for ordinary writes (origin or always, not replica-only) and call public.sync_embedding_search
- Drop the redundant client port option; postgres.js reads the URL port
2026-10-31 11:48:05 -07:00
Waleed b9e6ffb5b4 improvement(auth): encrypt stored integration tokens (#9346)
* improvement(auth): encrypt stored integration tokens

* fix(settings): read permission predicates from the db-free entry

* improvement(security): detect sealed envelopes by their full shape

* improvement(auth): bind sealed tokens to their column and guard the backfill key

* improvement(auth): read the sealed context from the column definition

* fix(audit): report the line of a raw sealed column name

* improvement(audit): flag wildcard and identifier reads of sealed columns
2026-10-23 16:07:07 -07:00
Waleed 2d0c050441 fix(file-search): find an owner's stale dependencies from its dependency rows (#9024)
* fix(file-search): find an owner's stale dependencies from its dependency rows

The dispatcher's dependency reconcile and its queue-delete check tested every ready
revision of each queued owner against its dependency manifest, so a large owner cost
two full walks of its ready files per pass inside the 10s dispatch statement budget.

file_search_dependency now carries its build's owner (entity_type, entity_id), set
by a BEFORE INSERT/UPDATE trigger from the build so the deployed app's inserts stay
addressable, backfilled in 0428, and indexed concurrently by
(entity_type, entity_id, build_id). Both queries now start from the owner's stale
dependency rows and join to its ready revisions by build. A revision whose build has
no dependency rows can never be stale, and a revision only points at a build of its
own owner, so the selected rows are unchanged.

Also corrects the backfill-page comment that still named the old workspace keyset index.

* fix(db): run the push-path dependency backfill after the trigger DDL commits

* fix(file-search): type the owner-index test seed and share the queued-owner predicate
2026-10-14 08:59:11 -07:00
mzxchandra 7bbce17f80 feat: establish shared file ownership foundation (#8609)
* feat(projects): add project identity and lifecycle foundation

* feat(projects): create projects with their initial environment

* docs(projects): record project files follow-up

* docs(projects): explain project and workspace creation flows

* fix(projects): stage activation after compatible writers deploy

* feat(projects): enforce membership after the staged backfill

* fix(projects): retry writes after concurrent membership changes

* fix(projects): align integration fixtures with membership constraints

* refactor(projects): prepare compatible writers for the SQL backfill

* refactor(projects): backfill through bounded SQL migration batches

* fix(projects): clean up automatically created fixture Projects

* fix(projects): backfill only families missing membership

* fix(projects): bound the trigger installation lock window

* fix(workflows): guard restore against concurrent workspace archive

* fix(projects): keep workflow lifecycle guards at workspace scope

* fix(workflows): guard restore against concurrent workspace archive

* fix(projects): close lifecycle races and surface rollout conflicts

* fix(workflows): return not found when import loses archive race

* fix(projects): tighten rollout checks and deduplicate lifecycle validation

* test(projects): detect missing lifecycle validation calls

* test(projects): verify concurrent lifecycle lock contention

* feat: establish durable file ownership and rollout compatibility

Add canonical entity ownership while preserving legacy workspace writers.
Make storage accounting, lifecycle cleanup, search, document artifacts, and
realtime transport tolerate project-owned data before feature activation.

Keep Project file user/API/tool entry points in the stacked feature change.

* test: align file ownership fixtures and validation reports

* refactor: persist file owners with native foreign keys

* fix(db): parenthesize the file owner search index expression

* test(projects): update new workspace fixtures for enforcement

* fix(files): harden ownership lifecycle and realtime admission

* test(files): complete Project detachment database fixture

* test(files): seed required Project memberships in integration fixtures

* fix(files): resolve lifecycle and search review findings

* fix(realtime): fence file joins by owner-qualified room

* fix(files): retain shared resources after creator deletion

Keep durable workspace and Project files and file folders with a nullable live creator while preserving other creator cascades and native owner constraints. Require a creator at insertion and remove the original-creator snapshot schema and backfill.

Accept missing creator attribution throughout workspace metadata, v2 serialization and UI, and authorize canonical shared file delivery against current membership. Preserve stored version authors independently.

Exercise account departure/deletion, retained storage and history, rollback, and concurrent writes against real PostgreSQL.

* fix(files): reconcile creator handoff with project ownership

Keep shared file and folder creator references non-null by transferring them
to validated successors during departure and account deletion. Discover
Project-only references from prior departures, retain attribution while an
environment still grants access, and transfer ownership and storage payers
atomically when the final access is removed.

Recheck the selected membership under lock before handoff so a concurrent
replacement grant and its creator attribution remain untouched. Reconcile
the unreleased creator migration and restore non-null API/CLI contracts.

Integrates lifecycle 817191c757 and membership
race fix be01225427 into the file foundation.

* fix(files): preserve upload history across creator handoff

* fix(files): align lifecycle fixtures and conflict responses

* fix(files): preserve empty history and order lifecycle locks

* fix(files): retry restore names claimed by legacy writers

* fix(files): make staged cleanup safe across database failures

* fix(files): clean staged content after rejected commits

* fix(ci): resolve manual audit base from the open pull request

* fix(tests): create Project membership in desktop and CLI fixtures

* fix(files): bound affected subtrees and preserve fenced revisions

* fix(ci): pin the current pull request base branch

* fix(files): require workspace owners for workspace-scoped files

* fix(db): make file ownership provisioning replay safe

* fix(tests): restore Project enforcement fixtures after migration renumbering

* fix(tests): scope migration probes and align remaining Project fixtures

* feat(projects): prepare workspace project column compatibility

* test(projects): clean up compatibility fixtures atomically

* feat(projects): move membership to workspace column with rollout bridge

* test(projects): align transfer mocks with workspace membership

* test(projects): provision required membership in transfer unit fixtures

* improvement(workspaces): present API responses explicitly

* feat(projects): prepare legacy membership with a resumable operator tool

* fix(projects): support PostgreSQL 16 column migration

* fix(projects): allow multi-batch copies to finish

* fix(projects): support PostgreSQL 16 preparation and current fixtures

* fix(projects): reconcile memberships during schema push

* fix(projects): enforce safe schema push provisioning

* test(projects): provision newly merged workspace fixtures

* fix(projects): use the direct connection for push reconciliation

* test(billing): wait for parked transactions before racing writers

* test(billing): freeze the clock for exact deadline assertions

* fix(projects): close operator verification and contention gaps

* test(billing): stabilize member ledger timeout checks

* fix(projects): await cleanup and bound backfill artifacts

* fix(projects): honor operator cancellation and status exits

* fix(projects): reject verification of conflicted plans

* fix(projects): defer archive repair on database contention

* fix(projects): coordinate read-only maintenance commands

* ci(projects): use the standard PostgreSQL test coverage

* fix(projects): support trigger-free column rollout

* fix(projects): run bounded membership backfill before enforcement

* test(projects): verify column-only archive repair assignment

* fix(projects): retain healthy indexes during schema push

* ci(projects): use standard integration coverage for enforcement

* fix(projects): correct rollout fixtures and schema-push index

* fix(projects): reconcile assigned environments before enforcement

* fix(projects): preserve backfill repair and resume guarantees

Lock and verify effective legacy memberships before materializing reviewed
assignments and applying the shared detach policy. Reject resume reports
whose code hash differs before changing their checkpoint. Isolate local
pubsub subscriber failures so healthy archive subscribers still receive
notifications.

Extend existing CLI and real-database integration coverage for mixed
memberships, concurrent and stale connector changes, unchanged mismatched
reports, replay, and local subscriber delivery.

* test(projects): align fixture lifecycle with enforced project ownership

* test(projects): skip archive repair suite when Redis is unset

* chore(projects): normalize enforcement SQL whitespace

* feat(projects): commit membership authority before reconciliation

* fix(projects): switch membership authority after compatible rollout

* test(projects): guard optional authority fixtures explicitly

* test(projects): seed authority in billing lock-order mock

* fix(projects): bound authority barriers and verify push replay

* fix(projects): pin operator schema and pace detach repairs

* docs(projects): record native constraint rollout decisions

* refactor(projects): replace integrity triggers with native foreign keys

* fix(projects): recognize completed rollout without its marker

* fix(projects): retire rollout marker with legacy membership

* test(projects): model expansion authority in workspace move fixtures

* fix(projects): keep repair reads compatible with expansion schema

* fix(projects): retain project name for workspace archival

* docs(projects): consolidate permanent storage rules in README

* fix(files): remove stale membership imports and trigger fixture

* Bound historical Project repair fixture to compatible script migrations

* Address ownership lifecycle and realtime review findings

* Use compatible array copies for document identity sorting

* Keep foundation owned-file creation on its available billing API

* refactor: name the projects flag fallback PROJECTS

* test: cover ordinary PR and squash push audit bases

* ci: restore upstream audit base selection

* fix(db): retry public share backfill contention without losing progress

* refactor(db): fold creator lifetime guard into file ownership migration

* test(files): narrow recorded database insert values

* fix(files): preserve owned content and generated search delivery

* fix(files): preserve active artifact indexing and narrow helpers

* refactor(files): narrow ownership triggers and enforce folder edges with foreign keys

* fix(realtime): preserve replacement documents during delayed joins

* fix(files): provision composite folder keys before references

* fix(db): correct dependency patch offsets for clean installs
2026-10-13 23:53:54 -07:00
mzxchandra d7ec406d27 fix(db): optimize Project backfill and repair archived workflows (#8962)
* fix(db): reduce Project backfill round trips and scheduling limits

* fix(db): repair archived workspace workflows during Project backfill

* fix(db): retry busy Project archive repairs
2026-10-12 23:00:32 -07:00
mzxchandraandgreptile-apps[bot] eef9d29e4e feat(projects): enforce Project membership and retire the connector (#8590)
* feat(projects): add project identity and lifecycle foundation

* feat(projects): create projects with their initial environment

* docs(projects): record project files follow-up

* docs(projects): explain project and workspace creation flows

* fix(projects): stage activation after compatible writers deploy

* feat(projects): enforce membership after the staged backfill

* fix(projects): retry writes after concurrent membership changes

* fix(projects): align integration fixtures with membership constraints

* refactor(projects): prepare compatible writers for the SQL backfill

* refactor(projects): backfill through bounded SQL migration batches

* fix(projects): clean up automatically created fixture Projects

* fix(projects): backfill only families missing membership

* fix(projects): bound the trigger installation lock window

* fix(workflows): guard restore against concurrent workspace archive

* fix(projects): keep workflow lifecycle guards at workspace scope

* fix(workflows): guard restore against concurrent workspace archive

* fix(projects): close lifecycle races and surface rollout conflicts

* fix(workflows): return not found when import loses archive race

* fix(projects): tighten rollout checks and deduplicate lifecycle validation

* test(projects): detect missing lifecycle validation calls

* test(projects): verify concurrent lifecycle lock contention

* test(projects): update new workspace fixtures for enforcement

* fix(tests): create Project membership in desktop and CLI fixtures

* fix(tests): restore Project enforcement fixtures after migration renumbering

* fix(tests): scope migration probes and align remaining Project fixtures

* feat(projects): prepare workspace project column compatibility

* test(projects): clean up compatibility fixtures atomically

* feat(projects): move membership to workspace column with rollout bridge

* test(projects): align transfer mocks with workspace membership

* test(projects): provision required membership in transfer unit fixtures

* improvement(workspaces): present API responses explicitly

* feat(projects): prepare legacy membership with a resumable operator tool

* fix(projects): support PostgreSQL 16 column migration

* fix(projects): allow multi-batch copies to finish

* fix(projects): support PostgreSQL 16 preparation and current fixtures

* fix(projects): reconcile memberships during schema push

* fix(projects): enforce safe schema push provisioning

* test(projects): provision newly merged workspace fixtures

* fix(projects): use the direct connection for push reconciliation

* test(billing): wait for parked transactions before racing writers

* test(billing): freeze the clock for exact deadline assertions

* fix(projects): close operator verification and contention gaps

* test(billing): stabilize member ledger timeout checks

* fix(projects): await cleanup and bound backfill artifacts

* fix(projects): honor operator cancellation and status exits

* fix(projects): reject verification of conflicted plans

* fix(projects): defer archive repair on database contention

* fix(projects): coordinate read-only maintenance commands

* ci(projects): use the standard PostgreSQL test coverage

* fix(projects): support trigger-free column rollout

* fix(projects): run bounded membership backfill before enforcement

* test(projects): verify column-only archive repair assignment

* fix(projects): retain healthy indexes during schema push

* ci(projects): use standard integration coverage for enforcement

* fix(projects): correct rollout fixtures and schema-push index

* fix(projects): reconcile assigned environments before enforcement

* fix(projects): preserve backfill repair and resume guarantees

Lock and verify effective legacy memberships before materializing reviewed
assignments and applying the shared detach policy. Reject resume reports
whose code hash differs before changing their checkpoint. Isolate local
pubsub subscriber failures so healthy archive subscribers still receive
notifications.

Extend existing CLI and real-database integration coverage for mixed
memberships, concurrent and stale connector changes, unchanged mismatched
reports, replay, and local subscriber delivery.

* test(projects): align fixture lifecycle with enforced project ownership

* test(projects): skip archive repair suite when Redis is unset

* chore(projects): normalize enforcement SQL whitespace

* feat(projects): commit membership authority before reconciliation

* fix(projects): switch membership authority after compatible rollout

* test(projects): guard optional authority fixtures explicitly

* test(projects): seed authority in billing lock-order mock

* fix(projects): bound authority barriers and verify push replay

* fix(projects): pin operator schema and pace detach repairs

* docs(projects): record native constraint rollout decisions

* refactor(projects): replace integrity triggers with native foreign keys

* fix(projects): recognize completed rollout without its marker

* fix(projects): retire rollout marker with legacy membership

* test(projects): model expansion authority in workspace move fixtures

* fix(projects): keep repair reads compatible with expansion schema

* fix(projects): retain project name for workspace archival

* docs(projects): consolidate permanent storage rules in README

* fix(tests): seed Project membership in new staging fixtures

* Update packages/db/scripts/reconcile-project-membership.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-12 18:42:38 -07:00
Waleed 5313021d0b chore(db): drop retired storage whose readers have shipped (#8933)
* chore(db): drop retired storage whose readers have shipped

Drops tables and an index whose last readers and writers were removed in
already-released versions, makes chat.include_tool_calls NOT NULL, and
un-declares six dead columns ahead of a next-release DROP COLUMN.
embedding_keyword_tin is dropped by script migration 0031 so it runs after
0030 retires the triggers that still write it on skipped-release upgrades.

* fix(db): bound the chat lock in 0409 with a statement timeout
2026-10-12 12:50:01 -07:00
mzxchandra 34925988ee feat(projects): move Project membership to the workspace column (#8830)
* feat(projects): prepare workspace project column compatibility

* test(projects): clean up compatibility fixtures atomically

* feat(projects): move membership to workspace column with rollout bridge

* test(projects): align transfer mocks with workspace membership

* improvement(workspaces): present API responses explicitly

* fix(projects): support PostgreSQL 16 column migration

* fix(projects): allow multi-batch copies to finish

* fix(projects): reconcile memberships during schema push

* fix(projects): use the direct connection for push reconciliation

* test(billing): wait for parked transactions before racing writers

* test(billing): freeze the clock for exact deadline assertions

* ci(projects): use the standard PostgreSQL test coverage

* fix(projects): support trigger-free column rollout

* fix(projects): retain healthy indexes during schema push

* fix(projects): correct rollout fixtures and schema-push index

* fix(projects): switch membership authority after compatible rollout

* test(projects): guard optional authority fixtures explicitly

* test(projects): seed authority in billing lock-order mock

* fix(projects): bound authority barriers and verify push replay

* docs(projects): record native constraint rollout decisions

* fix(projects): recognize completed rollout without its marker

* test(projects): model expansion authority in workspace move fixtures
2026-10-10 14:24:42 -07:00
Theodore Li 1bb9e86673 fix(tables): log row writes to the change log instead of locking the table definition row (#8765)
* fix(tables): log row writes to the change log instead of locking the table definition row

* fix(tables): lock the change log before the dev count reconcile, and tighten the held-row test

* test(tables): name the renumbered change-log migration
2026-10-08 18:08:47 -04:00
Vikhyath Mondreti 0f5590d8c9 fix(db): retire unused keyword search projections (#8810)
* fix(db): retire unused keyword search projections

* fix(db): retire keyword writers before schema push

* fix(db): require approval before retiring push writers
2026-10-08 14:25:19 -07:00
Vikhyath Mondreti 491ab88db3 chore(search): add paced projection replacement and data retirement (#8534)
* chore(search): add paced projection replacement and data retirement

* chore(search): keep retirement usage in the CLI

* fix(db): fence schema push and require direct retirement sessions

* fix(db): preserve test connection URL parameters
2026-10-01 13:24:58 -07:00
Waleed 66e5705b00 fix(tables): match unique JSON values exactly and validate row writes against the live schema (#8394)
* fix(tables): match unique JSON values exactly and validate row writes against the live schema

- Unique checks and the upsert conflict probe matched JSON objects and arrays by containment, so
  `{"a":1}` counted as a duplicate of `{"a":1,"b":2}` and upsert could overwrite a row that only
  contained its target. They now also require exact jsonb equality, keeping containment as the
  GIN-indexed leading clause; JSON values take per-value locks like other types
- Row writes validated against a schema snapshot read before their transaction, so a concurrent
  make-unique, make-required, retype, or column delete could commit violating data. Each write
  now reads the live schema under the table's schema lock (shared) through
  `user_table_schema_for_write`, in the statement it already runs first, and validates against it
- The background update runner derives each batch's patch from the raw payload against the live
  schema, through the same helper as the inline bulk update, and refuses unique and required-null
  patches under the lock

* fix(tables): install the schema guard for db:push, refit rows from raw input

- user_table_schema_for_write moves from Drizzle migration 0391 to script
  migration 0026, which db:push runs too. A db:push database (local dev,
  the CI push provision) never applied 0391, so every guarded row write
  failed there. The journal ends at 0390 again; the function body and its
  comments are unchanged.
- A writer that finds the schema moved rebuilds the row from the caller's
  raw input instead of the value it coerced against its snapshot, so a
  "007" sent while a column changed from number to text is stored as
  "007", not "7". This covers insert, upsert, update, batch update and the
  import batch.
- The refit re-checks the row's size, which a coercion to a wider type can
  grow past the limit after the pre-lock check passed.

* fix(tables): re-check update batches under a moved schema, own-key reads

- The background update runner re-reads a batch's rows inside the batch
  transaction and re-validates them merged with the re-derived patch when
  the schema moved since the page was checked, as the inline bulk update
  does; an unchanged schema adds no query. updatePageByIds takes an async
  per-batch hook with the transaction for this.
- batchInsertRowsWithTx returns the definition it validated against, and
  batchInsertRows dispatches its insert triggers with it.
- Row cells and patch keys are read as own properties (Object.hasOwn), so a
  legacy column keyed by a prototype name such as `constructor` is not
  seen in rows or patches that do not hold it.
- The long schema-wait test asserts the write is waiting on the schema lock
  before the holder commits.

* fix(tables): read the remaining row cells by own key in bulk validation, replace dedupe, and the upsert probe
2026-09-28 19:29:40 -07:00
Waleed 185650fe47 improvement(knowledge): maintain keyword projections only for search indexes (#8333)
- Since #8314, workspace knowledge search ranks on `embedding`/`document`. The only live reader of `embedding_keyword_search` and `embedding_keyword_tin` is dormant indexed search, and only for bases that are search indexes. Yet every chunk write still upserted a keyword row, ran a Tin `DELETE` on insert, and every document insert fanned an ACL/connector sync out to the projections
- Script migration `0025_scope_keyword_projections`, all `CREATE OR REPLACE` in one transaction with the 0024 lock-timeout retry:
  - `sync_embedding_keyword_search` takes the shared membership lock and writes keyword rows only for `is_search_index` bases. On an update that moves a chunk out of a search index, it deletes the chunk's row
  - A new flip trigger backfills a base's keyword rows when it becomes a search index and deletes them when it stops being one, under the exclusive membership lock. It is separate from the Tin flip trigger, which only exists where Tin is installed. Its upsert skips unchanged rows
  - The Tin chunk trigger skips its `DELETE` on insert, since a new chunk can't have a Tin row
  - `projection_source_acl_sync` becomes `AFTER UPDATE OF connector_id, acl ... WHEN` the value actually changed. A new document has no chunks yet (FK), so the insert arm never matched anything
- The projector's keyword page writes only for search-index bases, keyed on the base flag
- Fresh installs, `db:push`, and late Tin adoption end with the same trigger definitions: 0019 installs the final guarded, key-share-locked Tin triggers, and 0025 re-runs after 0016. A `db:push` re-run of the legacy 0016 backfill may refill keyword rows for non-search bases; they're unread and left in place like the existing ones
- Both adoption backfills read their chunks `FOR KEY SHARE`, so a chunk delete racing an adoption is waited out instead of failing it
- Rollback floor: v0.9.1 and earlier ranked workspace keyword search through `embedding_keyword_search`. Once 0025 has run, don't roll back below v0.9.2, and self-hosters should upgrade through v0.9.2 or later
- Existing keyword rows for non-search bases are left in place (unread) and removed separately
2026-09-26 13:11:42 -07:00
Waleed 4e17dceda0 chore(tests): consolidate test patterns — shared Vitest base, central @sim/testing mocks, check:test-patterns, lean agent docs (#8309)
* chore(tests): consolidate test patterns — shared Vitest base, central @sim/testing mocks, check:test-patterns, lean agent docs

* fix(tests): discover central mocks from their declarations and accept the async-import form

* fix(tests): address review — mock fidelity, docs, and guards

* docs(tests): restore the heavy-graph, global-mock and permanent-implementation rules and small doc pointers
2026-09-25 16:36:13 -07:00
Waleed 9050e69caa chore(tests): remove low-signal tests and consolidate the testing setup (#8295)
* chore(tests): remove low-signal tests and consolidate the testing setup

* fix(tests): address review — shared disposable-DB guard, optional Redis suite, restored client-info wire contract
2026-09-25 09:03:41 -07:00
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>
2026-09-23 16:41:27 -07:00
Waleed 7481589b19 feat(knowledge): project document ACL and chunk changes asynchronously (#8199)
* feat(knowledge): project document ACL and chunk changes asynchronously

Document ACL/source changes and chunk writes mark their document in
knowledge_projection_dirty (one upsert with a generation bump) in the
writer's transaction. A knowledge projector converges every search
projection per document in short pages bounded by chunk rows, several
documents at once, and removes a mark only on the generation it read.

Writers that declare sim.projection_mode = 'async' skip the synchronous
embedding and document fan-out triggers. The processing commit and every
connector-lease ACL page declare it while the knowledge-async-projection
flag is on; every other writer, and every release before this one, keeps
writing projection rows itself. Marks are written in both modes so a
projector pass can never settle over a concurrent synchronous write.
Migrations 0021-0023 keep their trigger body; 0024 alone installs the
marking.

Search decides a marked document's rows on the document itself, so a
pending projection never admits a revoked grant. A document that moved
sources joins the new source's per-source ranking after its pass.

The projector runs as a Trigger.dev task, requested after writes and
swept every minute while there is work, or in-process without
Trigger.dev. A pass opens one worker per mark up to
KB_CONFIG_PROJECTION_CONCURRENCY. The separate source/ACL backfill is
folded into it behind knowledge-projection-fill.

* fix(knowledge): keep projection guards out of historical migrations

Restores 0016, 0019 and 0021 to their staging bodies; 0024 alone
re-creates the projection triggers with the mode guard, in the same
transaction that installs the marks. The fill starts only inside the
pass budget and reports what it marked as remaining. Passes dispatch
to Trigger.dev by the rule document processing uses, and the inline
coalescer clears its running flag in the same step it reads the owed
flag. Bumps the Helm chart for the projection cron job.

* test(knowledge): count projection requests per connector ACL case
2026-09-23 03:25:13 -07:00
Waleed 338e39ec74 fix(jobs): classify transient database failures once for background retries (#8194)
* fix(jobs): classify transient database failures once for background retries

- classifyDatabaseFailure in @sim/utils/errors: capacity / conflict / connection / permanent
- shared Trigger catchError decision helper with minute-scale database backoff
- workspace file search, document processing, connector sync, and the 0021 backfill adopt it
- a scheduled document retry leaves the document pending instead of failed
- a transient database failure no longer counts toward connector auto-disable

* fix(jobs): escalate database retries without spending the breaker, cover members mode

- connector and members-mode syncs climb the failure ladder by the failed-run streak read from their run logs; database failures never advance the auto-disable counter
- classify 25P03 as capacity and ECONNREFUSED/EHOSTUNREACH/ENOTFOUND/EAI_AGAIN (with a query) as connection
- in-process document processing keeps recording database failures as failed, documented
- offer Retry for a pending document whose dispatch or deferred retry is past the retry API's grace
- correct the processing task's retry-ceiling comment

* revert(knowledge): drop the stale-deferred Retry action and its wire fields

Restores the document list, contract, serializer, and Retry condition to staging; Retry stays failed-only.

* fix(knowledge): fail an uploaded document whose scheduled database retry never ran

- the deferral write and a deferred-retry-check outbox event commit together for uploaded documents
- the check fails the document only if the same deferral is still pending, overdue past the queue grace, and no run is live; otherwise it rechecks without spending an attempt, bounded by the recovery window
- a database deferral stamps processingQueuedAt when unset, so a dispatch cannot claim the row as never-queued during the retry window

* fix(knowledge): keep the deferred-retry watchdog alive through database failures

A transient database failure while checking postpones the check without spending an attempt, paced by how overdue it is and capped at the recheck interval, until a terminal bound past the recovery window; other errors, and any error past that bound, spend attempts as before.

* fix(jobs): progress-aware connector database retries, stuck-sync signal, strict query shapes

- the database-failure streak counts only failed runs that made no progress; a run that wrote documents (or completed a member) retries in minutes
- ten zero-progress database failures in a row log an alertable error; the connector is never disabled for them
- the classifier's query check matches only Drizzle's query error and the postgres.js query error shapes, so a client error carrying its own query stays a source failure

* fix(jobs): bound the retry-history read, count member purges, match driver connection errors

- the connector run-history read runs under short statement and lock timeouts and falls back to this run alone
- members-mode progress counts lifecycle purges (docs_purged in the run log)
- postgres.js connection codes count only on an error the driver built, or under a query error; the driver's query signature is its four own properties, which a refused connection carries with no SQL yet
- real-error PostgreSQL test for terminated transactions, refused connections, and an ending pool, wired into CI
- knowledge-processing tests use the static task import

* fix(jobs): classify ENETDOWN, ENETRESET and ENETUNREACH on a database query as connection failures

* test(knowledge): import the connector retry helpers statically
2026-09-23 00:26:19 -07:00
Waleed 1c597fec1a fix(db): retry migration lock timeouts within a time budget instead of eight attempts (#8190)
* fix(db): retry migration lock timeouts within a time budget instead of eight attempts

* fix(db): measure the migration lock budget on a monotonic clock and never start an attempt past it
2026-09-22 22:42:41 -07:00
Waleed 9573ecc666 improvement(knowledge): resolve connector and member state once per search (#8040)
* improvement(knowledge): resolve connectors once and rank each source in its own index

Two costs dominated organization search, and both came from deriving per candidate
what is true of a whole source.

Connector state — deletion, archival, a pending access rewrite, the organization's
integration approval, the access mode — is a fact about a connector, so a search
resolves it once and filters candidates by the resulting ids. For a member reading
~25k documents, the candidate predicate's connector lookup drops from one per
document examined to one per document of a source that still needs this request's
live proof: 24,571 evaluations to 610, and the access check from ~390ms to ~160ms.

Ranking then follows sources. pgvector post-filters, so one walk over every source
spends its scan budget on the sources a caller cannot read: measured recall for a
member reading half an index ranged from 0.00 to 1.00, averaging 0.80 over nine
queries, two of which returned none of the exact page. A member of a source reads
essentially all of it, so that source is walked through an index covering it alone,
built after a sync grows it past the threshold and dropped with the connector.
Every other source is sliced — mirrored permissions give a caller their own mail,
their own files — and those slices are ranked exactly in one statement. Recall over
the same queries rises to 0.95 with none below 0.75.

Retrieval never waits on an index existing: a source without one is ranked exactly,
so a build that is skipped, fails, or has not happened yet costs recall nothing.

* improvement(knowledge): resolve the caller's member identities with the rest of the plan

A members-mode document is readable while one of the caller's active members observes
it, freshly, and which members those are is a fact about the caller. Resolving them
with the connectors — one query, one plan — turns each candidate's check into a lookup
on the observation key instead of a join to the member behind it, and lets the vector
planner read the sources the caller belongs to from the same resolution rather than
asking again.

* chore(knowledge): drop the stage the access plan made unnecessary

* improvement(knowledge): resolve live source grants once per search

- ask a live-proof source for the caller's grants once, before either leg, and only when the scope actually reads one, instead of per candidate page
- drop the per-page source exclusion and refill loop that followed from the per-page proof
- read search result metadata under the stored predicate the rows already passed
- end candidate paging on a short page whether or not the leg reorders its results
- batch the embedding_search.connector_id backfill in independently committed keyset pages, matching the other projection backfills

* test(db): register the projection-source script migration in the push and registry expectations

* fix(knowledge): walk a saturated slice and re-read connector state at hydration

- fall back to a graph walk when the sliced sources hold more readable documents than one exact ranking may enumerate, since that enumeration has no order and would otherwise rank an arbitrary subset
- read content under the full predicate, which re-reads each connector's own lifecycle and approval, so a source deleted, archived or unapproved mid-search stops answering at the gate that returns content

* improvement(knowledge): ask a live source for grants only when one of its candidates is read

Resolving every gated source's grants up front charged a search for sources it never ranked. The grants are now resolved on first need — when a page of ranked candidates actually contains one of those sources — and memoized for the rest of the search, so a scope that ranks none never asks and one that ranks many asks once.

* fix(knowledge): rank uploads without a sliced source and bound the grant resolution

- always run the slice that carries connectorless uploads; a caller who is a member of every indexed source had no sliced source beside them, and their uploaded documents were never ranked
- resolve live source grants in the provider's bounded pages, so a scope holding more gated sources than one page no longer fails
- drop a source's index only while it is invalid, so overlapping syncs cannot have one remove the index the other just built
- fan a document's new source out to the chunks a search can reach, which the document lookup index covers, and take the source again when a chunk is enabled

* fix(knowledge): refill after a denied gated source, reserve the index build's session, lock the backfill's documents

- once a live proof shows the caller does not hold a gated source, rebuild the candidate pages without it, so its candidates no longer hold the slots of sources the caller can read
- run the source index build on one reserved connection, so its memory setting and its reset apply to the session that builds
- share-lock a page's documents before copying their source, so a detachment in flight waits for the page and then fans its own change out through the trigger

* fix(knowledge): start the scan budget over when the pages are rebuilt

The candidates already seen before a denied source was known are skipped when the pages are rebuilt, but they still counted against the scan budget, so a refill could exhaust it before reaching the readable candidates ranked after the denied source.

* fix(knowledge): serialize the projection source with its document

- the set trigger reads the document under FOR SHARE, so a projection write and a document's connector change cannot interleave and leave the older value
- the backfill writes a chunk's source only for the document it read that source from; a chunk moved meanwhile is left to its new document's trigger

* improvement(knowledge): choose the vector plan by the caller's reach

- a caller who reaches at least a quarter of the bases' documents walks the whole graph once, as before: pgvector post-filters, so at that share almost every neighbour the graph visits is theirs and one walk is the cheapest exact answer; searching each source on its own only helps a caller whose reach is a small share of the index
- the share is counted once against that bound when the probe saturates, and remembered with the saturation
- a bounded caller who is a member of an indexed source walks that source instead of ranking it exactly with the rest

* fix(knowledge): search a broad caller's sources when their whole-graph walk comes back short

Reach is counted from token overlap, which every readable document has but which connector state, requirement clauses or observations can still refuse. A caller the count called broad whose walk then underfills was not broad: their sources are searched on their own instead, so the misjudgement costs one walk rather than their neighbours.

* fix(knowledge): read result metadata under the scope the results were read under

Retrieval reports the scope its content was read under — with the live grants it resolved, when a gated source's candidate was read — and the metadata lookup applies the full read predicate under that scope. A gated source's result keeps its name and URL; a revoked one loses them here as it did at hydration.

* fix(knowledge): keep what a short broad walk found when searching its sources runs out of budget

The per-source search adds to the walk's candidates rather than replacing them, and if it is cancelled by the leg's budget the walk's candidates still stand.

* fix(api): fail a v1 knowledge search whose retrieval ran out of time

v1 cannot express an incomplete search, so a leg that reached its deadline fails the request, as it did before the route read the retrieval result directly.

* improvement(knowledge): mirror each chunk's source and ACL onto the ranking projections

- embedding_search and embedding_keyword_tin carry connector_id and acl from their document, set by each projection's own trigger under a share lock and fanned out when a document changes hands or its ACL is rewritten
- script migration 0021 installs both, backfills both projections in independently committed keyset pages, and builds a partial GIN index on each projection's acl concurrently
- projectionCandidateAccessCondition decides candidate readability on the projection row alone, admitting a superset of the per-row document predicate; a real-database test asserts it never refuses what that predicate admits

* improvement(knowledge): decide candidate readability on the ranking row

Once a search has resolved its connectors, the vector walks and the Tin keyword window test the caller's access on the row they score — the source and ACL are mirrored there — instead of joining document per visited or ranked chunk. The graph is no longer stalled by a document lookup per candidate, and a keyword window of mostly unreadable chunks costs an array test per row. Content is still read under the full predicate at hydration.

* improvement(knowledge): rank the sliced sources on the projection row

The sliced sources' readable chunks are enumerated by the projection's ACL index and ranked exactly in one statement, with the saturation bound counted in the same statement; the per-document enumeration through document is gone from the per-source path.

* improvement(knowledge): let a resolved scope's reach choose its plan without enumerating documents

- with readability decided on the projection row, a resolved scope never needs its readable documents enumerated ahead of ranking: its reach alone chooses between one walk over the whole graph and a search of each source, and is remembered per bases and tokens
- the reach share's denominator is the planner's estimate of the bases' documents rather than a count of them
- a resolved scope's keyword leg ranks with Tin and decides readability on the ranked row whether or not its reach is bounded

* improvement(knowledge): walk every source a caller reads whole; one keyword window for a resolved scope

- a source earns its own vector index at a thousand documents: once readability is decided on the row a walk costs a few milliseconds whatever the source's size, where ranking it exactly grows with it
- a resolved scope's keyword page takes one wide Tin window and leaves a short page short, rather than widening through narrower windows and then ranking every match

* improvement(knowledge): widen a broad reader's short walk; keyword windows follow reach

- a broad reader whose whole-graph walk comes back short walks again with a wider scan instead of searching each source: their own sources are already in the walk, and enumerating their readable chunks is a bitmap over most of the index
- a broad reader's keyword page widens through the narrow windows as before; only a narrow reader takes the wide window alone

* improvement(knowledge): index the projection by source; rank a narrow reader's keyword window once

- a partial btree on embedding_search.connector_id lets the planner lead with a few sources where the caller's tokens alone would match most of the index, which is what made a small slice cost a bitmap over all of it
- a narrow reader's keyword page returns several pages' worth of readable rows from one wide ranking, instead of ranking the window again for each page

* improvement(knowledge): widen a broad walk only when it is short of the result need; a narrower keyword window for narrow readers

A walk that found hundreds of candidates needs no rescue; widening it spent the leg's budget and lost them. The wider walk now runs only when the first found fewer candidates than there are results to return. A narrow reader's one keyword window is 20k rows: a few percent of it fills their page several times over, at less than half the widest window's cost.

* fix(knowledge): hydrate an oversized ranking page in slices, only as far as the results need

A ranking may hand back more candidates than one hydration should read — a narrow reader's keyword window is ranked once for several pages' worth — so a page is drained in slices of the result need and what is left waits, unread, until the results still need it.

* fix(knowledge): count a candidate as considered only once its slice is read

The slices a refill discards were never read, so the rebuilt pages may hand their readable candidates back.

* fix(knowledge): pair an observer with its connector, settle the per-source fan-out, serialize a source's index build

- an observation vouches for a document only from a member of the document's own connector: a document that changed hands keeps its old observations, which no longer carry it as a candidate
- a source whose search runs out of budget marks the leg partial while the other sources' results stand
- a source's index is built under a session lock on the one reserved connection that also builds it, so two syncs cannot interleave the invalidity check and the drop; 0021 drops an invalid leftover before building, and analyzes both projections after the backfill
- a broad reader's walk widens when it found fewer candidates than the smallest pool worth reranking

* fix(knowledge): give a broad reader's wider walk half of what the leg has left

The rerank and hydration of whatever is found — the first walk's candidates at least — keep the rest, so a wider walk that runs out of its share can no longer take the leg's results with it.

* improvement(knowledge): let an on-row walk run to its cap, widen a narrow reader's keyword window stepwise, apply scan settings with the deadline

- an on-row walk keeps walking, up to a 100k-tuple cap, until its limit is met; the separate wider walk and its diagnostic are gone
- the on-row predicate tests the mirrored ACL alone — a member's source is no longer admitted whole, so a document re-owned after its chunk was mirrored is refused at the row
- a reach count that ran out of time decides that search only; it is not remembered
- a narrow reader ranks the narrowest keyword window first and widens to the wide one only when the page is short; resolved scopes leave the widest window short instead of ranking every match
- the HNSW scan settings ride in the deadline statement, one round trip fewer per vector statement

* test(knowledge): expect the scan settings to share the deadline statement
2026-09-20 09:24:33 -07:00
Waleed 4dd929aa54 improvement(utils): adopt toRecord and toRecordOrNull over inline record coercions (#8053)
* improvement(utils): adopt toRecord and toRecordOrNull over inline record coercions

* improvement(utils): route the remaining record-coercion helpers through toRecord

The first pass matched one operand order, so six exact equivalents written
`x !== null && typeof x === 'object'` survived — two of them beside a sibling
the pass had already deleted. Domain-named wrappers keep their names and
delegate, matching the microsoft-teams client that already did.
2026-09-19 19:04:44 -07:00
Waleed eaa9ff08e1 improvement(knowledge): rank organization keyword search with Tin (#8007)
A member who reaches more of an organization search index than an exact
ranking can afford searched keywords through the GIN projection, which
scores every chunk matching the term before access is checked, so a common
word cost seconds. Where the database provides the tin extension, a BM25
projection of search-index chunks is kept by embedding and knowledge-base
triggers, and the keyword leg ranks with Tin first and checks access only on
the top of that ranking, widening the window while too few ranked chunks are
readable and leaving a page to GIN if the widest window cannot fill it.

The query is analyzed by the same websearch_to_tsquery as the GIN path and
translated to TINQL; shapes TINQL cannot express keep GIN. The path is gated
by the knowledge-tin-keyword flag, a valid Tin index (built only after the
backfill completes), and every base being a search index. Script migration
0019 installs the projection only where tin is available and creatable, so
self-hosted databases keep an empty table and the GIN path.
2026-09-19 10:06:05 -07:00
Waleed 4d64b377a1 fix(knowledge): store connector sync schedules at millisecond precision (#7966)
* fix(knowledge): store connector sync schedules at millisecond precision

The scheduler round-trips next_member_sync_at through a JavaScript Date and
claims the run by matching the value back exactly. Date carries milliseconds
while PostgreSQL stored microseconds, so a schedule written in SQL rather than
by the application became unmatchable the moment it landed on a fractional
millisecond: the connector stayed permanently due, every claim was refused, and
its members never synced.

Narrow both connector schedule columns to timestamp(3) so the two ends compare
the same value. The rewrite also rounds the stored values, so an already-wedged
row recovers on the next scheduler tick.

Also stop the claim diagnosis from asserting a queued run it cannot see — it now
reads the lock token and says so plainly when no condition explains the refusal,
which is what let this hide as ordinary contention.

* test(knowledge): pin the schedule rewrite's repair of already-stored rows

Scope the column-precision query to the test schema. It matched on table name
alone, so in CI — where the database already holds the migrated public table —
it saw four columns instead of two and failed. A local run passed because the
throwaway schema was the only place that table existed.

Write the sub-millisecond schedule before applying the migration rather than
after, so the test pins the rewrite rounding an already-wedged row, not just the
narrowed column refusing new ones. Without the migration it now fails on exactly
that claim.
2026-09-18 00:12:05 -07:00
Vikhyath Mondreti 783cf1715f chore(db): drop retired usage columns and compatibility scaffolding (#7868)
* chore(db): drop retired usage columns and compatibility scaffolding

* fix(db): forward force flags for local and dev schema pushes
2026-09-15 17:25:21 -07:00
Waleed c3f8140b6e feat(sso): let an organization keep several identity providers on one domain and choose the primary (#7836)
* feat(sso): let an organization keep several identity providers on one domain and choose the primary

* chore(db): remove the SSO primary provider migration ahead of merging staging

* fix(sso): regenerate the primary provider migration after staging, and harden provider switching
2026-09-14 18:52:42 -07:00
WaleedandClaude Fable 5.1 4d5e4aa8a7 feat(sso): several identity providers per organization (#7652)
* feat(sso): several identity providers per organization

An organization can now run more than one identity provider, one per
verified domain: Okta for eng.acme.com and Entra for acme.com, for example.
The schema already allowed several rows; the product could not show, pick,
or remove them.

- Sign-in names the provider explicitly. A new POST /api/auth/sso/resolve
  maps an email domain to the provider that serves it, preferring a verified
  domain and breaking ties on provider id, so routing no longer depends on
  the SSO plugin's unordered domain lookup.
- Registration refuses a second provider on a domain the caller already
  routes (SSO_DOMAIN_ALREADY_ROUTED), keeping email-domain routing
  deterministic. The check shares the existing cross-tenant domain read.
- DELETE /api/auth/sso/providers/[providerId], owned by Sim since the
  plugin's delete-provider stays blocked: organization owners and admins
  remove an organization provider, the creator a personal one. Accounts and
  memberships the provider admitted are untouched.
- The provider list is ordered by provider id; the settings sign-in tab
  lists providers, opens one by URL (`provider=`), adds another, and
  deletes with confirmation. JIT admissions record the provider id in
  their audit metadata.
- Docs describe multiple providers, domain routing, and deletion.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CkZjSKgtFdE5mzsQ31gGLY

* improvement(sso): verified multi-provider flow and cleaner provider settings

- Registration guard uses the same domain expression as sign-in resolution and domain verification
- Self-host registration script stores the normalized provider domain
- Sign-in reports "no provider" only on 404; other failures keep the generic message
- Settings: canonical back slot and title on provider detail and form, Edit then Delete, no duplicate Open in the row menu, awaited list refetch before navigating, replace-history on close, unsaved-changes guard on back
- Docs: state that an organization can use more than one identity provider

* fix(sso): make one provider per domain hold at the database and resolve only verified providers

- Partial unique index on sso_provider (organization_id, normalized domain), built concurrently after a duplicate pre-check; a lost race maps to the same 409 as the pre-check
- Sign-in resolution returns only providers whose domain is verified
- Settings controls follow the organization owner/admin model the server enforces, not the creator

* fix(sso): support registered provider IDs in settings

* refactor(sso): keep provider deletion in details

* chore(db): remove SSO migration before staging update

* chore(db): regenerate SSO migration after staging

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 11:21:10 -07:00
Waleed 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.
2026-09-07 17:23:32 -07:00
Theodore Li 2795922177 feat(resource-policies): add credential group access policies (#6892) 2026-08-27 18:57:47 -04:00
Waleed 32fbcdcfe1 improvement(db): finish workspace file size cutover (#7112)
* improvement(db): finish workspace file size cutover

* test(db): update workspace file size fixtures

* fix(db): cover dev size cutover

* fix(db): fail closed on missing file sizes
2026-08-26 12:27:13 -07:00
Theodore Li 4c0bd944dc feat(slack): launch v2 triggers and backfill custom bots (#6873)
* feat(slack): launch v2 triggers and backfill custom bots

* fix(slack): propagate legacy webhook dispatch failures

* fix(slack): continue shared legacy webhook fanout

* fix(slack): acknowledge filtered webhook deliveries

* fix(slack): finalize custom bot migration rollout

* fix(slack): dedupe migrated bots per workflow

* fix(slack): harden custom bot rollout

* fix(slack): acknowledge permanently ignored deliveries

* fix(slack): retry failed webhook deliveries
2026-08-25 14:11:02 -04:00
Waleed c49751b32e perf(prefetch): stop calling our own API over the wire during server render (#6657)
* perf(prefetch): read the data layer instead of calling our own API over the wire

Four server-render prefetches went out over HTTP to our own routes. With
INTERNAL_API_BASE_URL unset in prod, getInternalApiBaseUrl() falls back to the
public base URL, so each was RSC -> public HTTPS -> load balancer -> back into
the app, awaited inside the render with a second round of auth.

- /home fetched the workflow folder list that the workspace layout had already
  fetched, under the identical query key. Since getQueryClient() builds a new
  client per call on the server, the two never deduped: same data, twice a
  request, once directly and once over the wire. Dropped; the layout's entry
  already hydrates it.
- /home cached raw route JSON under workspaceFilesKeys.list, while
  files/prefetch.ts seeds that same key from listWorkspaceFilesWithShares. The
  contract declares the date fields z.coerce.date(), so consumers hold Dates —
  a file record's type depended on which page the viewer landed on. Now reads
  the same function files/prefetch.ts does.
- tables and knowledge folder reads now call listFoldersForWorkspace, matching
  the sidebar prefetch.

These reads carry no authorization of their own, so each surface proves the
viewer through getWorkspaceHostContextForViewer first and caches nothing when
it fails, leaving the client fetch to reach the route for the real 403. Both it
and getSession are cache()d and already resolved by the layout, so the proof
costs no extra queries.

Left on the wire, deliberately: the tables and knowledge lists, whose cached
shape is the serialized wire shape, and pinned items and members, which have no
exported data-layer function.

* improvement(prefetch): skip the viewer proof when there is no session

Passing an empty-string userId ran a real permission query that could only
return null. Take an optional userId instead and skip straight to the
unauthorized path, matching how the home prefetch is called.

* perf(prefetch): finish removing self-HTTP prefetches and delete the legacy helper

Converts the last four server-render prefetches that called our own API over
HTTP, and deletes prefetch-internal-fetch.ts now that nothing imports it.

- knowledge bases: runs the route's own listInternalKnowledgeBases use case
  with a principal from the same internalSessionAuth policy the route declares,
  then projects through the same presenter and contract. Not a bypass of the
  application boundary — the same path, called in-process.
- tables: extracts the route's list projection into lib/table/wire.ts as
  toTableListItem, which the route and the prefetch now both call. This matters
  because listTablesContract's response schema is a passthrough z.custom, so a
  client fetch caches the route's JSON verbatim. Seeding listTables() directly
  would have put Date objects and the server-only metadata field under a key the
  hook never sees them on.
- pinned items: extracts the route's inline query into lib/pinned-items/queries.ts
  as listPinnedItemsForUser, which the route now calls too.
- workspace members: getWorkspaceMemberProfiles already existed; the prefetch
  calls it directly.

normalizeColumn moves from app/api/table/utils.ts to lib/table/wire.ts with ten
importers repointed. That also removes a pre-existing lib/* -> app/api/* boundary
violation in lib/table/import-runner.ts. No response shape changes: the v1/v2
edits are import-path moves only.

Every converted read proves the viewer first and caches nothing when that fails,
so an unauthorized viewer's client fetch still reaches the route for the real
403. Authorization equivalence was checked by unfolding both paths to
checkWorkspaceAccess rather than assumed.

* improvement(prefetch): collapse the duplicated folder prefetch and unify the call shape

- Extract prefetchResourceFolders. The same eight-line folder prefetch was
  written three times, varying only by resourceType, with the key, stale time
  and mapper kept in sync by hand.
- Adopting it removes the conditional spread from the tables and knowledge
  prefetches. Tables can now early-return, matching prefetchFilesBrowser:
  prefetchResourceListChrome already self-guards on the same cached host
  context, so a null context meant the function did nothing either way.
- Take userId as string | undefined everywhere and guard inside, so every
  prefetch module has one calling convention rather than two.
- Export toWireTimestamp and use it for the create-table response's own copy of
  the same idiom, and drop a cast that the extraction made dead: the parameter
  is already TableDefinition, whose schema is TableSchema.
- Read params and the session concurrently on the tables and knowledge pages,
  matching the files page, and drop TSDoc that restated each prefetch's own.

* fix(prefetch): keep the tables list on its route and cut the executor edge

Reading listTables from a page prefetch put the executable tool registry into
the Tables page server graph — ~4,700 modules, which check:tool-registry-boundary
rejects. lib/table/service reaches workflow-columns by several independent
paths (directly, and through jobs/service and rows/service), so severing one
edge is not enough; untangling that belongs in its own change.

- The tables list goes back through GET /api/table, with the reason recorded so
  the next person does not repeat the attempt. Folders and chrome on that page
  stay on the data layer.
- stripGroupDeps moves to its own leaf module. It is a pure projection over a
  WorkflowGroup, but living beside the group runtime meant every importer of
  lib/table/service paid for the executor to get it.

Net effect on the Tables page graph: 2,186 modules to 1,742.

* perf(prefetch): finish the migration, delete the legacy helper, ratchet page graphs

Answers the question the previous commit left open: the tables list did not have
to stay on HTTP. lib/table/service reached the executor through
jobs/service -> rows/service -> workflow-columns, for one symbol.
pendingDeleteMask is a delete-visibility SQL clause with no executor
involvement, so it moves to its own leaf and that chain is cut. The tables
prefetch now reads the data layer like every other one, and
prefetch-internal-fetch.ts is deleted: nothing in the app calls its own API over
HTTP during a server render any more.

stripGroupDeps likewise moves to a leaf rather than being re-exported through
workflow-columns, so its importers no longer pull the executor to get a pure
projection.

React Query mechanism fixes, all found by audit:
- settings/[section] fired two prefetches without awaiting them. Only a settled
  query is dehydrated, so those were shipped mid-flight; a rejection hydrated
  into an error state retryOnMount: false never retries, leaving the panel
  broken for the session. Awaited now, and the pending-dehydration opt-in is
  removed since nothing streams.
- The viewer profile was prefetched by both the layout and the settings page.
  Separate server QueryClients mean that was a real second read per request.
- prefetchSubscriptionData was dead, and hand-rolled an unannotated raw fetch.
- retry is scoped to the browser. Query core defaults it to 0 on the server;
  stating one value for both opted awaited prefetches into a retry backoff. The
  gcTime default is dropped entirely — 5 minutes is already the browser default,
  and setting it explicitly overrode the server's Infinity, leaving a live timer
  and payload per request.

check:tool-registry-boundary now also ratchets per-page module counts against a
committed baseline, attributing a regression to the import that caused it via a
dominator tree. It caught a +444 regression in this branch by hand; it would
have caught it in CI. Its import regex also missed bare side-effect imports,
so `import '@/tools/registry'` could have slipped past it entirely.

Prefetch guidance added to .claude/rules/sim-queries.md.

* fix(prefetch): correct the extracted module's db imports and stale rationale

Audit findings from the migration.

- pending-delete-mask imported its schema tables from @sim/db rather than
  @sim/db/schema, which the module it came from was careful to split. The
  global test mocks are bound per-entrypoint and only the schema mock exports
  tables, so every suite that reaches pendingDeleteMask would have failed on a
  missing mock export. Restored to the original convention, and the same split
  applied to the new pinned-items queries module before it grows a test.
- The settings prefetch and page justified awaiting with a mechanism this
  branch removed — pending queries being shipped with their promise. Only a
  settled query is dehydrated now, so an unawaited prefetch is dropped from the
  payload entirely. Same conclusion, correct reason, and no longer contradicting
  the rule this branch added.
- Removed the doc block left orphaned above validateSchema when stripGroupDeps
  moved out of workflow-columns.

Skill projections regenerated after trimming the boundary skill.

* chore(table): drop a section separator comment

Separators like these are non-TSDoc decoration that CLAUDE.md already rules
out. This is the only one in a file this branch touches; the rest of the repo
is swept separately.

* chore: remove section separator comments

CLAUDE.md already rules these out ("No ==== separators. No non-TSDoc
comments"), but 546 of them had accumulated across 48 files. They decorate
rather than explain, and they drift: a separator says "Validation" while the
code beneath it moved elsewhere, as one in workflow-columns already had.

Pure deletion — no source line was touched, and lines inside template
literals were skipped so nothing in a generated string changed.
2026-08-13 00:12:45 -07:00
Vikhyath Mondreti 5cf1f9be84 improvement(provenance): cleanup secrets boundary (#6374)
* fix(secrets): preserve raw outputs with durable provenance

* improvement(provenance): cleanup boundary

* fix copy resources

* fix fork copies to work with provenance

* address comments

* fix
2026-08-07 17:12:17 -07:00
Theodore Li e369997eac fix(db): encode Date binds in raw sql, document the fetch_types contract (#6040)
* fix(db): encode Date binds in raw sql, document the fetch_types contract

* fix(testing): drop template placeholders from mock error message for biome
2026-07-29 13:06:34 -04:00
Waleed 513292f17b feat(sso): DNS domain verification gating org SSO registration (#5909)
* feat(sso): DNS domain verification gating org SSO registration

Add org-scoped domain ownership verification (DNS TXT challenge) as the
security precondition for configuring SSO. Closes the first-come domain-claim
vuln where any org could wire another company's domain to its own IdP.

- New sso_domain table + migration 0266; existing org SSO domains are
  grandfathered as verified so live tenants are unaffected
- Verified-domains settings UI (enterprise-gated) with add/verify/remove
- Register route now requires a verified domain for org-scoped registration;
  personal SSO and already-grandfathered domains are unaffected
- Self-host register script writes the verified sso_domain row directly, so
  script-driven registration stays backwards compatible

* fix(sso): harden domain verification against concurrency + fix CI lint

Addresses review findings on state invariants under concurrent/failed writes:
- Add unique index on (organization_id, domain) so concurrent claims can't
  create duplicate pending rows; POST re-reads and stays idempotent on conflict
- Verify flips the row only if it's still the exact pending challenge checked
  (guards deletion/token-rotation mid-DNS-lookup) and maps the partial unique
  index violation to 409 instead of an unhandled 500
- Wrap the self-host script's provider write + verified-domain upsert in a
  transaction so a failed ownership write can't leave a provider committed
- Format 0266 snapshot/journal with biome (fixes @sim/db lint:check)

* fix(sso): re-check domain verification before provider write (TOCTOU)

The register gate checked the verified sso_domain row only at handler entry,
then ran OIDC discovery before writing the provider. A verified row removed
during that window could still complete registration. Extract the check into a
closure and call it both as an entry fast-fail and authoritatively right before
registerSSOProvider, alongside the existing domain-conflict re-check.

* fix(sso): stop rotating verification token on idempotent re-add

Re-adding a pending domain rotated its verification token, which invalidated a
TXT record the admin may have already published and — under two concurrent
re-adds — could return a token the racing write had already superseded, so the
admin's DNS record would never verify. Return the existing row unchanged
instead; the pending token is always shown in the UI, so it is never lost.

* fix(sso): close register TOCTOU with compensating delete + harden edges

Audit-driven hardening:
- Close the residual register TOCTOU: registerSSOProvider is create-only (throws
  if the providerId exists), so a compensating delete after the write is provably
  safe — it can only remove the just-created row. If verification was revoked
  during the write, roll the provider back and 403.
- Verify is now idempotent under concurrency: a same-org row already flipped to
  verified by a racing request returns 200, not a confusing 409.
- Grandfather backfill + self-host script now match normalizeSSODomain's dominant
  transforms (lower + trim + strip leading wildcard) so a non-canonical legacy
  domain can't miss the runtime gate's lookup. Prod backfill result is unchanged.
- Cleanup: drop dead default export, align card radius to sibling convention.

* fix(sso): redact domain tokens from non-admins + fix script stale-update

Round-5 review findings:
- GET /domains redacted the pending TXT verification token (a management
  secret) to any org member. Now only owner/admins read it; members see the
  list and status without it. Non-Enterprise orgs get an empty list (entitlement
  flag only), never the domains/tokens.
- Self-host script decided update-vs-insert from a read taken OUTSIDE the
  transaction; a provider deleted mid-flight made the UPDATE match zero rows
  silently while the verified-domain upsert still committed (orphaned domain).
  The decision now happens inside the transaction from the UPDATE's row count.

* docs(sso): drop unshipped enforce-SSO / auto-join copy from verified domains

Verified domains currently only gate SSO configuration. Remove the
forward-looking references to enforcing SSO and auto-joining members (deferred
to a later release) from the docs, settings copy, nav description, and schema
comment so we don't promise unshipped features.

* fix(sso): guard rollback to new providers only + Enterprise-gate domain removal

Round-6 review findings:
- The compensating provider rollback now only fires when the provider did not
  exist before this request (providerExistedBefore). registerSSOProvider is
  create-only today so reaching the rollback already implies a fresh create, but
  this makes the safety local and future-proof: if Better Auth ever allowed
  updating an existing provider, a revoked-verification rollback must not delete
  that pre-existing row.
- DELETE /domains now requires an Enterprise plan like add/list/verify, so all
  domain mutations share one entitlement (the UI already hides removal from
  non-Enterprise orgs). Adds a delete-route test.

* fix(sso): roll back the SSO provider by row id, not logical keys

The compensating rollback deleted by (providerId, orgId). providerId is unique,
so if this request's row were deleted and recreated by a concurrent registration
in the narrow window before the rollback, the logical-key delete would remove
that other request's provider. Delete by the primary-key id registerSSOProvider
returns instead, so only the exact row this request created is ever removed.

* chore(sso): final-review polish — trim script read, unify copy, doc migration edge

Cosmetic cleanup from a final 4-track adversarial review (no bugs found in the
new logic):
- Self-host script: narrow the pre-transaction existence read to select({ id })
  instead of SELECT * (it only feeds a log line now).
- Unify invalid-domain copy ("for example acme.com") and the verified-elsewhere
  409 wording ("is already verified by another organization") across routes.
- p-3 shorthand on the domain row card.
- Document the migration's rare two-orgs-share-a-domain grandfather behavior
  (login unaffected; validated no such duplicates in prod).

* fix(sso): apply attribute mapping + make SSO edit work; drop dead guard

Two pre-existing SSO bugs the final review surfaced (prod has one SSO org, RVW,
script-registered with the default mapping, so neither change affects it):

- Attribute mapping was passed at the top level of the register payload, which
  Better Auth ignores — it reads oidcConfig.mapping / samlConfig.mapping. Nest it
  so custom mappings actually apply. (Default mapping is unchanged, so existing
  logins are unaffected.)
- Editing an SSO provider was broken: registerSSOProvider is create-only and
  threw on the existing providerId → generic 500. Route now detects a provider
  the caller already owns and updates it via Better Auth's updateSSOProvider, and
  surfaces Better Auth's own error status/message instead of a blanket 500.

Also drops the now-unnecessary providerExistedBefore guard (the rollback deletes
by the created row's primary-key id and register is create-only) and the earlier
final-review polish (script read, unified copy, migration edge note).

Smoke-test SSO login + edit on staging before merge (auth-path change).

* fix(sso): require null org on personal-mode provider lookups (gate bypass)

The personal branch of both provider-ownership lookups keyed on
(providerId, userId) without requiring organizationId IS NULL. Because org
providers store userId = their creator and providerId is globally unique, an org
admin could send a personal-mode request (no orgId) — which skips the membership
check and the domain-verification gate — yet still match, and then via the new
update path move, their org's provider to an unverified domain. Add
isNull(organizationId) to the personal branch of both clauses so it can only
match a genuinely personal provider, matching the route's own isOwnedByCaller.

Found by an adversarial review of the update path added in 394bda9f7.

* fix(sso): script updates the observed provider by id, not providerId

Inside the registration transaction the script updated WHERE providerId — the
logical key. If the observed provider was deregistered and a replacement created
with the same providerId before the transaction ran, that update would clobber
the replacement's config and ownership. Update the specific observed row by its
primary-key id instead; if it's gone we insert, which fails cleanly on the
providerId unique constraint rather than overwriting the replacement.

* fix(sso): script upserts provider via delete-then-insert (no unique constraint)

sso_provider.provider_id is a plain (non-unique) index and prod holds legitimate
duplicates, so the previous "update by id, else insert" could create a duplicate
provider when the observed row was deregistered and replaced before the
transaction — the fallback insert would succeed. Delete every row for the
providerId then insert exactly one, inside the transaction, so the providerId
ends up as exactly this config atomically. Linked accounts key on the providerId
string (not the row id), so existing logins are unaffected.

* fix(sso): guard compensating-delete row id so rollback can't silently no-op

* chore(sso): regenerate migration as 0268 after merging staging

Staging landed migrations 0266/0267, colliding with our 0266. Removed our
migration, merged staging, and regenerated cleanly with drizzle-kit as
0268_sso_domain_verification (identical sso_domain table + indexes), then
re-appended the grandfather backfill. api-validation baseline reconciled to 973
(staging 970 + our 3 domain routes). Also make the register-route test's
registerSSOProvider mock return an id so the guarded compensating delete runs.

* refactor(sso): share normalizeSSODomain via @sim/utils so script matches gate

The self-host script canonicalized SSO domains with a minimal inline transform
(lower+trim+wildcard) that diverged from the app's full normalizeSSODomain
(protocol, port, path, trailing dot, email local part) — equivalent spellings
could store a different ownership key than the runtime gate looks up. Move
normalizeSSODomain into @sim/utils/sso-domain (a pure function) so the register
route, the domain-claim route, and the script all use the identical canonicalizer.
The script now skips the verified-domain record when SSO_DOMAIN isn't a valid
registrable domain instead of storing a malformed key.
2026-07-24 00:34:16 -07:00
Theodore Li de934b9979 feat(script): migrate agent/router/evaluator LLM keys to BYOK by model prefix (#5607)
* feat(byok): migrate agent/router/evaluator LLM keys to BYOK by model prefix

* fix(script): address review — cover translate/guardrails, trim provider ids, reject mixed mapping, add key-prefix guard

* fix(script): include pi block in LLM-family set, trim key-prefix value

* fix(script): add router_v2 to LLM-family set, canonicalize provider ids to lowercase

* fix(script): resolve overlapping model prefixes deterministically (longest match wins)
2026-07-13 18:28:12 -04:00
Vikhyath Mondreti ef7c8e24b2 feat(platform): settings permissions, admin, billing attribution (#5545)
* fix(invites): preserve active organization for external access

Keep organization activation server-owned so failed membership checks cannot clear a valid session context.

* feat(admin, billing, settings): cleanup settings visibility, billing actor resolution, new admin routes

* address comments

* chore(db): reset pending migrations before staging merge

Remove locally generated migrations so they can be regenerated against the latest staging schema without preserving stale snapshots or numbering.

* regen migrations

* address comments

* chore(db): reset generated migrations before staging merge

Remove this branch's generated migrations so they can be regenerated against the latest staging schema with fresh numbering.

* upgrade global work

* fix lint

* address comments

* legacy callbacks correctness

* address comments

* update

* guardrail attribution
2026-07-13 00:53:49 -07:00
Theodore Li 12fb4a9db1 feat(db): auto-apply tracked script data migrations in db:migrate (#5497)
* feat(db): auto-apply tracked script data migrations in db:migrate

* fix(db): reset session lock_timeout before script migrations, guard journal insert

* improvement(db): re-verify advisory-lock session before script migrations
2026-07-07 20:55:42 -04:00
Waleed e1b8200660 fix(sso): support skipping the OIDC UserInfo endpoint at registration (#5386)
* fix(sso): support skipping the OIDC UserInfo endpoint at registration

* fix(sso): cap OIDC discovery fetch at 10s to avoid stalling registration

* test(sso): default-mock discovery fetch so intent is explicit

* fix(sso): prefer client_secret_post and surface discovery failure reasons

* fix(sso): always resolve token auth method and skip SSRF-checking a discarded userInfoEndpoint
2026-07-03 12:09:22 -07:00
Waleed 2fa3dd65bc fix(db): retry the migration connection on transient slot exhaustion (#5226)
* ci(migrations): skip db:migrate on merges that change no migration files

Every push to main/staging ran db:migrate against the production/staging
database even when the merge changed no schema, so a no-op migration would dial
the DB and fail whenever it was at its connection limit (53300, slots reserved
for SUPERUSER) — red-X'ing UI-only merges.

Add a detect-migrations job (dorny/paths-filter on packages/db/migrations/**)
and pass the result into the reusable migrations workflow, which now skips the
apply step when no migration files changed. The migrate job still runs so
downstream build/deploy jobs that need it are never skipped, and the flag
defaults to 'true' so manual dispatch and any unknown value always apply
migrations — the gate only ever skips a provably-empty change.

* fix(db): retry the migration connection on transient slot exhaustion

The migration opens its session on the first query (the advisory-lock
acquire). When the deploy database briefly exhausts every non-superuser
connection slot at peak, that connect fails with 53300 ("remaining connection
slots are reserved for roles with the SUPERUSER attribute") and the whole
deploy's migrate step errors out — even when the spike clears within seconds.

Add a bounded connectWithRetry() before acquiring the lock that retries 53300,
the 08xxx connection_exception class, and the driver's transport errors with
backoff (10 attempts, ~90s ceiling). Non-transient errors (auth, bad config)
still fail fast. The migration is a single short-lived session, so waiting out
a transient spike is far safer than failing the deploy.

* ci: drop the migration paths-filter gate (out of scope)

Revert the detect-migrations gate carried over from the closed CI PR; we are
fixing the connection failure at its source (migrate.ts connection retry)
rather than gating db:migrate, which the reviewers correctly noted could leave
a previously-merged migration unapplied after a failed deploy.
2026-06-26 12:21:11 -07:00
Theodore Li a68d38ae75 feat(db): attribute Postgres connections by runtime via application_name (#5211)
* feat(db): attribute Postgres connections by runtime via application_name

* improvement(db): label migration-runner connection sim-migrate; trim DB_APP_NAME comment

* fix(db): label realtime's shared @sim/db connections sim-realtime too

The realtime process uses both its own socketDb pool and the shared @sim/db
client (handlers, preflight, permissions). Only socketDb was labeled, so the
shared client defaulted to sim-app, mislabeling much of realtime's DB traffic.
Set DB_APP_NAME=sim-realtime at the process level (bootstrap before the dynamic
@/index import for prod; dev/start scripts for local) so both clients report it.
2026-06-25 17:11:23 -04:00
Waleed 9efb7b45f4 feat(byok): support multiple keys per provider with round-robin rotation (#4963)
* feat(byok): support multiple keys per provider with round-robin rotation

* fix(byok): address review feedback — serialize cap check, defer encryption, explicit delete guard

* fix(byok): drop ON CONFLICT on removed unique index in legacy key migration script

* improvement(byok): guard double-submit, Enter-to-save on key field, cap hint in manage modal
2026-06-11 10:00:58 -07:00
Waleed 284edf0b85 improvement(db): opt-in read-replica client + migration runner hardening (#4955)
* improvement(db): add opt-in read-replica client and harden migration runner

* fix(db): detect wrapped lock-timeout errors, jittered retries, direct migration DSN support

* fix(db): audit fixes — unparameterized SET, primary reads for authz scoping, shared error helper

* fix(db): pin migration session — disable max_lifetime recycling, guard backend pid across retries

* fix(db): gate pid session guard to direct migration connections (pooler pids legitimately vary)

* improvement(billing): route display-only usage aggregations to the read replica via executor threading

* chore(db): drop call-site justification comments

* chore(db): tighten doc comments

* ci(migrations): map optional direct-connection DSN secrets

* fix(data-drains): add stability window to time cursors so late-visible rows are never skipped

* fix(billing): resolve pagination cursor on primary; replica for member ledger display

* fix(billing): usage-limits returns cost and limit from one computation
2026-06-10 18:33:58 -07:00
Waleed b2a485e164 fix(db): serialize concurrent migrations with a Postgres advisory lock (#4939)
* fix(db): serialize concurrent migrations with a Postgres advisory lock

Deployments start N app replicas at once, each with a migration sidecar.
drizzle migrate() has no cross-process lock, so all N read
__drizzle_migrations, all see the same migration pending, and all apply it
concurrently — one wins, the losers run the same DDL against already-mutated
state and exit 1 (e.g. DROP TABLE "form" -> table does not exist /
TaskFailedToStart). Wrap migrate() in a session-level pg_advisory_lock so
runners serialize: the winner migrates, the losers block, then re-read and
find nothing pending. Session locks auto-release on disconnect, so a crashed
runner never wedges the lock.

* fix(db): guard pg_advisory_unlock so it cannot mask a successful migration

If the explicit unlock throws (e.g. connection drops in the window after
migrate() commits), the exception bubbled to the outer catch and exited 1 —
falsely reporting a failed migration to the deploy orchestrator. The session
lock auto-releases on disconnect anyway, so swallow and log instead.

* refactor(db): move unlock-guard rationale to TSDoc helper
2026-06-09 21:54:27 -07:00
Vikhyath MondretiandCursor 49673055be improvement(logs): object storage backed tracespans (#4787)
* improvement(logs): obj storage backed tracespans

* fix storage write context

* fix tests

* address comments

* address comments

* chore(db): remove migration 0219 to regenerate after staging merge

Drops the 0219_robust_shard SQL, its snapshot, and the journal entry so the
trace-spans/cost schema migration can be regenerated on top of the latest
staging migration chain (avoids a number collision with staging's migrations).

Co-authored-by: Cursor <cursoragent@cursor.com>

* improvement(billing): accurate per-member usage via shared ledger helper

Per-member/per-user usage in the org-member routes now adds the usage_log
ledger to the currentPeriodCost baseline (which is no longer incremented),
via a shared getOrgMemberLedgerByUser helper to avoid repeating the
subscription→period→ledger lookup across the admin and member-facing routes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* regen migrations

* update migration

* address comments

* more code cleanup

* incorrect type cast

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 13:47:32 -07:00
Theodore Li 786c6f0607 fix(db): disable statement_timeout for migrations (#4714)
* fix(db): disable statement_timeout for migrations

* fix(ci): route migration workflow through guarded migrate.ts
2026-05-22 14:23:06 -04:00