Create or migrate a protected Sim resource operation in the shared Principal and application-use-case architecture across internal APIs, public or versioned APIs, Copilot, and other trusted tool adapters. Use when adding a protected endpoint, tool command, or CRUD method; removing route- or tool-local authorization and business logic; consolidating resource reads or writes behind semantic operation policies; or adding another surface to an existing application operation while preserving contracts, identity, errors, rate limits, audit, analytics, and compatibility behavior. Treat v1, uploads, streams, large bodies, bulk recursion, and polymorphic tools as explicitly scoped special cases.
70
85%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
View guide
Passed
No findings from the security scan
Create or migrate one bounded semantic operation at a time. Share authorization and business behavior without forcing internal APIs, public APIs, Copilot, and other tools to share authentication, input schemas, or response shapes.
Apply this invariant:
Every real operation on persisted or protected data enters through an authorized application use case.
This includes mutations, content and metadata reads, canonical resource lookup, and reference-to-resource resolution when the lookup is authorization-sensitive.
Surface helpers may:
Principal.Surface helpers must not:
A helper that resolves a path is valid only when the actual protected lookup runs through an authorized application resolver. If a helper begins doing real data work, move that work into an application use case.
Read these files completely before editing:
packages/auth/src/principal.tsapps/sim/lib/core/application/operation.tsapps/sim/lib/core/application/workspace-operation.tsapps/sim/lib/core/application/workspace-authorization.tsapps/sim/lib/core/application/authorized-workspace-use-case.tsapps/sim/lib/api/server/routes/definition.tsapps/sim/lib/api/server/routes/internal-json-route.tsapps/sim/lib/api/server/routes/v2-json-route.tsapps/sim/lib/auth/internal-delegation.tsapps/sim/lib/copilot/application/application-adapter.tsapps/sim/lib/copilot/auth/application-delegation.tsUse the file domain only as a representative golden slice:
apps/sim/lib/workspace-files/application/operations.tsapps/sim/lib/workspace-files/application/authorized-workspace-file-use-case.tsapps/sim/lib/workspace-files/application/rename-workspace-file.tsapps/sim/lib/copilot/application/execute-file-use-case.tsapps/sim/lib/copilot/auth/file-delegation.tsThen read the target domain's operation registry, application code, repositories, contracts, adapters, aliases, resume paths, and focused tests. Fail immediately if the shared foundation is absent. Do not recreate it inside the domain.
Inventory every entry point for the behavior before editing:
Classify each as migrate, defer, or non-goal. Do not migrate adjacent operations merely because they share a module. Do not modify v1 unless the request explicitly includes it.
Preserve behavior unless the task explicitly changes it. Stop and report a decision when surfaces currently disagree on security or compatibility behavior; do not silently choose one.
Treat the legacy route or tool as an ordered program, not merely a bag of business logic. Before moving code, write a compact baseline for every in-scope entry point and add focused characterization tests for behavior not already pinned down.
Capture all of these when they apply:
Compare the old statement order with the proposed application lifecycle explicitly:
legacy parse/normalize
-> legacy authorization checks
-> branch-specific canonical lookup
-> mutation(s)
-> per-step side effects
-> response or redirect catchMoving those steps under a wrapper may change behavior even when each individual call is reused. In particular:
projectAudit and afterSuccess run only after execute returns. They cannot describe earlier committed mutations when a later step throws. Make the compound mutation atomic or define explicit partial-result/failure projection semantics before migrating it.URLSearchParams normalization or exact legacy response unions.Fail fast if the baseline cannot be established from code, tests, or an explicit product decision. Do not infer that behavior is unimportant because it was previously implicit.
Use these responsibilities:
Principal.For ordinary public JSON routes, preserve this order:
IP abuse limit
-> authenticate
-> build Principal
-> operation rate limit
-> parse surface contract
-> application use case
-> canonical load
-> asserted-scope concealment
-> current authorization
-> manager read or mutation
-> semantic audit
-> shared domain effects
-> surface presenterInternal routes may omit the IP bucket or operation limit only through an explicit policy with a reason. Usage billing, storage quota, cost admission, and concurrency are separate from request-rate limiting.
Never query API keys or sessions from the application layer. Never add fallback identity or authorization behavior. Propagate infrastructure failures instead of turning them into not-found or forbidden results.
Add one stable entry to the target domain's operation registry:
rename: defineWorkspaceOperation({
id: 'widgets.rename',
minimumRole: 'write',
workspaceApiKey: 'allow',
capability: 'widgets.use',
principalKinds: ['session', 'personal_api_key', 'workspace_api_key', 'delegated'],
delegatedServices: ['copilot'],
})Do not create internal-, public-, or Copilot-specific versions of the same semantic operation. If two callers have materially different business or transactional semantics, define separate semantic operations and use cases and explain the distinction.
Choose principal kinds from actual behavior. Do not accept every principal merely because the use case is shared. Workspace API keys have a write ceiling and cannot satisfy admin operations. The operation definition must fail fast when its role, workspace-key policy, and principal kinds disagree.
capability is required — name the permission-group capability that governs the operation, or 'none' with a // permission-group-exempt: <reason> comment directly above it. defineWorkspaceOperation throws at definition time when it is absent. See add-permission-group-item.
Route declarations, tool adapters, and use cases must use the same literal operation. Runtime operation selection is permitted only from a trusted, code-defined registry. Never accept an operation ID or permission tag from an HTTP body, model argument, or other untrusted input.
Dynamic selector dispatch is the deliberate instance of trusted runtime selection. Define and
authorize selectors.execute once: it means "enumerate options while configuring a workflow or
workspace resource." The browser supplies only a selector key from the exhaustive browser-safe
manifest, scope, allowlisted context, and list/detail request. After canonical scope authorization,
the application use case selects the matching attachment from the exhaustive server-only registry.
Provider and internal attachments are trusted implementation adapters under that semantic operation,
not separate application operations. Do not create one operation per selector, provider, or listing
endpoint. Attachments may choose only code-defined credential/service binding, destination policy,
provider primitive, and projection behavior; they must not accept a module, provider, service,
operation kind, origin, or permission tag from the request. The selectors.execute use case owns
reference resolution, credential authorization, provider invocation, sanitization, and safe result
projection end to end.
Use defineAuthorizedWorkspaceUseCase directly or a thin domain binding that supplies domain-specific authorization options:
export const renameWidget = defineAuthorizedWorkspaceUseCase({
operation: widgetOperations.rename,
resolveContext: ({ input }: { input: RenameWidgetInput }) =>
loadCanonicalWidgetContext(input.id, input.assertedWorkspaceId),
authorizationOptions: { delegation: widgetDelegationPolicy },
execute: async ({ input, context }) => renameWidgetRecord({
workspaceId: context.workspaceId,
widgetId: context.resourceId,
name: input.name,
}),
projectAudit: ({ result }) => ({
action: AuditAction.WIDGET_UPDATED,
resourceType: AuditResourceType.WIDGET,
resourceId: result.id,
resourceName: result.name,
}),
afterSuccess: ({ context }) => notifyWidgetsChanged(context.workspaceId),
})Adapt the example to the domain's real authorization options; do not copy invented field names.
The wrapper must own this lifecycle:
Do not call shared authorization, principal audit attribution, or recordAudit manually from an ordinary migrated use-case body. Use projectAudit only when the operation has semantic audit. Return no audit entries for authoritative no-ops. Keep product analytics such as captureServerEvent surface-specific through the adapter's success hook.
Inspect legacy orchestration before reusing it. If it already authorizes, audits, notifies, or captures analytics, call a lower-level primitive or remove duplicate responsibility for migrated callers.
Application code must remain surface-neutral. It must not import app/api/**, next/server, internal/v1/v2 contracts or presenters, or Copilot tool handlers. Return domain values and let each surface presenter project its own wire result.
Use defineInternalJsonRoute for ordinary JSON routes. Explicitly declare the contract, authentication policy, semantic operation, rate policy, error policy, input mapping, use case, and presenter when the wire result differs.
Use internalSessionAuth for session-only routes. Use createInternalSessionOrExecutorAuth only when the endpoint genuinely supports signed executor delegation; the semantic operation must then allow delegated principals from the executor service. Never turn an actorless legacy JWT into a fake session, owner, or user principal.
The internal adapter owns authentication and internal response envelopes. It must not implement workspace authorization. Preserve internal-only analytics through onSuccess after application success.
Keep the route module declarative. If several internal routes repeat authentication, parsing, error rendering, or response construction, improve the shared internal route builder instead of adding a domain-specific route wrapper.
Use the appropriate public/versioned route builder, such as defineV2JsonRoute, with API-key authentication, explicit semantic operation and rate policy, external error projection, input mapping, application use case, and an external presenter.
Authentication and HTTP formatting may differ from internal APIs; authorization and business behavior must not. Rate-limit using the credential or principal subject, never a billed owner. Resolve billing attribution only for billing, quota, or legacy required-user fields.
Keep surface contracts separate when their wire shapes differ. Reuse shared primitive schemas and domain validators for invariants such as IDs, names, bounds, and formats. Do not maintain duplicate internal and external schemas merely because the routes are separate; import the same schema when the wire shape is genuinely identical. Never cast one surface response into another.
Keep v1 middleware and routes unchanged unless explicitly included.
Copilot is a surface adapter, not a separate application layer. If an HTTP or other surface already uses an application use case, Copilot must call that exact use case rather than reimplementing protected business behavior under lib/copilot.
Create one domain-level Copilot application adapter with createCopilotApplicationAdapter instead of constructing delegated principals in every tool:
executeCopilotWidgetUseCase(context, renameWidget, input, { resourceId })That adapter must:
Principal in one place.Never construct authoritative delegation from model-provided workspace IDs, user IDs, operation IDs, resource scope, or permission tags. Model arguments are requested targets only and must be checked against trusted execution context and canonical data.
Tool handlers own argument aliases, resumable legacy names, abort checks, tool-call reporting, and tool-specific presentation. They must not query managers directly for protected operations, manually authorize, or implement protected business behavior. If a Copilot-only compound action expresses real domain behavior, define a surface-neutral domain operation and application use case for it.
A Copilot reference helper may translate a path to a resource only by calling an authorized application resolver under the intended semantic operation. Passing a code-defined operation object is acceptable; passing a model-provided operation string is not. An immediate same-request resolver followed by the operation may reuse one trusted principal, though the application operation still performs its own canonical authorization. Fresh authentication and authorization are required across lifecycle boundaries such as resumed tool calls, executor callbacks, queued or background work, upload control legs and finalization, durable completion, and long-running provider operations. When resolution and execution form one business operation, need a consistent snapshot, or appear repeatedly together, prefer a top-level application use case such as renameWidgetByReference.
Surface adapters must not compose protected mutations. An atomic compound action requires one top-level semantic domain operation and application use case that owns the transaction and authoritative result. An explicitly best-effort application command may coordinate multiple operations only when it defines hard input and expansion caps, cancellation checkpoints, partial-result semantics, audit behavior, and rate/quota policy. Keep composition exceptional and explicit; ordinary tools should use the shared execution adapter.
Map expected typed errors to safe tool results. Unknown errors must become generic system/retryable messages while retaining full causes in server logs. Never return raw database or storage errors to the model.
Treat every tool runtime as a surface adapter:
Principal through one shared adapter for that runtime or domain.An internal caller is not automatically trusted to bypass authorization. It must supply an explicit principal or use a deliberately designed service/delegation principal. If the current principal model cannot express its authority, stop and extend the identity model intentionally; do not fall back to an owner, uploader, creator, or arbitrary user ID.
External tool endpoints authenticate at their adapter exactly like public APIs. Do not authenticate again inside the application use case.
PrincipalActor metadata in semantic audit.If a required legacy user column cannot represent the real actor, label the compatibility attribution explicitly. Never pretend it is the acting human.
Do not force these through an ordinary JSON migration:
Stop and report a missing design rather than weakening identity, authorization, limits, or errors.
Add focused tests for every migrated surface and principal kind allowed by the operation:
Run at minimum:
bunx vitest run <focused test files>
bunx biome check <changed source and test files>
bunx turbo run type-check --filter=@sim/app --filter=@sim/auth
bun run check:api-validation:strict
git diff --checkDo not claim a check passed unless it completed successfully.
Report:
7945b29
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.