@somewhere-cloud/cli 0.38.150 → 0.38.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.38.151
4
+
5
+ - The generated project guide shows where to declare data access and how to check it with signed-in users.
6
+ - `somewhere typecheck` recognizes `ownerOnly: true` for caller-scoped browser and function reads. Use it to return only rows owned by the current user.
7
+
3
8
  ## 0.38.150
4
9
 
5
10
  - `somewhere typecheck` now checks the source and functions sent to deploy, using the platform's TypeScript version, generated types and checker settings. Use `somewhere typecheck --project` for the full local project check.
@@ -43507,7 +43507,7 @@ var FIRST_CLI_PERMISSION;
43507
43507
  var init_first_cli_permission = __esm({
43508
43508
  "dist/lib/first-cli-permission.js"() {
43509
43509
  "use strict";
43510
- FIRST_CLI_PERMISSION = "Before your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.";
43510
+ FIRST_CLI_PERMISSION = "Ask before destructive or paid actions unless the user already authorized them.";
43511
43511
  }
43512
43512
  });
43513
43513
 
@@ -44092,236 +44092,65 @@ var init_skills_pack = __esm({
44092
44092
  });
44093
44093
 
44094
44094
  // dist/lib/init-agent-guide.js
44095
- var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, TEST_ACCESS_RULES, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44095
+ var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44096
44096
  var init_init_agent_guide = __esm({
44097
44097
  "dist/lib/init-agent-guide.js"() {
44098
44098
  "use strict";
44099
- init_first_cli_permission();
44100
44099
  init_skills_pack();
44101
44100
  AGENT_WORKFLOW = `## Build, deploy, test
44102
44101
 
44103
- Enough to start a typical app: declare access and use the browser client; docs are for exceptions.
44104
-
44105
- | Requirement | Declaration below |
44102
+ | Does your app verify emails? | Choose the declared access rule |
44106
44103
  | --- | --- |
44107
- | Each user sees only their own rows | notes: owner() |
44108
- | Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |
44109
- | Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |
44110
- | Public pages from private drafts | pages: conditional publicRead |
44111
- | Share one record read-only | shared_notes/note_shares: read-only grant() |
44112
-
44113
- db/schema.ts is declaration only: imports, constants/spreads, default schema;
44114
- no helpers/expressions. id() is random text; owner() stamps user_id. client.read
44115
- includes the key. Inside anyOf(), owner() takes only column/read: it stamps the
44116
- creator, not create/delete options; group() gates placement (non-member create is
44117
- refused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });
44118
- indexes: [['team_id']].
44119
-
44120
- \`\`\`ts
44121
- import { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';
44122
- export default schema({
44123
- notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },
44124
- }),
44125
- tasks: table({ id: id(), team_id: text(), title: text() }, {
44126
- scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],
44127
- create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),
44128
- client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },
44129
- }),
44130
- tickets: table({ id: id(), subject: text() }, {
44131
- scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),
44132
- client: { read: true, create: ['subject'], update: ['subject'] },
44133
- }),
44134
- messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44135
- scope: parent({ via: 'ticket_id' }),
44136
- client: { read: true, create: ['ticket_id', 'body'] },
44137
- }),
44138
- staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44139
- scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),
44140
- client: { read: true, create: ['ticket_id', 'body'] },
44141
- }),
44142
- pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {
44143
- scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],
44144
- publicRead: { where: { published: true } } },
44145
- }),
44146
- note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {
44147
- scope: owner(), unique: [['note_id', 'grantee_id']],
44148
- }),
44149
- shared_notes: table({ id: id(), title: text() }, {
44150
- scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),
44151
- client: { read: ['id', 'title'], create: ['title'], update: ['title'] },
44152
- }),
44153
- }, { appRoles: { staff: { emailDomain: 'staff.example' } } });
44154
- \`\`\`
44104
+ | Yes, invited teams | Use \`group()\` and \`sw.groups\` for invitations, membership and owner/admin permissions. See \`somewhere docs sw.groups --section team-example\`. |
44105
+ | No, app-managed teams | Use \`member()\` over a server-only roster. Declare author-or-team-owner delete with \`anyOf()\` and a role-filtered branch. See \`somewhere docs declared-data --section teams-without-email-verification\`. |
44106
+ | Yes, staff by domain | Use \`appRole()\` and \`appRoles: { staff: { emailDomain: 'staff.example' } }\`. The address must be verified. |
44107
+ | No, staff by invitation | Use \`appRole()\` and \`assignedBy: 'server'\`. Redeem an app-issued invitation and call \`sw.auth.server.setRoles\` inside the sign-up route. See \`somewhere docs sw.auth --section server-assigned-app-roles-setroles\`. |
44108
+ | Either, personal rows | Use \`owner()\`. The platform stamps the owner from the signed-in user. |
44109
+ | Either, shared private row | Use a read-only \`grant()\` for a known app-user ID. Share by address only after verification. Adding the grant widens existing caller-scoped reads. See \`somewhere docs declared-data --section read-only-sharing-without-email-verification\`. |
44110
+ | Either, public pages from private drafts | Use conditional \`client.publicRead\`. Anonymous results can be cached for up to 120 seconds. For fresh pages, read with \`sw.db.server.from\` in a page handler, filter for published rows, select public fields, and set \`Cache-Control: no-store\`. |
44155
44111
 
44156
- Who is staff is your app's decision; the platform enforces what the role may do.
44157
- First choice, as above: emailDomain. The role holds once the person verifies an address
44158
- at that domain; no grant code. An email ending alone proves nothing: anyone can sign up
44159
- as anyone@your-domain without owning that mailbox. Without verification, grant only from
44160
- something the visitor cannot choose, such as an invitation your app issued, checked inside
44161
- the sign-up route: single use, bound to one account, its link delivered only to that person:
44162
- somewhere docs sw.auth --section server-assigned-app-roles-setroles.
44163
- messages use parent(): owner() would hide staff replies from the customer.
44164
- A staff reply is a messages row, and creating a parent() child needs create on the parent
44165
- for that person: its owner, or a role listed under the parent's create. Read or update is
44166
- not enough. So tickets lists create: ['staff']; without it every staff reply is refused
44167
- (403 POLICY_AUTHORITY_REQUIRED).
44168
- Publish pages in an owner-checked endpoint. Share with caller-scoped
44169
- sw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.
44170
- Browser calls THROW, not { error }; catch below.
44171
- Browser list: paginate with after. Sort locally or in an endpoint.
44172
-
44173
- \`\`\`ts
44174
- import { data } from 'somewhere:data';
44175
- export async function save(title: string) {
44176
- try { await data.notes.create({ title }); return null; }
44177
- catch (e) { return e instanceof Error ? e.message : 'Save failed'; }
44178
- }
44179
- export const list = (after?: string) => data.notes.list({ limit: 100, after });
44180
- \`\`\`
44112
+ ### Schema and data
44181
44113
 
44182
- A page that needs several reads: start them together and show it once every read it depends on has answered.
44183
- Keep an input disabled until the data it depends on has loaded, including who the user is.
44184
- Never let a late answer overwrite what the user typed: fill an input from loaded data only before it is enabled.
44185
-
44186
- Teams are built-in groups: the platform keeps the team, invitations, roster, removal,
44187
- leaving, last owner. Starting a team needs a signed-in user; joining needs a verified
44188
- email (a password sign-up joins once it enters its emailed code).
44189
- No email verification in your app: keep membership in your own table with member() (somewhere docs sw.groups --section relationships-that-are-not-teams) and assign staff with setRoles in the sign-up route (above).
44190
- The browser cannot call
44191
- sw.groups: pass each call through an endpoint. A parent() child's delete follows the task
44192
- (creator or team owner), so "comment author or team owner deletes" is an endpoint.
44193
- Staff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and
44194
- sw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).
44195
- Complete apps and specs: somewhere docs sw.groups --section team-example or staff-example.
44196
-
44197
- \`\`\`ts
44198
- // api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own
44199
- const refusal = (e: { code: string; message: string; status: number }) =>
44200
- Response.json({ error: e.code, message: e.message }, { status: e.status });
44201
- export const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {
44202
- const page = await sw.groups.list(request, { limit: 100 });
44203
- return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };
44204
- } });
44205
- export default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {
44206
- const made = await sw.groups.create(request, { name: body.name });
44207
- return made.error ? refusal(made.error) : { id: made.data.id };
44208
- } });
44209
- \`\`\`
44114
+ Declare tables in \`db/schema.ts\` with imports, literal values, constants and spreads.
44115
+ New \`id()\` keys are text. Reference them with \`text({ references: 'table_name' })\`.
44116
+ Existing integer IDs stay integers. Declare composite uniqueness with \`unique: [['a', 'b']]\`.
44210
44117
 
44211
- \`\`\`ts
44212
- // api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER
44213
- export default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {
44214
- const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });
44215
- return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };
44216
- } });
44217
- \`\`\`
44118
+ - Browser reads and writes use generated \`somewhere:data\`. \`client\` sets allowed operations and fields. Include the key in explicit read lists. Browser calls throw errors, and list pages use the returned \`next\` as \`after\` (at most 100 rows per page).
44119
+ - \`anyOf()\` grants access through either branch. \`allOf()\` requires both the membership gate and the action rule. \`parent()\` inherits the parent row's access. To let a child author update or delete, declare \`parent({ author, update, delete })\`. It evaluates the child author and the parent operation separately. For staff replies through \`parent()\`, grant staff create permission on the ticket's rule. See \`somewhere docs declared-data --section comments-that-their-author-may-edit\`.
44120
+ - \`sw.db.from/insert/update/remove\` apply the caller's scope and return \`{ data, count, changes }\`. Use \`where\`, \`columns\`, \`order\`, \`limit\` and \`offset\` for server reads. \`sw.db.tx\` takes an array of write intents. Supply related IDs up front.
44121
+ - Authorize before \`sw.db.server\` calls, which bypass the caller's scope. Keep declared scopes on records users work with, even when an exceptional write needs server authority. Use \`serverOnly()\` for protected ledgers and job state. Raw SQL uses a separate raw database.
44122
+ - For booking and help desk schemas, see \`somewhere docs sw.db --section provider-or-booker-and-owner-or-staff-recipes\`. For browser paging, server paging and transactions, see \`somewhere docs sw.db\`.
44218
44123
 
44219
- Same shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)
44220
- (last owner: 409 LAST_OWNER), delete(request, id) by owners.
44124
+ Use \`client.intake\` for public submissions to a private parent row. See
44125
+ \`somewhere docs declared-data\` for intake, scoped writes and related rows.
44221
44126
 
44222
- Do not hand-write access to app-read/write data: declare who may read/write it.
44223
- serverOnly() fits job/import/audit/counter state.
44224
- Grant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates
44225
- (e.g. expiry) or per-role writable fields (split tables or check that write).
44127
+ ### Routes and auth
44226
44128
 
44227
- Build src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.
44228
- Auth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.
44229
- api/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;
44230
- GET/DELETE: named exports.
44129
+ - \`src/App.tsx\` and \`src/routes.ts\` route React pages. \`api/notes/[id].ts\` serves \`/api/notes/:id\`. A root \`[...path].ts\` handles document routes, including \`/\`. Underscore-prefixed files are import-only helpers.
44130
+ - JSON routes use \`sw.endpoint({ auth, body, rateLimit, handler })\`. Set \`auth\` to \`'required'\`, \`'optional'\` or \`'none'\`. Use a limit like \`'30/minute'\`. Read route parameters from the handler's \`params\`. Use a default handler or named HTTP method exports. For streaming, webhooks or custom responses, use a bare \`(req, sw)\` handler and \`sw.params\`. See \`somewhere docs functions\`.
44131
+ - Keep \`api/auth/[...path].ts\` and extend the starter's \`src/auth/hooks.ts\`. Configure providers in \`src/config.ts\`. Gate private UI on auth state. Password sign-up starts unverified, and signed-in unverified users pass \`auth: 'required'\`. See \`somewhere docs auth-client\`.
44132
+ - Render a view when the reads it depends on finish. Keep inputs disabled until their initial data and identity are ready, and preserve edits when a late response arrives.
44133
+ - Browser requests use same-origin cookies. For scripted writes with a cookie session, send the app's origin in the \`Origin\` header. Use the CLI test helper to send data endpoint calls with the deployed contract digest.
44231
44134
 
44232
- \`\`\`ts
44233
- export const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });
44234
- \`\`\`
44135
+ ### Run and verify
44235
44136
 
44236
- sw.db applies caller scopes; sw.db.server bypasses them: authorize first.
44237
- Caller-scoped sw.db.insert needs no client.create grant: client limits only the browser.
44238
- Reads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).
44239
- Filter: { id: { in: ids } }; unique: [['a', 'b']] in schema.
44240
- Writes: insert(table, values), update(table, { where, set }), remove(table, { where }).
44241
- tx takes an ARRAY of write intents, never a callback; pre-generate related IDs.
44242
-
44243
- Browser: fetch(path, { method: 'POST', credentials: 'same-origin',
44244
- headers: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).
44245
- Access cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts
44246
- need Origin equal to the app URL.
44247
-
44248
- After every deploy the platform checks the live app in its own browser: pages load signed out and as a
44249
- test user, a stranger and a signed-out visitor cannot read a person's data, and your saved checks pass.
44250
- Save each journey you want re-checked after every deploy as checks/<plain-name>.json; the platform runs them
44251
- in its browser after each deploy and \`somewhere test\` runs them now.
44252
- ${FIRST_CLI_PERMISSION}
44253
- Run them now: npx @somewhere-cloud/cli test (one PASS or FAIL line per check, failures first; exit 1 when one fails).
44254
- A saved check is the somewhere verify --flow actions list; "signed_in": true runs it as a test user the platform
44255
- creates and removes, and "viewports": ["desktop", "mobile"] runs it at both sizes:
44256
- { "actions": [ { "fill": "[data-testid=note-title]", "value": "Lunch with Ana 42" },
44257
- { "click": "[data-testid=note-save]" },
44258
- { "expect": { "selector": "[data-testid=note-item]", "text": "Lunch with Ana 42" } } ],
44259
- "signed_in": true, "viewports": ["desktop", "mobile"] }
44260
- Find controls by data-testid so renaming a button does not break a check; keep the ids when you restyle.
44261
- The notes starter ships this one as checks/add-a-note.json (note-title, note-save, note-item): start from it.
44262
- Open a list item by clicking the item element itself (what a person clicks), not a link inside it.
44263
- Deploy raw source, no frontend build; type errors stop upload.
44264
- The complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.
44265
- Diagnose with somewhere errors and somewhere logs.
44266
-
44267
- On demand:
44268
- - Server paging: \`somewhere docs sw.db --section server-read-paging\`
44269
-
44270
- ## Testing shared access
44271
-
44272
- With the team endpoints above, the owner invites a fixture by email; test users are verified,
44273
- so its next GET /api/teams shows the team. A test user who still owns a team is not deleted:
44274
- delete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take
44275
- about a second, so raise the timeout:
44276
-
44277
- \`\`\`ts
44278
- // tests/team.spec.ts
44279
- import { test, expect } from '@somewhere-cloud/cli/testing';
44280
- test.describe.configure({ timeout: 90_000 });
44281
- test('owner invites a second user by email', async ({ newUser }) => {
44282
- const [owner, bob] = await Promise.all([newUser(), newUser()]);
44283
- const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();
44284
- expect((await owner.request.post(\`/api/teams/\${id}/invitations\`, { data: { email: bob.email } })).ok()).toBeTruthy();
44285
- const { teams } = await (await bob.request.get('/api/teams')).json();
44286
- expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));
44287
- expect((await owner.request.delete(\`/api/teams/\${id}\`)).status()).toBe(204);
44288
- });
44289
- \`\`\`
44290
- `;
44291
- SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44292
- PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44293
- MCP_POINTER = "Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.";
44294
- PREVIEW_POINTER = "somewhere preview runs your change on a copy of production data with its own sign-in: a preview starts with no users (sign up in it or `somewhere preview user-add`), its sign-in mail is captured (`somewhere preview mail`), and rows private to a production user stay hidden from preview users. Server user lookup, roles and built-in teams work in a preview (its own users, its own copy; team invitations are captured); jobs/cron handlers do not yet: check those in production after promoting (`somewhere docs dev-environments`). Test your change in the preview before you promote it: `somewhere test --preview`.";
44295
- TEST_ACCESS_RULES = `## Testing access rules
44137
+ Run \`somewhere typecheck\` and focused tests. \`somewhere deploy-check\` checks compilation and schema without publishing. \`somewhere deploy\` uploads raw source directly to production. When testing changes with real users or data, use \`somewhere preview\`, test with \`somewhere test --preview\`, then promote. See \`somewhere docs dev-environments\`.
44296
44138
 
44297
- In a linked test app, run \`somewhere test-users prepare alice bob\`. For an
44298
- owner() table with client create and read, create a fixture as Alice and read it
44299
- as both users:
44139
+ Save journeys in \`checks/<name>.json\`, using \`checks/add-a-note.json\` from the notes starter as a model. Keep test IDs when restyling and click the item a person would use. Set \`"signed_in": true\` for a test user and \`"viewports": ["desktop", "mobile"]\` to check both sizes. Saved checks run after deploy. Use \`somewhere test\` to rerun them and \`somewhere verify --flow flow.json\` for a focused journey. For shared access, test the owner, a recipient and an unrelated user separately. The team fixture is in \`somewhere docs sw.groups --section team-example\`. For schedules, trigger \`somewhere cron run <id> --wait\` before asserting its effects. Inspect failures with \`somewhere errors\` and \`somewhere logs\`.
44300
44140
 
44301
- \`\`\`sh
44302
- ID=$(somewhere data create notes --as alice --values '{"title":"Access test"}' | jq -er 'select(.status == 200 and .kind == "ok") | .data.id') &&
44303
- somewhere data get notes --as alice --id "$ID" | jq -e '.status == 200 and .kind == "ok"' &&
44304
- somewhere data get notes --as bob --id "$ID" | jq -e '.status == 200 and .kind == "empty" and .data == null and .access == {"filtered":true}'
44305
- \`\`\`
44306
-
44307
- 200 with access.filtered means the rule constrained the read, even when rows
44308
- are returned. 404 DATA_NOT_FOUND on update or delete hides whether the row
44309
- exists. 401 AUTH_REQUIRED needs a signed-in session. 403 names the access rule
44310
- or operation that refused the call. DATA_CONTRACT_* means the operation never
44311
- ran. Assert the exact outcome in handed-over tests and confirm a refused write
44312
- left the owner's fixture unchanged.
44141
+ Use \`somewhere docs <topic> --section <id>\` for one section or \`--full\` for all examples. Ask before destructive or paid actions unless the user already authorized them.
44313
44142
  `;
44143
+ SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44144
+ PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44145
+ MCP_POINTER = "App MCP tools: `somewhere docs app-mcp`.";
44146
+ PREVIEW_POINTER = "Preview users are separate from live users. Sign up in the preview or use `somewhere preview user-add`. Check captured mail with `somewhere preview mail`.";
44314
44147
  INIT_AGENTS_MD = `# somewhere.cloud project contract
44315
- ${FIRST_CLI_PERMISSION}
44316
-
44148
+ ${AGENT_WORKFLOW}
44317
44149
  ${SKILLS_POINTER}
44150
+ Without a global CLI, use \`npx @somewhere-cloud/cli deploy\` and \`npx @somewhere-cloud/cli test\`.
44318
44151
 
44319
- Build your app. Deploy the raw source and run its tests: \`npx @somewhere-cloud/cli deploy && npx @somewhere-cloud/cli test\`.
44320
-
44321
- For an app with sign-in, keep the starter's auth gate. Render private UI only after the session is confirmed. Keep the pending and retry views. In a browser test wait for the expected screen; if the SDK publishes \`data-sw-auth\` on \`<html>\`, first wait for the expected sign-in state there.
44152
+ For a signed-in browser test, wait for the SDK's expected \`data-sw-auth\` state when available. See \`somewhere docs auth-client --section wait-for-auth-in-a-browser-test\`. For direct data checks, prepare fixture users with \`somewhere test-users prepare alice bob\`, then call \`somewhere data get notes --as alice --id <id>\` as each user. Assert the exact outcome. See \`somewhere docs test --section testing-access-rules\`.
44322
44153
 
44323
- ${AGENT_WORKFLOW}
44324
- ${TEST_ACCESS_RULES}
44325
44154
  ${PORTABILITY_POINTER}
44326
44155
  ${MCP_POINTER}
44327
44156
  ${PREVIEW_POINTER}
@@ -44669,8 +44498,8 @@ var init_skills_pack_generated = __esm({
44669
44498
  BUNDLED_SKILLS_PACK = {
44670
44499
  "schema": 1,
44671
44500
  "name": "somewhere-skills",
44672
- "version": "1+c727c92e8193",
44673
- "sha256": "c727c92e81938d2e7cbf125de17c4d8a6feef4cf5bc4530f173f6dc04fe0da3e",
44501
+ "version": "1+30e51d444ef2",
44502
+ "sha256": "30e51d444ef28d9ad6eda0999739679f9fe13e9a102b8d908044694378bbfc96",
44674
44503
  "files": [
44675
44504
  {
44676
44505
  "path": "adopt/SKILL.md",
@@ -44679,18 +44508,18 @@ var init_skills_pack_generated = __esm({
44679
44508
  },
44680
44509
  {
44681
44510
  "path": "deploy-verify-loop/SKILL.md",
44682
- "sha256": "b394c2944cd64a48517dff6c80917b0e9332758f429e96600587ca91e4e951f8",
44683
- "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nBefore your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.\n\n```bash\nsomewhere typecheck\nsomewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44511
+ "sha256": "a8d6850065722efe3098ed54008d22066d8274338b037758d0d8490df7e68986",
44512
+ "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nAsk before destructive or paid actions unless the user already authorized them.\n\n```bash\nnpx somewhere typecheck\nnpx somewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44684
44513
  },
44685
44514
  {
44686
44515
  "path": "schema-changes/SKILL.md",
44687
- "sha256": "ab5a21715672de983d2bb1ed19822563a8d94fad936b2424f3653c0c087642b2",
44688
- "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nBefore the first deploy, delete an unused starter table declaration outright: there is no deployed table to retire. After a table has been deployed, mark it `removedTable()` to retire it with 30-day data retention, including when the table is empty.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44516
+ "sha256": "3b74e0482260cc6673f12a2d5105950357dab8d0d9960fd5de8a3f54a153faef",
44517
+ "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nDelete a never-deployed starter table's declaration and references. A `removedTable()` marker for it is a no-op. **Removing a table** is `old_table: removedTable()`. The deploy keeps the table while your previous version is still serving; once the new version is live it retires the table and keeps its data for 30 days.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44689
44518
  },
44690
44519
  {
44691
44520
  "path": "sign-in-setup/SKILL.md",
44692
- "sha256": "ffc4f29eb96c0a18c5ea0ce10308f696f227ec842c37e0bd70951b2284d885ba",
44693
- "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n await auth.signUp({ email, password }) // or auth.signIn({ email, password })\n return auth.getUser() // the signed-in user, or null\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44521
+ "sha256": "c0c2095f24ced94d6457389d4943b79cc101cc66adc60b23114944e3a64a0d71",
44522
+ "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n return auth.signUp({ email, password }) // or auth.signIn({ email, password })\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44694
44523
  },
44695
44524
  {
44696
44525
  "path": "troubleshooting/SKILL.md",
@@ -78246,7 +78075,8 @@ function checksJsonReport(check) {
78246
78075
  findings,
78247
78076
  sentence: findings.length !== (check?.findings?.length ?? 0) ? null : check?.sentence ?? null,
78248
78077
  passed: summary.outcome === "passed",
78249
- ...summary
78078
+ ...summary,
78079
+ not_checked: check?.not_checked ?? null
78250
78080
  };
78251
78081
  }
78252
78082
  function resultEvidence(line) {
@@ -78277,8 +78107,12 @@ function formatChecksReport(check) {
78277
78107
  if (!line.outcome && label === "Could not check")
78278
78108
  lines.push(` Run ${cliInvocation()} test --again to confirm this access check.`);
78279
78109
  }
78280
- for (const line of checks.filter((item) => lineOutcome(item) === "passed"))
78281
- lines.push(`PASS ${line.name}`);
78110
+ for (const line of checks.filter((item) => lineOutcome(item) === "passed")) {
78111
+ const observation = line.responses?.[0]?.observed || line.detail || "The stored result has no observation.";
78112
+ const label = check.not_checked ? line.name : `${line.method === "flow" ? "Browser flow" : line.method ?? "Check"} ${line.path ?? "(surface unavailable)"}`;
78113
+ const status = line.status ? ` (HTTP ${line.status})` : "";
78114
+ lines.push(`PASS ${label}${status} \u2014 ${observation}`);
78115
+ }
78282
78116
  for (const finding of functionWarnings(check)) {
78283
78117
  if (finding.kind === "crash") {
78284
78118
  lines.push(`Warning: A server function crashed: ${finding.via} (request ID ${finding.request_id}).`);
@@ -78296,7 +78130,31 @@ function formatChecksReport(check) {
78296
78130
  if (summary.counts.could_not_check && !lines.some((line) => line.startsWith("Could not check")))
78297
78131
  lines.push(`Could not check: run ${cliInvocation()} test --again to get named results.`);
78298
78132
  }
78299
- return [...lines, JSON.stringify(summary)];
78133
+ const coverage = check?.not_checked ?? null;
78134
+ if (coverage) {
78135
+ if (typeof check?.routes_discovered === "number")
78136
+ lines.push(`${check.routes_checked ?? 0} of ${check.routes_discovered} app routes had a completed read check.`);
78137
+ const { routes_without_read_check: reads, routes_without_write_check: writes, schedules_not_run: schedules, other } = coverage;
78138
+ if (reads === null || writes === null)
78139
+ lines.push("App route coverage could not be listed.");
78140
+ if (reads?.length)
78141
+ lines.push(`${reads.length} ${reads.length === 1 ? "route" : "routes"} without a read check (${reads.join(", ")}).`);
78142
+ if (writes?.length)
78143
+ lines.push(`${writes.length} ${writes.length === 1 ? "route" : "routes"} without a write check (${writes.join(", ")}).`);
78144
+ if (schedules === null)
78145
+ lines.push("Registered schedules could not be listed.");
78146
+ if (schedules?.length)
78147
+ lines.push(`${schedules.length} registered ${schedules.length === 1 ? "schedule" : "schedules"} did not run (${schedules.join(", ")}).`);
78148
+ if (other.length)
78149
+ lines.push(`Other checks skipped or out of scope: ${other.join(", ")}.`);
78150
+ } else {
78151
+ lines.push("Coverage details are unavailable for this run.");
78152
+ }
78153
+ return [...lines, JSON.stringify({
78154
+ ...summary,
78155
+ not_checked: coverage,
78156
+ ...coverage ? { routes_checked: check?.routes_checked, routes_discovered: check?.routes_discovered } : {}
78157
+ })];
78300
78158
  }
78301
78159
  var DEPLOY_CHECKS_POLL_MS, DEPLOY_CHECKS_RUNNING, TEST_CHECKS_WAIT_MS, cleanupFindings, functionWarnings;
78302
78160
  var init_deploy_checks = __esm({