## Building an app

A Techne app is an ordinary atproto app: records live in each user's repo on their PDS; the platform indexes them,
applies permissions and serves reads. SDK: `npm i techne-sdk` (also a Rust crate); docs:
https://techne.computer/docs/quickstart.html. In order: find or publish the type (publishing is a signed-in call,
see Types), host the client metadata, sign in naming the types you write, `put`, read back.

### Sign-in

Standard atproto OAuth, no registration. The app is its client metadata URL (`client_id`): name, logo and homepage
come from that document; its `scope` is `atproto`, one `repo:<nsid>` per type it writes, and for
private data the permissioned methods (`include:pub.techne.draft.authPermissioned`) plus a
`space:` scope (see Private and shared data). The SDK builds this least-privilege list for you (`scopes()`, the
default of `signIn` and `clientMetadata`; see Permissions). In the SDK, `connect(session, TECHNE_PLATFORM_DID)`
(`did:web:techne.computer`, from `techne-sdk/auth`) gives the clients over the signed-in session.

On techne.town (our PDS) the consent page says "Built by Techne" only for our own listed apps; any other app gets a
community-app warning scaled to its scope.

Mobile apps use Universal Links (iOS) or App Links (Android) for the OAuth redirect. In development, atproto's
loopback client (`client_id` `http://localhost?...`, redirect to `http://127.0.0.1`) needs no hosted metadata. Its
`client_id` carries its scope and redirect, so its private app space changes when the port or the types change. It is
for development only: a loopback `client_id` is not an app identity (any app can present the same one). The browser
keeps one stored session per origin: sign out before switching client ids on one origin. Ship with hosted client
metadata.

### Types

Three ways to a type:

1. **Use an indexed one.** `pub.techne.draft.registry.listTypes` {q} searches names, fields and purposes (most used
   first); `pub.techne.draft.registry.getType` {nsid} gives the lexicon, query roles, creator, state, record count
   and sidecars. People browse the same list on techne.pub (https://techne.pub/community.html).
2. **Publish a community draft.** `pub.techne.draft.registry.publishType` {name, lexicon, query}, signed in (an app
   asks for it with the SDK's `scopes({ publish: true })` and calls it through `techne.platform`; the answer's
   `nsid` then goes in `types` for the sign-in that writes it), makes
   `pub.techne.draft.c.<id>.<name>` (random id), indexed from then on. Send `query` (which fields are the start,
   end, location, text, references, category); without it records can only be got and listed. Only you may change
   it (publishType again with its `nsid`, additive changes only); anyone may fork it (`forkOf`). One publish a
   minute per account (bursts of 10):

       call("pub.techne.draft.registry.publishType", { name: "toolListing",
         lexicon: { lexicon: 1, defs: { main: { type: "record", key: "tid", record: { type: "object",
           required: ["title", "createdAt"], properties: { title: { type: "string", maxLength: 200 },
           createdAt: { type: "string", format: "datetime" } } } } } },
         query: { lexicon: 1, defs: { main: { type: "queryDocument", roles: { text: "title" } } } } })

3. **Request an existing NSID** from the network: `pub.techne.draft.registry.requestType` {nsid, query}. Its schema
   must be published (`_lexicon` TXT record, `com.atproto.lexicon.schema` record). Build at once: while pending,
   records written through the platform (SDK `put`, the door's `com.atproto.repo.applyWrites`, or a hint) are
   indexed under the real name. An operator approves (its existing records on the network are then read in; new
   network writes follow once a release subscribes to the type) or declines (still written-through only).
   `pub.techne.draft.registry.getTypeRequest` {nsid} shows where it stands. Find types we
   don't index on Lexicon Garden (https://lexicon.garden); see who writes one with
   `com.atproto.sync.listReposByCollection` {collection} on a relay (https://bsky.network).

### Sidecars

To extend someone else's type, publish a sidecar (`sidecarOf`): your own type whose records carry `subject` (the
record extended). "Would this be a field on their record?" means a sidecar; "do people make many?" means its own
type. `listTypes` {sidecarOf} finds a type's sidecars.

### Always share the page

Every registry answer carries `page`, the type's techne.pub page. Share it.

### Write

Write into the user's repo, on their PDS. The SDK's `put` writes, then hints `pub.techne.draft.sync.indexRecord`
{uri} so the record is indexed at once rather than when the relay brings it. After a delete on the PDS, hint the
same uri: the platform reads the PDS's proof it is gone and drops it (a pending type's deletes arrive no other way).
`npx techne-sdk types <nsid>` prints code types for any type.

### Private and shared data

Private records belong to the user (`repo` is theirs) but stay off the public network: the platform stores and
serves them. Each one is written for a space, `at://{authority}/{spaceType}/{key}`: the authority owns the space, the author wrote the record,
and they need not be the same person. A space type's policy decides who reads and writes there, from claims
(memberships, shares). Every write names its space (`space`); one that names none is 400 `InvalidRequest`. A
public record goes through `com.atproto.repo.putRecord` on the PDS instead, and a record only the user reads goes in
their personal space, `at://{user}/pub.techne.draft.space.personal/self`. Writes are never refused for the space
they name: the space admits the record or it counts nowhere, and the answer says which (`space` is absent when not
admitted). Calls: `pub.techne.draft.permissioned.putRecord`,
`putRecords`, `deleteRecord`, `getRecord`, `listRecords`, `listChanges`.

Three options today:

- Public: ordinary repo records, read by anyone.
- Your app's own space per user: `at://{user}/pub.techne.draft.space.private/{appKey}`, where `appKey` is your
  `client_id` hashed: base32 (lowercase, no padding) of its SHA-256. Ask for
  `space:pub.techne.draft.space.private?skey={appKey}`. Only that user reads it, and only through your app: the
  platform admits and serves a record there only for the app its key names. Any collection but the platform's own
  record types (400 `InvalidRequest`); the adopted calendar types are allowed and stay your app's data.
- Everything the user can reach: `include:pub.techne.draft.authRead` or `authWrite`: their personal space, their
  circles, beacons shared with them. The consent page shows a large warning; ask only if the app needs it.

A token that carries `space:` scopes reaches only the spaces they cover: other writes are 403 `Forbidden`, other
records are not returned. This works for users on techne.town (our PDS puts your `client_id` and granted scopes on
the call); users on other PDSes cannot use an app space yet. An agent token names no app, so test app-space calls
from the app.

The path from here: apps approved per space (a circle lets your app in), then full permissioned data for community
apps when spaces move to the 0016 address format, always with a clear warning on consent.

### Permissions

What an app asks for decides what it can do and which consent page the person sees. Ask for the least that works.

- `atproto`: required; signs the person in. Reaches nothing by itself.
- `repo:<nsid>` (one per type the app writes): create, edit and delete those public records in the person's repo.
- `include:pub.techne.draft.authPermissioned`: the `permissioned.*` calls (private writes, reads, deletes, changes,
  grants). It reaches only the spaces the `space:` scopes name.
- `space:pub.techne.draft.space.private?skey=<appKey>`: the app's own private space, which no other app sees
  (`appKey` = base32 of the SHA-256 of the `client_id`; SDK `appKey`, `appSpace`). Any other `space:` scope reaches
  other private data.
- `rpc:<method>?aud=did:web:techne.computer%23atproto_appview`: one platform call. The SDK asks for
  `query.listRecords`, `countRecords`, `getRecords`, `registry.getType`, `listTypes`, `sync.indexRecord` (with
  types) and `registry.publishType` (with `publish: true`). The platform narrows the queries to public data and
  the app's own space.
- `include:pub.techne.draft.authRead`: read everything the person may see through the platform, private spaces
  they belong to included (SDK `everything: 'read'`).
- `include:pub.techne.draft.authWrite`: write every public `pub.techne` record and private ones in any space they
  can write (SDK `everything: 'write'`, with authRead).
- `include:pub.techne.draft.authCommons` and `authOperator`: the Commons API's views, and its operator actions
  (refused for anyone who is not an operator).

On techne.town the consent page shows one of three community banners: public records only; public records plus
the app's own space; or a red warning when the app can read or write other private data (authRead, authWrite, any
other `space:` scope, or a call we can't bound). The SDK's defaults, with `types` and `publish`, stay off the red one.

### Read

`pub.techne.draft.query.listRecords`, `getRecords`, `countRecords` and `pub.techne.draft.query.composeRecords` take
a query as a JSON string, for example:

    {"where":{"all":[{"type":{"is":"<nsid>"}},{"author":{"is":"$viewer"}}]}}

Short form, as other sections write it: `{type is X, author is $viewer}`. Besides type and author, a query
filters and orders on roles (start, end, location, text, references, category), which a type's query document maps
to its fields. A leaf names one role and one operator: `is`, `in` (a list), `after` and `before` (RFC 3339 or
`$now`), `near` ({point: "lat,lng", within: "5km"}, at most 50km) and `matches` (words of the text); `all`, `any`
and `not` combine leaves, and `order` names one role, a `near`/`matches` measure or `shuffle`. `$now` and
`$viewer` are the platform's; pass your own `$params` in `params`. The full grammar is the
`pub.techne.draft.query` lexicon (`registry.getType` {nsid: "pub.techne.draft.query"}).

### State two people share

A loan, a booking, a handover: each person writes only in their own repo, and the state is derived from the pair.
To lend a tool, the lender writes a `loan` (`subject` the listing, `borrower` a DID); the borrower writes an
`acceptance` whose `subject` is the loan's uri. "On loan" means both exist (a loan alone is an offer). The return is
the lender's own `return` naming the loan; either side withdraws by deleting their record. Map `subject` to the
references role and query both types by it.

### Limits

Writes have a per-account rate (429). Indexing of a community or requested type has daily budgets (by default 5000
records per author and 200000 per type); a record over budget is skipped, and `pub.techne.draft.query.listRejections`
names it with reason `budget`.
