Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions .agents/skills/hypercerts-org-sdk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: hypercerts-org-sdk
description: "Write Hypercerts and Certified records (org.hypercerts.*, app.certified.*) to a PDS from an app with @hypercerts-org/sdk: setting up the SDK context from an authenticated @atproto/lex Client, choosing the right operation and subpath, uploading blobs, and handling write errors without duplicates. Use when app code imports @hypercerts-org/sdk, or the user wants to create, link or write hypercert-related records from an app. Not for changing the SDK's own source."
metadata:
author: hypercerts-org
version: "4"
version: "5"
---

# @hypercerts-org/sdk
Expand Down Expand Up @@ -51,6 +51,7 @@ Make a new context when the signed-in account changes. Records are always writte
| `@hypercerts-org/sdk/tag` | `createVocabularyTag`, `createWorkScopeTag`, `RecordAlreadyExistsError`, the same `Write*` errors, input/result types |
| `@hypercerts-org/sdk/feature` | `createFeature`, `RecordAlreadyExistsError`, the same `Write*` errors, `FeatureInput`, `CreateFeatureResult`, `LeafletDocument` |
| `@hypercerts-org/sdk/organization` | `createOrganization`, `OrganizationAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `OrganizationInput`, `CreateOrganizationInput`, `CreateOrganizationResult`, `LeafletDocument` |
| `@hypercerts-org/sdk/social` | `followAccount`, `followEntity`, `like`, `repost`, `unfollowAccount`, `unfollowEntity`, `unlike`, `unrepost`, the `Write*` errors, `UndoResult` and input types |
| `@hypercerts-org/sdk/blob` | `uploadBlob` |
| `@hypercerts-org/sdk/collection` | `createCollection`, `createActivityInCollection`, `RecordAlreadyExistsError`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types |

Expand All @@ -69,12 +70,14 @@ Operations are grouped by domain, each under its own subpath. Read the domain's
| Feature (`org.hypercerts.entity.feature`, with its tags and locations) | `@hypercerts-org/sdk/feature` | [references/feature.md](references/feature.md) |
| Collection (create a Collection with items; add a new Activity to an existing Collection) | `@hypercerts-org/sdk/collection` | [references/collection.md](references/collection.md) |
| Organization (`app.certified.actor.organization`, with its profile and locations) | `@hypercerts-org/sdk/organization` | [references/organization.md](references/organization.md) |
| Social (follow accounts and records, like, repost, and undo them) | `@hypercerts-org/sdk/social` | [references/social.md](references/social.md) |

Three things to know before opening a reference:
Things to know before opening a reference:

- `createProfile` needs an OAuth scope with both `create` and `update` on `app.certified.actor.profile`. With only `create` it fails with `WriteRejectedError` (403).
- `location: { uri }` inside a location is a link to external data; a whole location given as `{ uri }` in `createActivity` reuses an existing record.
- `createOrganization` takes the name, avatar, banner and website in `profileIfMissing`, not in `organization`, and an existing location as `{ uri }`, never a bare string.
- Social functions take the **target** of the action: `{ targetDid }` for an account, `{ targetUri }` (a full record URI) for a record. Undo functions return `UndoResult` (`deleted`, `not-found` or `ambiguous`), not `void`.

## 5. Images and files

Expand Down Expand Up @@ -107,13 +110,13 @@ Uploads happen before the write and are not rolled back, so a call that throws c

Order of work: validate input → read `{ uri }` records → upload blobs → validate against lexicons → one write. The SDK never retries.

The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection` and `/organization` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three.
The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection`, `/organization` and `/social` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three.

| Error | Meaning | What to do |
| -------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------- |
| `TypeError` | Bad input. The message names the field (e.g. `contributors[1].weight`). Nothing written. | Fix the input. |
| `Error` | Not authenticated, a `{ uri }` record could not be read, or an upload failed. Nothing written. | Fix auth or the URI, then retry. |
| `WriteRejectedError` | PDS answered 4xx. Nothing created or changed. `status`, `code`. | Safe to fix and retry. `InvalidSwap`: see [Concurrent changes](#concurrent-changes-invalidswap). |
| `WriteRejectedError` | PDS answered 4xx. Nothing created or changed. `status`, `code`. | Safe to fix and retry. `InvalidSwap`: see [Concurrent changes](#concurrent-changes-invalidswap); undo functions also return it when the record changed after it was read, and calling again is safe. |
| `RecordAlreadyExistsError` | A key you chose is taken (a `WriteRejectedError`). `uri` names the record. Nothing written. | Use it as `{ uri }`, or choose another key. |
| `WriteOutcomeUnknownError` | Network error, timeout or 5xx. The records may exist. `attempted` lists every URI. | Check before retrying. |
| `WriteResultMismatchError` | Created, but the PDS reported other URIs/CIDs (`reported` vs `attempted`). | Do not retry. Log it and inspect the records. |
Expand Down Expand Up @@ -179,7 +182,7 @@ try {

- `createSDKContext({ client: session })` or passing an `@atproto/api` `Agent` throws. Wrap it: `new Client(session)`.
- Passing an `uploadBlob` result as `image` throws. Pass the `Blob`/`File`.
- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. `createFeature`, `createCollection` and `createWorkScopeTag` are not safe to repeat.
- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. Undo functions are safe to repeat too. `createFeature`, `createCollection`, `createWorkScopeTag`, `followAccount`, `followEntity`, `like` and `repost` are not safe to repeat.
- An item of `createCollection` is `{ activity }`, `{ feature }`, `{ collection }` or `{ uri }`, never a bare Activity input; `{ uri }` must be an Activity, Feature or Collection.
- A vocabulary tag's key is `<category>.<key>` exactly as you pass it. A dot in either part throws a `TypeError`; the SDK does not normalise the parts.
- A work-scope tag URI is not a vocabulary tag URI: each field accepts one collection, and a `{ uri }` of another throws a `TypeError`.
Expand All @@ -188,6 +191,6 @@ try {

## Verify

1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../tag` or `.../blob`.
1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../social`, `.../tag` or `.../blob`.
2. `tsc --noEmit` passes. The input types catch wrong field names and shapes.
3. `com.atproto.repo.getRecord` on each returned `uri` returns the record, and any references it holds match the URIs and CIDs the SDK returned.
90 changes: 90 additions & 0 deletions .agents/skills/hypercerts-org-sdk/references/social.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Social domain (`@hypercerts-org/sdk/social`)

Read [../SKILL.md](../SKILL.md) first for setup and error handling. Every example assumes `context` from `createSDKContext`.

The subpath covers `app.certified.graph.*` (follows) and `app.certified.feed.*` (likes, reposts). Each action has a create function and an undo function; all of them act on the signed-in account's own repo.

| Create | Undo | Record | Target | Stored `subject` |
| ------------------------------------- | --------------------------------------- | ----------------------------------- | --------------------------- | --------------------------------------------------- |
| `followAccount(context, { targetDid })` | `unfollowAccount(context, { targetDid })` | `app.certified.graph.follow` | an account's **DID** | the DID |
| `followEntity(context, { targetUri })` | `unfollowEntity(context, { targetUri })` | `app.certified.graph.entityFollow` | a **record URI** | the URI only, no CID: survives edits of the record |
| `like(context, { targetUri })` | `unlike(context, { targetUri })` | `app.certified.feed.like` | a **record URI** | URI and the CID the SDK read: pins that version |
| `repost(context, { targetUri })` | `unrepost(context, { targetUri })` | `app.certified.feed.repost` | a **record URI** | URI and the CID the SDK read: pins that version |

Create functions return `{ uri, cid }` of the **new social record**, not of the target. Callers never build a strong reference: pass the URI and the SDK reads the CID.

## Targets

- `targetDid` is an account **DID** (`did:plc:...`, `did:web:...`), typed `DidString`. A handle, a record URI or an object fails to compile in TypeScript, and throws `TypeError` at runtime for JavaScript callers or after a cast. Resolve a handle to a DID yourself first.
- A DID held as a plain `string` (a form field, a JSON response) does not compile either. Narrow it with `isDidString(did)` from `@atproto/lex` (`if (!isDidString(did)) throw ...`); do not cast.
- `targetUri` is a **full record URI**: `at://<did>/<collection>/<rkey>`, with a DID as the authority. A bare DID, a handle authority (`at://alice.bsky.social/...`) or a partial URI (no record key) throws `TypeError`. The record may be of any Lexicon.
- To follow an account use `followAccount`, not `followEntity`: `followEntity({ targetUri: "did:plc:..." })` throws.

```ts
import { followAccount, followEntity, like, repost } from "@hypercerts-org/sdk/social";

const activity = "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8";

await followAccount(context, { targetDid: "did:plc:abc123" }); // looks nothing up
await followEntity(context, { targetUri: activity }); // does not read the record, stores no CID
const liked = await like(context, { targetUri: activity }); // reads the record, pins its current CID
await repost(context, { targetUri: activity }); // same
console.log(liked.uri); // at://<your did>/app.certified.feed.like/<tid>
```

A like is social feedback only. It is not an evaluation, an acknowledgement or proof of endorsement; do not present it as one.

## Options

Create functions also take `createdAt` (ISO 8601, default: now) and `via`:

```ts
await like(context, {
targetUri: activity,
via: "at://did:plc:def456/app.certified.feed.repost/3k2a4b5c6d7e9", // how you came across it
});
```

`via` is the URI of the record through which the target was found (a repost, a starter pack, ...). The SDK reads it and stores a strong reference; it may be a record of any Lexicon. A `via` that cannot be read fails the call and nothing is written.

## Nothing is deduplicated

Each create call writes a new record under a new TID. Calling `like` twice for the same record creates two likes; the SDK does not look for an existing one and does not toggle. Check your own state first if the app must not create two.

## Undo and `UndoResult`

Undo functions return `UndoResult`, not `void`:

```ts
import { unlike } from "@hypercerts-org/sdk/social";

const result = await unlike(context, { targetUri: activity });
switch (result.status) {
case "deleted": // exactly one matching like existed and is gone
break;
case "not-found": // no matching like; nothing was deleted
break;
case "ambiguous": // result.matchCount likes match; NOTHING was deleted
// The account liked it more than once. Delete the extras yourself (com.atproto.repo.deleteRecord), then call again.
break;
}
```

- The SDK lists **all** records of that collection in your own repo (every page, from your PDS, no indexer) and matches by subject: DID for follows, record URI for entity follows, likes and reposts. The CID a like or repost pinned is ignored, so a like of an older version of an edited record is found.
- The target is **not** read, so a deleted or edited target does not stop you removing the like or follow.
- Exactly one match is deleted, only if it still has the CID the scan saw. If it changed in between, the call throws `WriteRejectedError` with `code === "InvalidSwap"` and nothing is deleted; call again to scan afresh.
- A page that fails to load or looks wrong throws `Error`. It is never treated as "not found".
- The scan is a snapshot. It cannot stop another writer creating a matching record meanwhile, so `deleted` does not promise that none remains.
- `WriteOutcomeUnknownError` from an undo: `attempted` is the record the SDK tried to delete. Calling the undo again is safe: it either deletes the record or returns `not-found`. For create functions it is not safe to repeat; see [Handle failures](../SKILL.md#6-handle-failures).
- The session needs permission to **delete** the collection (`app.certified.graph.follow`, `...graph.entityFollow`, `...feed.like`, `...feed.repost`) to undo, and to create it to create.

## Input fields

| Field | Used by | Type | Notes |
| ------------ | -------------------------------------------- | -------- | --------------------------------------------------------------------------------------- |
| `targetDid` | `followAccount`, `unfollowAccount` | `DidString` (from `@atproto/lex`) | Required. A DID, not a handle. |
| `targetUri` | `followEntity`, `like`, `repost` and their undo functions | `string` | Required. Full record URI with a DID authority. |
| `createdAt` | create functions | `string` | Optional. ISO 8601 date-time. Default: time of the call. |
| `via` | create functions | `string` | Optional. Record URI, read and pinned by the SDK. Any Lexicon. |

Unknown fields throw `TypeError`. Undo functions accept only the target.
7 changes: 7 additions & 0 deletions .changeset/social-follows-likes-reposts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@hypercerts-org/sdk": minor
---

- Add `followAccount`, `followEntity`, `like` and `repost` at `@hypercerts-org/sdk/social`, with an optional `via` record URI that the SDK pins.
- Add `unfollowAccount`, `unfollowEntity`, `unlike` and `unrepost`. They scan the account's own repository and return `UndoResult` (`deleted`, `not-found` or `ambiguous`); with several matching records nothing is deleted.
- Deletions are guarded by the record's CID; a concurrent change throws `WriteRejectedError` with `code` `"InvalidSwap"`.
4 changes: 4 additions & 0 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
"types": "./dist/organization/index.d.ts",
"default": "./dist/organization/index.js"
},
"./social": {
"types": "./dist/social/index.d.ts",
"default": "./dist/social/index.js"
},
"./tag": {
"types": "./dist/tag/index.d.ts",
"default": "./dist/tag/index.js"
Expand Down
35 changes: 35 additions & 0 deletions packages/sdk/src/internal/submit-writes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { fakeRepo, HEAD, methods } from "../test-utils/fake-repo.js";
import { prepareRecord, prepareUpdate } from "./prepare-record.js";
import {
submitCreateOnly,
submitDelete,
submitWrites,
WriteOutcomeUnknownError,
WriteRejectedError,
Expand Down Expand Up @@ -183,3 +184,37 @@ describe("submitCreateOnly", () => {
expect(error.reported).toEqual([{ uri: record.ref.uri, cid: CID }]);
});
});

describe("submitDelete", () => {
const ref = { uri: `at://${DID}/app.certified.feed.like/3k2a4b5c6d7e8` as const, cid: CID };

it("treats an HTTP 4xx other than a conflict as a definite rejection, naming what was not deleted", async () => {
const { context } = fakeRepo({
deleteRecord: () => json(403, { error: "Forbidden", message: "no delete permission" }),
});

const error = await submitDelete(context, DID, ref, "op").catch((e) => e);

expect(error).toBeInstanceOf(WriteRejectedError);
expect(error).toMatchObject({ status: 403, code: "Forbidden", attempted: [ref] });
expect(error.message).toContain(`${ref.uri} was not deleted`);
});

it.each([
["HTTP 408", () => json(408, { error: "RequestTimeout", message: "slow" })],
[
"a network failure",
() => {
throw new TypeError("fetch failed");
},
],
])("treats %s as an unknown outcome", async (_, deleteRecord) => {
const { context } = fakeRepo({ deleteRecord });

const error = await submitDelete(context, DID, ref, "op").catch((e) => e);

expect(error).toBeInstanceOf(WriteOutcomeUnknownError);
expect(error.attempted).toEqual([ref]);
expect(error.message).toContain(`whether ${ref.uri} was deleted`);
});
});
Loading
Loading