@harperfast/skills 1.6.1 → 1.7.0

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/dist/index.js CHANGED
@@ -29,28 +29,28 @@ export const ruleNames = [
29
29
  */
30
30
  export const rules = {
31
31
  "adding-tables-with-schemas": "---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n\tid: ID @primaryKey\n\tname: String\n\ttag: String @indexed\n}\n```\n",
32
- "automatic-apis": "---\nname: automatic-apis\ndescription: How to use Harper's automatically generated REST and WebSocket APIs.\nmetadata:\n mode: synthesized\n---\n\n# Automatic APIs\n\nInstructions for the agent to follow when utilizing Harper's automatic APIs.\n\n## When to Use\n\nUse this skill when you want to interact with Harper tables via REST or WebSockets without writing custom resource logic. This is ideal for basic CRUD operations and real-time updates.\n\n## How It Works\n\n1. **Enable REST in `config.yaml`**: REST endpoints are **not active by default**. You must explicitly enable them:\n ```yaml\n rest: true\n ```\n Without this, `@export`ed tables will not respond to HTTP requests.\n2. **Enable Automatic APIs**: Ensure your GraphQL schema includes the `@export` directive for the table.\n3. **Access REST Endpoints**: Use the standard endpoints for your table (Note: Paths are case-sensitive).\n4. **Use Automatic WebSockets**: Connect to `wss://your-harper-instance/{TableName}` to receive events whenever updates are made to that table. This is the easiest way to add real-time capabilities. (Use `ws://` for local development without SSL). For more complex needs, see [Real-time Apps](real-time-apps.md).\n5. **Apply Filtering and Querying**: Use query parameters with `GET /{TableName}/` and `DELETE /{TableName}/`. See the [Querying REST APIs](querying-rest-apis.md) skill for advanced details.\n6. **Customize if Needed**: If the automatic APIs don't meet your requirements, [customize the resources](./custom-resources.md).\n\n## Examples\n\n### Schema Configuration\n\n```graphql\ntype MyTable @table @export {\n\tid: ID @primaryKey\n\tname: String\n}\n```\n\n### Common REST Operations\n\n- **List Records**: `GET /MyTable/`\n- **Create Record**: `POST /MyTable/`\n- **Update Record**: `PATCH /MyTable/{id}`\n",
33
- "caching": "---\nname: caching\ndescription: How to implement integrated data caching in Harper from external sources.\nmetadata:\n mode: synthesized\n---\n\n# Caching\n\nInstructions for the agent to follow when implementing caching in Harper.\n\n## When to Use\n\nUse this skill when you need high-performance, low-latency storage for data from external sources. It's ideal for reducing API calls to third-party services, preventing cache stampedes, and making external data queryable as if it were native Harper tables.\n\n## How It Works\n\n1. **Configure a Cache Table**: Define a table in your `schema.graphql` with an `expiration` (in seconds).\n2. **Define an External Source**: Create a Resource class that fetches the data from your source.\n3. **Attach Source to Table**: Use `sourcedFrom` to link your resource to the table.\n4. **Implement Active Caching (Optional)**: Use `subscribe()` for proactive updates. See [Real-Time Apps](real-time-apps.md).\n5. **Implement Write-Through Caching (Optional)**: Define `put` or `post` in your resource to propagate updates upstream.\n\n## Examples\n\n### Schema Configuration\n\n```graphql\ntype MyCache @table(expiration: 3600) @export {\n\tid: ID @primaryKey\n}\n```\n\n### Resource Implementation\n\n```js\nimport { Resource, tables } from 'harper';\n\nexport class ThirdPartyAPI extends Resource {\n\tasync get() {\n\t\tconst id = this.getId();\n\t\tconst response = await fetch(`https://api.example.com/items/${id}`);\n\t\tif (!response.ok) {\n\t\t\tthrow new Error('Source fetch failed');\n\t\t}\n\t\treturn await response.json();\n\t}\n}\n\n// Attach source to table\ntables.MyCache.sourcedFrom(ThirdPartyAPI);\n```\n",
34
- "checking-authentication": "---\nname: checking-authentication\ndescription: How to handle user authentication and sessions in Harper Resources.\nmetadata:\n mode: synthesized\n---\n\n# Checking Authentication\n\nInstructions for the agent to follow when handling authentication and sessions.\n\n## When to Use\n\nUse this skill when you need to implement sign-in/sign-out functionality, protect specific resource endpoints, or identify the currently logged-in user in a Harper application.\n\n## How It Works\n\n1. **Configure Harper for Sessions**: Ensure `harper-config.yaml` has sessions enabled and local auto-authorization disabled for testing:\n ```yaml\n authentication:\n authorizeLocal: false\n enableSessions: true\n ```\n2. **Implement Sign In**: Use `this.getContext().login(username, password)` to create a session:\n ```typescript\n async post(_target, data) {\n const context = this.getContext();\n try {\n await context.login(data.username, data.password);\n } catch {\n return new Response('Invalid credentials', { status: 403 });\n }\n return new Response('Logged in', { status: 200 });\n }\n ```\n3. **Identify Current User**: Use `this.getCurrentUser()` to access session data:\n ```typescript\n async get() {\n const user = this.getCurrentUser?.();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n }\n ```\n4. **Implement Sign Out**: Use `this.getContext().logout()` or delete the session from context:\n ```typescript\n async post() {\n const context = this.getContext();\n await context.session?.delete?.(context.session.id);\n return new Response('Logged out', { status: 200 });\n }\n ```\n5. **Protect Routes**: In your Resource, use `allowRead()`, `allowUpdate()`, etc., to enforce authorization logic based on `this.getCurrentUser()`. For privileged actions, verify `user.role.permission.super_user`.\n\n## Examples\n\n### Sign In Implementation\n\n```typescript\nasync post(_target, data) {\n const context = this.getContext();\n try {\n await context.login(data.username, data.password);\n } catch {\n return new Response('Invalid credentials', { status: 403 });\n }\n return new Response('Logged in', { status: 200 });\n}\n```\n\n### Identify Current User\n\n```typescript\nasync get() {\n const user = this.getCurrentUser?.();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n}\n```\n\n### Sign Out Implementation\n\n```typescript\nasync post() {\n const context = this.getContext();\n await context.session?.delete?.(context.session.id);\n return new Response('Logged out', { status: 200 });\n}\n```\n\n## Status code conventions used here\n\n- 200: Successful operation. For `GET /me`, a `200` with empty body means “not signed in”.\n- 400: Missing required fields (e.g., username/password on sign-in).\n- 401: No current session for an action that requires one (e.g., sign out when not signed in).\n- 403: Authenticated but not authorized (bad credentials on login attempt, or insufficient privileges).\n\n## Client considerations\n\n- Sessions are cookie-based; the server handles setting and reading the cookie via Harper. If you make cross-origin requests, ensure the appropriate `credentials` mode and CORS settings.\n- If developing locally, double-check the server config still has `authentication.authorizeLocal: false` to avoid accidental superuser bypass.\n\n## Token-based auth (JWT + refresh token) for non-browser clients\n\nCookie-backed sessions are great for browser flows. For CLI tools, mobile apps, or other non-browser clients, it’s often easier to use **explicit tokens**:\n\n- **JWT (`operation_token`)**: short-lived bearer token used to authorize API requests.\n- **Refresh token (`refresh_token`)**: longer-lived token used to mint a new JWT when it expires.\n\nThis project includes two Resource patterns for that flow:\n\n### Issuing tokens: `IssueTokens`\n\n**Description / use case:** Generate `{ refreshToken, jwt }` either:\n\n- with an existing Authorization token (either Basic Auth or a JWT) and you want to issue new tokens, or\n- from an explicit `{ username, password }` payload (useful for direct “login” from a CLI/mobile client).\n\n```javascript\nexport class IssueTokens extends Resource {\n\tstatic loadAsInstance = false;\n\n\tasync get(target) {\n\t\tconst { refresh_token: refreshToken, operation_token: jwt } =\n\t\t\tawait databases.system.hdb_user.operation(\n\t\t\t\t{ operation: 'create_authentication_tokens' },\n\t\t\t\tthis.getContext(),\n\t\t\t);\n\t\treturn { refreshToken, jwt };\n\t}\n\n\tasync post(target, data) {\n\t\tif (!data.username || !data.password) {\n\t\t\tthrow new Error('username and password are required');\n\t\t}\n\n\t\tconst { refresh_token: refreshToken, operation_token: jwt } =\n\t\t\tawait databases.system.hdb_user.operation({\n\t\t\t\toperation: 'create_authentication_tokens',\n\t\t\t\tusername: data.username,\n\t\t\t\tpassword: data.password,\n\t\t\t});\n\t\treturn { refreshToken, jwt };\n\t}\n}\n```\n\n**Recommended documentation notes to include:**\n\n- `GET` variant: intended for “I already have an Authorization token, give me new tokens”.\n- `POST` variant: intended for “I have credentials, give me tokens”.\n- Response shape:\n - `refreshToken`: store securely (long-lived).\n - `jwt`: attach to requests (short-lived).\n\n### Refreshing a JWT: `RefreshJWT`\n\n**Description / use case:** When the JWT expires, the client uses the refresh token to get a new JWT without re-supplying username/password.\n\n```javascript\nexport class RefreshJWT extends Resource {\n\tstatic loadAsInstance = false;\n\n\tasync post(target, data) {\n\t\tif (!data.refreshToken) {\n\t\t\tthrow new Error('refreshToken is required');\n\t\t}\n\n\t\tconst { operation_token: jwt } = await databases.system.hdb_user.operation({\n\t\t\toperation: 'refresh_operation_token',\n\t\t\trefresh_token: data.refreshToken,\n\t\t});\n\t\treturn { jwt };\n\t}\n}\n```\n\n**Recommended documentation notes to include:**\n\n- Requires `refreshToken` in the request body.\n- Returns a new `{ jwt }`.\n- If refresh fails (expired/revoked), client must re-authenticate (e.g., call `IssueTokens.post` again).\n\n### Suggested client flow (high-level)\n\n1. **Sign in (token flow)**\n - POST /IssueTokens/ with a body of `{ \"username\": \"your username\", \"password\": \"your password\" }` or GET /IssueTokens/ with an existing Authorization token.\n - Receive `{ jwt, refreshToken }` in the response\n2. **Call protected APIs**\n - Send the JWT with each request in the Authorization header (as your auth mechanism expects)\n3. **JWT expires**\n - POST /RefreshJWT/ with a body of `{ \"refreshToken\": \"your refresh token\" }`.\n - Receive `{ jwt }` in the response and continue\n\n## Quick checklist\n\n- [ ] Public endpoints explicitly `allowRead`/`allowCreate` as needed.\n- [ ] Sign-in uses `context.login` and handles 400/403 correctly.\n- [ ] Protected routes call `ensureSuperUser(this.getCurrentUser())` (or another role check) before doing work.\n- [ ] Sign-out verifies a session and deletes it.\n- [ ] `authentication.authorizeLocal` is `false` and `enableSessions` is `true` in Harper config.\n- [ ] If using tokens: `IssueTokens` issues `{ jwt, refreshToken }`, `RefreshJWT` refreshes `{ jwt }` with a `refreshToken`.\n",
32
+ "automatic-apis": "---\nname: automatic-apis\ndescription: How to use Harper's automatically generated REST and WebSocket APIs.\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/overview.md\n - reference/v5/rest/websockets.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 8fcf0cfe190e013e\n---\n\n# Automatic APIs\n\nInstructions for the agent to follow when enabling and using Harper's automatically generated REST and WebSocket APIs.\n\n## When to Use\n\nApply this rule when adding REST or WebSocket API access to Harper tables or custom resources. Use it when configuring `config.yaml` to expose endpoints, mapping HTTP methods to resource operations, or implementing real-time WebSocket connections on a resource class.\n\n## How It Works\n\n1. **Enable the REST plugin**: Add `rest: true` to your application's `config.yaml`. This activates the HTTP REST interface and enables WebSocket support by default.\n\n ```yaml\n rest: true\n ```\n\n To configure optional behavior:\n\n ```yaml\n rest:\n lastModified: true # enables Last-Modified response header support\n webSocket: false # disables automatic WebSocket support (enabled by default)\n ```\n\n2. **Export your resource in the schema**: Tables are not exposed by default. Use the `@export` directive in your schema definition to make a table available as a REST endpoint. The exported name defines the base URL path, served on the application HTTP server port (default `9926`).\n\n3. **Use the correct URL structure**: The REST interface follows a consistent path convention.\n\n | Path | Description |\n | -------------------------------------------- | ---------------------------------------------------------------------------------- |\n | `/my-resource` | Returns a description of the resource (e.g., table metadata) |\n | `/my-resource/` | Trailing slash — represents the full collection; append query parameters to search |\n | `/my-resource/record-id` | A specific record identified by its primary key |\n | `/my-resource/record-id/` | Trailing slash — collection of records with the given id prefix |\n | `/my-resource/record-id/with/multiple/parts` | Record id with multiple path segments |\n\n4. **Map HTTP methods to operations**: Each HTTP method maps to a resource method and operation.\n - **GET** — Retrieve a record or search. Calls `get()`.\n\n ```\n GET /MyTable/123\n GET /MyTable/?name=Harper\n GET /MyTable/123.propertyName\n ```\n\n Responses include an `ETag` header. Clients may send `If-None-Match` to receive `304 Not Modified` when the record is unchanged.\n\n - **PUT** — Create or replace a record (upsert). Calls `put(record)`. Properties not in the body are removed.\n\n ```\n PUT /MyTable/123\n Content-Type: application/json\n\n { \"name\": \"some data\" }\n ```\n\n - **POST** — Create a new record without specifying a primary key. Calls `post(data)`. The assigned key is returned in the `Location` response header.\n\n ```\n POST /MyTable/\n Content-Type: application/json\n\n { \"name\": \"some data\" }\n ```\n\n - **PATCH** — Partially update a record, merging only provided properties. Unspecified properties are preserved.\n\n ```\n PATCH /MyTable/123\n Content-Type: application/json\n\n { \"status\": \"active\" }\n ```\n\n - **DELETE** — Delete a record or all records matching a query.\n ```\n DELETE /MyTable/123\n DELETE /MyTable/?status=archived\n ```\n\n5. **Access the auto-generated OpenAPI spec**: Harper generates an OpenAPI specification for all exported resources. Retrieve it at:\n\n ```\n GET /openapi\n ```\n\n6. **Connect via WebSocket**: When `rest` is enabled, WebSocket support is on by default. Connect to a resource URL to subscribe to change events for that resource.\n\n ```javascript\n let ws = new WebSocket('wss://server/my-resource/341');\n ws.onmessage = (event) => {\n \tlet data = JSON.parse(event.data);\n };\n ```\n\n Connecting to `wss://server/my-resource/341` accesses the `my-resource` resource with record id `341` and subscribes to it. When the record changes or a message is published to it, the WebSocket connection receives the update.\n\n7. **Implement a custom `connect()` handler**: Override `connect(incomingMessages)` on a resource class to control WebSocket behavior. The method must return an async iterable or generator that produces messages to send to the client.\n\n## Examples\n\n**Simple echo server using an async generator**:\n\n```javascript\nexport class Echo extends Resource {\n\tasync *connect(incomingMessages) {\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield message; // echo each message back\n\t\t}\n\t}\n}\n```\n\n**Using the default `connect()` with event-style access and a timer**:\n\n```javascript\nexport class Example extends Resource {\n\tconnect(incomingMessages) {\n\t\tlet outgoingMessages = super.connect();\n\n\t\tlet timer = setInterval(() => {\n\t\t\toutgoingMessages.send({ greeting: 'hi again!' });\n\t\t}, 1000);\n\n\t\tincomingMessages.on('data', (message) => {\n\t\t\toutgoingMessages.send(message); // echo incoming messages\n\t\t});\n\n\t\toutgoingMessages.on('close', () => {\n\t\t\tclearInterval(timer);\n\t\t});\n\n\t\treturn outgoingMessages;\n\t}\n}\n```\n\n**Minimal `config.yaml` enabling REST with WebSocket disabled**:\n\n```yaml\nrest:\n webSocket: false\n```\n\n## Notes\n\n- Tables must be explicitly exported using `@export` in the schema — they are not exposed by default.\n- `rest: true` is the minimal configuration to enable both REST and WebSocket support. See [real-time-apps.md](real-time-apps.md) for patterns around real-time WebSocket usage.\n- For full query syntax on `GET` and `DELETE` with query parameters, see [querying-rest-apis.md](querying-rest-apis.md).\n- The default `connect()` returns an iterable with a `send(message)` method and a `close` event for cleanup on disconnect.\n- For MQTT over WebSockets, set the sub-protocol header `Sec-WebSocket-Protocol: mqtt`.\n- In distributed environments, non-retained messages are delivered in the order received per node; retained messages (PUT/updated records) keep only the latest-timestamp version as the winning record across the cluster.\n- Use the `Content-Type` request header to specify body format and the `Accept` header to request a specific response format.\n",
33
+ "caching": "---\nname: caching\ndescription: How to implement integrated data caching in Harper from external sources.\nmetadata:\n mode: generate\n sources:\n - learn/developers/caching-with-harper.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 8212a7d7dbbd2b18\n---\n\n# Caching External Data Sources in Harper\n\nInstructions for the agent to implement integrated data caching in Harper by wrapping external sources with a cache table and `sourcedFrom`.\n\n## When to Use\n\nApply this rule when a Harper application needs to cache responses from an external API, microservice, or database to avoid repeated slow or expensive upstream calls. Use it whenever you need to define TTL-based cache expiration, observe ETag-based conditional responses, or manually invalidate cached entries.\n\n## How It Works\n\n1. **Define a cache table with `expiration`**: In `schema.graphql`, add the `expiration` argument to `@table`. The value is in seconds. Any record older than this threshold is considered stale and will be re-fetched on next access.\n\n ```graphql\n type JokeCache @table(expiration: 60) @export {\n \tid: ID @primaryKey\n \tsetup: String\n \tpunchline: String\n }\n ```\n\n2. **Wrap the external source in `resources.js`**: Create an object with a `get(id)` method that fetches from the upstream source. Then call `sourcedFrom` on the table to register it.\n\n ```javascript\n const jokeAPI = {\n \tasync get(id) {\n \t\tconst response = await fetch(`https://official-joke-api.appspot.com/jokes/${id}`);\n \t\treturn response.json();\n \t},\n };\n\n tables.JokeCache.sourcedFrom(jokeAPI);\n ```\n\n Harper's caching behavior after `sourcedFrom` is registered:\n - A request arrives for `/JokeCache/1`.\n - Harper checks if the record with id `1` exists in `JokeCache` and is not stale.\n - If fresh, Harper returns it immediately.\n - If missing or stale, Harper calls `jokeAPI.get()`, stores the result in `JokeCache`, and returns it.\n - Multiple simultaneous requests for the same missing or stale record wait on a single upstream call — Harper prevents cache stampedes automatically.\n\n3. **Configure plugins in `config.yaml`**: Enable the schema, REST API, and JS resource plugins.\n\n ```yaml\n graphqlSchema:\n files: 'schema.graphql'\n rest: true\n jsResource:\n files: 'resources.js'\n ```\n\n4. **Observe caching via ETags**: Harper automatically computes an ETag from the record's last-modified timestamp. On the first request you receive a `200` with an `etag` header. Pass that value back in `If-None-Match` on subsequent requests; Harper returns `304 Not Modified` with an empty body if the record is unchanged.\n\n ```bash\n curl -i 'http://localhost:9926/JokeCache/1' \\\n -H 'If-None-Match: \"abCDefGHij\"'\n ```\n\n5. **Force a cache bypass**: Send `Cache-Control: no-cache` to make Harper skip the local cache and always call the upstream source, regardless of TTL.\n\n ```bash\n curl -i 'http://localhost:9926/JokeCache/1' \\\n -H 'Cache-Control: no-cache'\n ```\n\n6. **Invalidate a cache entry on demand**: Remove `@export` from the schema type, then export a class of the same name in `resources.js` that extends the table and implements a `post` handler calling `this.invalidate(target)`.\n\n ```graphql\n type JokeCache @table(expiration: 60) {\n \tid: ID @primaryKey\n \tsetup: String\n \tpunchline: String\n }\n ```\n\n ```javascript\n export class JokeCache extends tables.JokeCache {\n \tstatic async post(target, data) {\n \t\tconst body = await data;\n \t\tif (body?.action === 'invalidate') {\n \t\t\tthis.invalidate(target);\n \t\t\treturn { status: 200, data: { message: 'invalidated' } };\n \t\t}\n \t}\n }\n ```\n\n Trigger invalidation with a `POST`:\n\n ```bash\n curl -X POST 'http://localhost:9926/JokeCache/1' \\\n -H 'Content-Type: application/json' \\\n -d '{\"action\": \"invalidate\"}'\n ```\n\n The next `GET /JokeCache/1` will fetch fresh data from the upstream source regardless of TTL.\n\n## Examples\n\nComplete `schema.graphql` and `resources.js` for a cached external API with on-demand invalidation:\n\n```graphql\ntype JokeCache @table(expiration: 60) {\n\tid: ID @primaryKey\n\tsetup: String\n\tpunchline: String\n}\n```\n\n```javascript\n// resources.js\n\nconst jokeAPI = {\n\tasync get() {\n\t\tconst id = this.getId();\n\t\tconst response = await fetch(`https://official-joke-api.appspot.com/jokes/${id}`);\n\t\treturn response.json();\n\t},\n};\n\ntables.JokeCache.sourcedFrom(jokeAPI);\n\nexport class JokeCache extends tables.JokeCache {\n\tstatic async post(target, data) {\n\t\tconst body = await data;\n\t\tif (body?.action === 'invalidate') {\n\t\t\tthis.invalidate(target);\n\t\t\treturn { status: 200, data: { message: 'invalidated' } };\n\t\t}\n\t}\n}\n```\n\nFirst request cache miss, upstream is called, `200` returned:\n\n```bash\ncurl -i 'http://localhost:9926/JokeCache/1'\n```\n\nSecond request with ETag — cache hit, `304 Not Modified`:\n\n```bash\ncurl -i 'http://localhost:9926/JokeCache/1' \\\n -H 'If-None-Match: \"abCDefGHij\"'\n```\n\n## Notes\n\n- `expiration` is measured in seconds. Harper also supports separate `eviction` and `scanInterval` arguments on `@table` for fine-grained control over physical record removal.\n- The `@export` directive on the schema type is not required when you export a Resource class of the same name from `resources.js` — the class export serves as the endpoint registration. See [custom-resources.md](custom-resources.md) for details on building Resource classes.\n- Harper's REST layer automatically exposes `@export`-ed tables and Resource classes as HTTP endpoints. See [automatic-apis.md](automatic-apis.md) for how endpoints are structured and named.\n- ETag values include their double quotes as part of the value — include them verbatim when passing the value in `If-None-Match`.\n- `sourcedFrom` must be called after the table reference (`tables.JokeCache`) is available, which is guaranteed when the call is at the top level of `resources.js`.\n",
34
+ "checking-authentication": "---\nname: checking-authentication\ndescription: How to handle user authentication and sessions in Harper Resources.\nmetadata:\n mode: generate\n sources:\n - >-\n reference/v5/resources/resource-api.md#`getCurrentUser(): User |\n undefined`\n - reference/v5/resources/resource-api.md#Session and Login from a Resource\n - reference/v5/security/jwt-authentication.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: fdd9ec3b11011490\n---\n\n# Checking Authentication\n\nInstructions for the agent to follow when handling user authentication and session management inside Harper Resources.\n\n## When to Use\n\nApply this rule when implementing authentication checks, login/logout flows, or token issuance inside a custom Resource. Use it any time a Resource needs to identify the current user, establish a session, or issue JWTs to clients. See [custom-resources.md](custom-resources.md) for the general Resource authoring pattern.\n\n## How It Works\n\n1. **Check the current user** with `getCurrentUser()`. Call it inside any Resource method to retrieve the authenticated user or `undefined` if no user is authenticated. Guard protected endpoints by returning a `401` when the result is `undefined`.\n\n ```javascript\n async get(target) {\n const user = this.getCurrentUser();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n }\n ```\n\n The returned object exposes `username`, `role`, and `role.permission` flags.\n\n2. **Enable sessions** before using session-based login. Set `authentication.enableSessions: true` in `harperdb-config.yaml`:\n\n ```yaml\n authentication:\n enableSessions: true\n ```\n\n3. **Access login and session helpers** via `getContext()`. The context object exposes `context.login` and `context.session` for sign-in/out flows.\n - Call `context.login(username, password)` to verify credentials and establish a session cookie on success.\n - To end a session, delete it via `context.session.delete(context.session.id)`.\n\n4. **Implement sign-in and sign-out Resources** using the context helpers:\n\n ```javascript\n export class SignIn extends Resource {\n \tasync post(_target, data) {\n \t\tconst context = this.getContext();\n \t\ttry {\n \t\t\tawait context.login(data.username, data.password);\n \t\t} catch {\n \t\t\treturn new Response('Invalid credentials', { status: 403 });\n \t\t}\n \t\treturn new Response('Logged in', { status: 200 });\n \t}\n }\n\n export class SignOut extends Resource {\n \tasync post() {\n \t\tconst context = this.getContext();\n \t\tif (!context.session) return new Response(null, { status: 401 });\n \t\tawait context.session.delete(context.session.id);\n \t\treturn new Response('Logged out', { status: 200 });\n \t}\n }\n ```\n\n5. **Issue JWTs for non-browser clients** (CLI tools, mobile apps, service-to-service). Cookie-based sessions are intended for browser clients. For other clients, mint tokens programmatically using `server.operation()`:\n\n ```javascript\n import { Resource, server } from 'harper';\n\n export class IssueTokens extends Resource {\n \tstatic async get(_target, context) {\n \t\tconst { operation_token, refresh_token } = await server.operation(\n \t\t\t{ operation: 'create_authentication_tokens' },\n \t\t\tcontext,\n \t\t\ttrue,\n \t\t);\n \t\treturn { operation_token, refresh_token };\n \t}\n\n \tstatic async post(_target, data) {\n \t\tconst { username, password } = await data;\n \t\tif (!username || !password) {\n \t\t\treturn new Response('username and password required', { status: 400 });\n \t\t}\n \t\tconst { operation_token, refresh_token } = await server.operation({\n \t\t\toperation: 'create_authentication_tokens',\n \t\t\tusername,\n \t\t\tpassword,\n \t\t});\n \t\treturn { operation_token, refresh_token };\n \t}\n }\n\n export class RefreshJWT extends Resource {\n \tstatic async post(_target, data) {\n \t\tconst { refresh_token } = await data;\n \t\tif (!refresh_token) {\n \t\t\treturn new Response('refresh_token required', { status: 400 });\n \t\t}\n \t\tconst { operation_token } = await server.operation({\n \t\t\toperation: 'refresh_operation_token',\n \t\t\trefresh_token,\n \t\t});\n \t\treturn { operation_token };\n \t}\n }\n ```\n\n Pass `true` as the third argument to `server.operation()` when the operation should run as the current authenticated user. Omit it or pass `false` when the operation supplies its own credentials.\n\n6. **Configure JWT token expiry** in `harperdb-config.yaml` under the `authentication` section:\n\n ```yaml\n authentication:\n operationTokenTimeout: 1d\n refreshTokenTimeout: 30d\n ```\n\n Duration strings follow the `jsonwebtoken` package format (e.g., `1d`, `12h`, `60m`).\n\n## Examples\n\n**Protecting a resource endpoint and returning user info:**\n\n```javascript\nasync get(target) {\n const user = this.getCurrentUser();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n}\n```\n\n**Full session-based sign-in/sign-out flow:**\n\n```javascript\nexport class SignIn extends Resource {\n\tasync post(_target, data) {\n\t\tconst context = this.getContext();\n\t\ttry {\n\t\t\tawait context.login(data.username, data.password);\n\t\t} catch {\n\t\t\treturn new Response('Invalid credentials', { status: 403 });\n\t\t}\n\t\treturn new Response('Logged in', { status: 200 });\n\t}\n}\n\nexport class SignOut extends Resource {\n\tasync post() {\n\t\tconst context = this.getContext();\n\t\tif (!context.session) return new Response(null, { status: 401 });\n\t\tawait context.session.delete(context.session.id);\n\t\treturn new Response('Logged out', { status: 200 });\n\t}\n}\n```\n\n**JWT token refresh endpoint:**\n\n```javascript\nexport class RefreshJWT extends Resource {\n\tstatic async post(_target, data) {\n\t\tconst { refresh_token } = await data;\n\t\tif (!refresh_token) {\n\t\t\treturn new Response('refresh_token required', { status: 400 });\n\t\t}\n\t\tconst { operation_token } = await server.operation({\n\t\t\toperation: 'refresh_operation_token',\n\t\t\trefresh_token,\n\t\t});\n\t\treturn { operation_token };\n\t}\n}\n```\n\n## Notes\n\n- `getCurrentUser()` and `getContext()` are instance methods; call them with `this` inside non-static Resource methods.\n- `enableSessions` must be `true` in config before `context.login` or `context.session` will function.\n- Cookie-based sessions target browser clients. Use JWT issuance via `server.operation()` for all other client types.\n- When both `operation_token` and `refresh_token` have expired, the client must call `create_authentication_tokens` again with credentials.\n",
35
35
  "creating-a-fabric-account-and-cluster": "---\nname: creating-a-fabric-account-and-cluster\ndescription: How to create a Harper Fabric account, organization, and cluster.\nmetadata:\n mode: synthesized\n---\n\n# Creating a Harper Fabric Account and Cluster\n\nFollow these steps to set up your Harper Fabric environment for deployment.\n\n## How It Works\n\n1. **Sign Up/In**: Go to [https://fabric.harper.fast/](https://fabric.harper.fast/) and sign up or sign in.\n2. **Create an Organization**: Create an organization (org) to manage your projects.\n3. **Create a Cluster**: Create a new cluster. This can be on the free tier, no credit card required.\n4. **Set Credentials**: During setup, set the cluster username and password to finish configuring it.\n5. **Get Application URL**: Navigate to the **Config** tab and copy the **Application URL**.\n6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with cluster-specific credentials.\n7. **Next Steps**: See the [deploying-to-harper-fabric](deploying-to-harper-fabric.md) rule for detailed instructions on deploying your application successfully.\n\n## Examples\n\n### Environment Configuration\n\n```bash\nCLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'\nCLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'\nCLI_TARGET='YOUR_CLUSTER_URL'\n```\n",
36
36
  "creating-harper-apps": "---\nname: creating-harper-apps\ndescription: How to initialize a new Harper application using the CLI.\nmetadata:\n mode: synthesized\n---\n\n# Creating Harper Applications\n\nThe fastest way to start a new Harper project is using the `create-harper` CLI tool. This command initializes a project with a standard folder structure, essential configuration files, and basic schema definitions.\n\n## When to Use\n\nUse this command when starting a new Harper application or adding a new Harper microservice to an existing architecture.\n\n## Commands\n\nInitialize a project using your preferred package manager:\n\n### NPM\n\n```bash\nnpm create harper@latest\n```\n\n### PNPM\n\n```bash\npnpm create harper@latest\n```\n\n### Bun\n\n```bash\nbun create harper@latest\n```\n\n## Options\n\nYou can specify the project name and template directly:\n\n```bash\nnpm create harper@latest my-app --template default\n```\n\n## Next Steps\n\n1. **Configure Environment**: Set up your `.env` file with local or cloud credentials.\n2. **Define Schema**: Modify `schema.graphql` to fit your application's data model.\n3. **Start Development**: Run `npm run dev` to start the local Harper instance.\n4. **Deploy**: Use `npm run deploy` to push your application to Harper Fabric.\n",
37
37
  "custom-resources": "---\nname: custom-resources\ndescription: How to define custom REST endpoints with JavaScript or TypeScript in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Custom Resources\n\nInstructions for the agent to follow when creating custom resources in Harper.\n\n## When to Use\n\nUse this skill when the automatic CRUD operations provided by `@table @export` are insufficient, and you need custom logic, third-party API integration, or specialized data handling for your REST endpoints.\n\n## How It Works\n\n1. **Check if a Custom Resource is Necessary**: Verify if [Automatic APIs](./automatic-apis.md) or [Extending Tables](./extending-tables.md) can satisfy the requirement first.\n2. **Create the Resource File**: Create a `.ts` or `.js` file in the directory specified by `jsResource` in `config.yaml` (typically `resources/`).\n3. **Define the Resource Class**: Export a class extending `Resource` from `harper`:\n\n ```typescript\n import { type RequestTargetOrId, Resource } from 'harper';\n\n export class MyResource extends Resource {\n \tasync get(target?: RequestTargetOrId) {\n \t\treturn { message: 'Hello from custom GET!' };\n \t}\n }\n ```\n\n4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests.\n5. **Route Nesting and Naming**: You can control the URL structure by how you export your resources:\n - **Direct Class Export**: `export class Foo extends Resource` creates endpoints at `/Foo/`. Class names are case-sensitive in the URL.\n - **Nested Objects**: `export const Bar = { Foo };` creates endpoints at `/Bar/Foo/`.\n - **Lowercase and Hyphens**: Use object keys to define custom paths: `export const bar = { 'foo-baz': Foo };` exposes endpoints at `/bar/foo-baz/`.\n6. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:\n ```typescript\n import { tables } from 'harper';\n // ... inside a method\n const results = await tables.MyTable.list();\n ```\n7. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).\n",
38
38
  "defining-relationships": "---\nname: defining-relationships\ndescription: How to define and use relationships between tables in Harper using GraphQL.\nmetadata:\n mode: synthesized\n---\n\n# Defining Relationships\n\nInstructions for the agent to follow when defining relationships between Harper tables.\n\n## When to Use\n\nUse this skill when you need to link data across different tables, enabling automatic joins and efficient related-data fetching via REST APIs.\n\n## How It Works\n\n1. **Identify the Relationship Type**: Determine if it's one-to-one, many-to-one, or one-to-many.\n2. **Use the `@relationship` Directive**: Apply it to a field in your GraphQL schema.\n - **Many-to-One (Current table holds FK)**: Use `from`.\n ```graphql\n type Book @table @export {\n \tauthorId: ID\n \tauthor: Author @relationship(from: \"authorId\")\n }\n ```\n - **One-to-Many (Related table holds FK)**: Use `to` and an array type.\n ```graphql\n type Author @table @export {\n \tbooks: [Book] @relationship(to: \"authorId\")\n }\n ```\n3. **Query with Relationships**: Use dot syntax in REST API calls for filtering or the `select()` operator for including related data.\n - Example Filter: `GET /Book/?author.name=Harper`\n - Example Select: `GET /Author/?select(name,books(title))`\n",
39
- "deploying-to-harper-fabric": "---\nname: deploying-to-harper-fabric\ndescription: How to deploy a Harper application to the Harper Fabric cloud.\nmetadata:\n mode: synthesized\n---\n\n# Deploying to Harper Fabric\n\nInstructions for the agent to follow when deploying to Harper Fabric.\n\n## When to Use\n\nUse this skill when you are ready to move your Harper application from local development to a cloud-hosted environment.\n\n## How It Works\n\n1. **Sign up**: Follow the [creating-a-fabric-account-and-cluster](creating-a-fabric-account-and-cluster.md) rule to create a Harper Fabric account, organization, and cluster.\n2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:\n ```bash\n CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'\n CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'\n CLI_TARGET='YOUR_CLUSTER_URL'\n ```\n3. **Deploy From Local Environment**: Run `npm run deploy`.\n4. **Set up CI/CD**: Configure `.github/workflows/deploy.yaml` and set repository secrets for automated deployments.\n\n## Manual Setup for Existing Apps\n\nIf your application was not created with `npm create harper`, you'll need to manually configure the deployment scripts and CI/CD workflow.\n\n### 1. Update `package.json`\n\nAdd the following scripts and dependencies to your `package.json`:\n\n```json\n{\n\t\"scripts\": {\n\t\t\"deploy\": \"dotenv -- npm run deploy:component\",\n\t\t\"deploy:component\": \"harper deploy_component . restart=rolling replicated=true\"\n\t},\n\t\"devDependencies\": {\n\t\t\"dotenv-cli\": \"^11.0.0\",\n\t\t\"harper\": \"^5.0.0\"\n\t}\n}\n```\n\n#### Why split the scripts?\n\nThe `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.\n\n- `deploy`: Uses `dotenv-cli` to load environment variables (like `CLI_TARGET`, `CLI_TARGET_USERNAME`, and `CLI_TARGET_PASSWORD`) before executing the next command.\n- `deploy:component`: The actual command that performs the deployment.\n\nBy using `dotenv -- npm run deploy:component`, the environment variables are correctly set in the shell session before `harper deploy_component` is called, allowing it to authenticate with your cluster.\n\n### 2. Configure GitHub Actions\n\nCreate a `.github/workflows/deploy.yaml` file with the following content:\n\n```yaml\nname: Deploy to Harper Fabric\non:\n workflow_dispatch:\n# push:\n# branches:\n# - main\nconcurrency:\n group: main\n cancel-in-progress: false\njobs:\n deploy:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout code\n uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1\n with:\n fetch-depth: 0\n fetch-tags: true\n - name: Set up Node.js\n uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0\n with:\n cache: 'npm'\n node-version-file: '.nvmrc'\n - name: Install dependencies\n run: npm ci\n - name: Run unit tests\n run: npm test\n - name: Run lint\n run: npm run lint\n - name: Deploy\n run: npm run deploy\n env:\n CLI_TARGET: ${{ secrets.CLI_TARGET }}\n CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}\n CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}\n```\n\nBe sure to set the following repository secrets in your GitHub repository's /settings/secrets/actions:\n\n- `CLI_TARGET`\n- `CLI_TARGET_USERNAME`\n- `CLI_TARGET_PASSWORD`\n",
39
+ "deploying-to-harper-fabric": "---\nname: deploying-to-harper-fabric\ndescription: How to deploy a Harper application to the Harper Fabric cloud.\nmetadata:\n mode: generate\n sources:\n - reference/v5/components/applications.md#Remote Management\n - >-\n fabric/cluster-creation-management.md#Connecting the Harper CLI to a\n Cluster\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: ccdefbbf8f3b8657\n---\n\n# Deploying to Harper Fabric\n\nInstructions for the agent to follow when deploying a Harper application to the Harper Fabric cloud using the Harper CLI.\n\n## When to Use\n\nApply this rule when deploying a Harper application to a remote Harper instance or Harper Fabric cluster. This covers interactive deployments, CI/CD pipelines, and any scenario where the agent must push a local or remote package to a target environment.\n\n## How It Works\n\n1. **Authenticate with the remote target**: Run `harper login` once to store an authentication token. The CLI writes `HARPER_CLI_TARGET` to a local `.env` so subsequent commands do not need credentials repeated. Find the **Application URL** on the cluster's **Config → Overview** page (see [creating-a-fabric-account-and-cluster.md](creating-a-fabric-account-and-cluster.md)).\n\n ```bash\n harper login <Application URL>\n # Provide cluster username and password when prompted\n ```\n\n2. **Deploy the application**: Run `harper deploy` with the required parameters. After logging in, no credentials are needed inline.\n\n ```bash\n harper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n ```\n\n3. **Choose a package source**: Set the `package` parameter to any valid npm dependency value, or omit it to package and deploy the current local directory.\n\n | Value | Effect |\n | ---------------------------------------------------- | ------------------------------------------------ |\n | _(omitted)_ | Packages and deploys the current local directory |\n | `\"@harperdb/status-check\"` | npm package |\n | `\"HarperDB/status-check\"` | GitHub repo (short form) |\n | `\"https://github.com/HarperDB/status-check\"` | GitHub repo (full URL) |\n | `\"git+ssh://git@github.com:HarperDB/secret-app.git\"` | Private repo via SSH |\n | `\"https://example.com/application.tar.gz\"` | Remote tarball |\n\n For git tags, use the `semver` directive for reliable versioning:\n\n ```\n HarperDB/application-template#semver:v1.0.0\n ```\n\n4. **Authenticate for CI/CD pipelines**: Use environment variables instead of interactive login. Set credentials before running `harper deploy`.\n\n ```bash\n export HARPER_CLI_USERNAME=<username>\n export HARPER_CLI_PASSWORD=<password>\n harper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n ```\n\n5. **Register SSH keys for private repos**: Before deploying from an SSH-based private repository, use the Add SSH Key operation to register the key with the remote instance.\n\n## Examples\n\n**Interactive login then deploy (recommended):**\n\n```bash\n# Log in once\nharper login <remote>\n# Provide your username and password when prompted\n\n# Subsequently deploy without credentials\nharper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n**Deploy with inline credentials (not recommended for production):**\n\n```bash\nharper deploy \\\n project=<name> \\\n package=<package> \\\n username=<username> \\\n password=<password> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n**Deploy a specific GitHub release by semver tag:**\n\n```bash\nharper deploy \\\n project=my-app \\\n package=\"HarperDB/application-template#semver:v1.0.0\" \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n## Notes\n\n- Always prefer `harper login` for interactive use and environment variables (`HARPER_CLI_USERNAME`, `HARPER_CLI_PASSWORD`) for CI/CD. Avoid inline `username`/`password` parameters in production.\n- Omitting `package` causes the CLI to package the current local directory. Specifying a local file path creates a symlink, so changes are picked up between restarts without redeploying.\n- Harper generates a `package.json` from component configurations and resolves dependencies using a form of `npm install`.\n- For SSH-based private repos, register keys with the Add SSH Key operation before deploying.\n",
40
40
  "extending-tables": "---\nname: extending-tables\ndescription: How to add custom logic to automatically generated table resources in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Extending Tables\n\nInstructions for the agent to follow when extending table resources in Harper.\n\n## When to Use\n\nUse this skill when you need to add custom validation, side effects (like webhooks), data transformation, or custom access control to the standard CRUD operations of a Harper table.\n\n## How It Works\n\n1. **Define the Table in GraphQL**: In your `.graphql` schema, define the table using the `@table` directive. **Do not** use `@export` if you plan to extend it.\n ```graphql\n type MyTable @table {\n \tid: ID @primaryKey\n \tname: String\n }\n ```\n2. **Create the Extension File**: Create a `.ts` file in your `resources/` directory.\n3. **Extend the Table Resource**: Export a class that extends `tables.YourTableName`:\n\n ```typescript\n import { type RequestTargetOrId, tables } from 'harper';\n\n export class MyTable extends tables.MyTable {\n \tasync post(target: RequestTargetOrId, record: any) {\n \t\t// Custom logic here\n \t\tif (!record.name) {\n \t\t\tthrow new Error('Name required');\n \t\t}\n \t\treturn super.post(target, record);\n \t}\n }\n ```\n\n4. **Override Methods**: Override `get`, `post`, `put`, `patch`, or `delete` as needed. Always call `super[method]` to maintain default Harper functionality unless you intend to replace it entirely.\n5. **Implement Logic**: Use overrides for validation, side effects, or transforming data before/after database operations.\n",
41
41
  "handling-binary-data": "---\nname: handling-binary-data\ndescription: How to store and serve binary data like images or audio in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Handling Binary Data\n\nInstructions for the agent to follow when handling binary data in Harper.\n\n## When to Use\n\nUse this skill when you need to store binary files (images, audio, etc.) in the database or serve them back to clients via REST endpoints.\n\n## How It Works\n\n1. **Store Binary Data**: In your resource's `post` or `put` method, convert incoming data to Buffers and then to Blobs using `createBlob` from Harper's globals. Include the MIME type if available:\n\n ```typescript\n async post(target, record) {\n if (record.data) {\n record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {\n type: record.contentType || 'application/octet-stream',\n });\n }\n return super.post(target, record);\n }\n ```\n\n2. **Serve Binary Data**: In your resource's `get` method, return a response object with the appropriate `Content-Type` and the binary data in the `body`:\n ```typescript\n async get(target) {\n const record = await super.get(target);\n if (record?.data) {\n return {\n status: 200,\n headers: { 'Content-Type': record.data.type || 'application/octet-stream' },\n body: record.data,\n };\n }\n return record;\n }\n ```\n3. **Use the Blob Type**: Ensure your GraphQL schema uses the `Blob` scalar for binary fields.\n",
42
- "logging": "---\nname: logging\ndescription: Best practices for logging in Harper, including console capture, the granular logger interface, and programmatic log retrieval.\nmetadata:\n mode: synthesized\n---\n\n# Logging Best Practices\n\nHarper provides a robust logging system that captures standard output and offers a granular, tagged logging interface for both local and deployed environments.\n\n## Standard Console Logging\n\nThe simplest way to log in Harper is using standard JavaScript console methods. `console.log()`, `console.warn()`, `console.error()`, and `console.trace()` are automatically captured by Harper and can be viewed in the logs.\n\n- `console.log(...)`: Captured as `stdout` level in Harper logs.\n- `console.warn(...)`: Captured as `stderr` level in Harper logs.\n- `console.error(...)`: Captured as `stderr` level in Harper logs.\n- `console.trace(...)`: Captured as `stdout` level in Harper logs (includes stack trace).\n\n## Harper Logger\n\nFor more granularity and better organization, use Harper's built-in `logger`. You can use the global `logger` object or import it from the `harper` package.\n\n### Log Levels\n\nThe Harper `logger` supports the following levels (ordered by increasing severity):\n\n- `trace`\n- `debug`\n- `info`\n- `warn`\n- `error`\n- `fatal`\n- `notify`\n\n### Usage\n\n```typescript\nimport { logger, loggerWithTag } from 'harper';\n\n// Basic logging\nlogger.info('Application started');\nlogger.error('An error occurred', error);\n\n// Tagged logging for better filtering (Namespacing)\nconst authLogger = loggerWithTag('auth');\nauthLogger.debug('User login attempt', { userId: '123' });\n```\n\nUsing `loggerWithTag` is highly recommended for grouping related logs, making them much easier to filter and analyze in the Harper Studio or via the API.\n\n## Programmatic Log Retrieval\n\nYou can programmatically read logs from a deployed Harper instance using the `read_log` operation. This is useful for building custom monitoring tools or debugging dashboards.\n\n### `read_log` Operation\n\nThe `read_log` operation is a POST request to the Harper instance.\n\n**Example Request:**\n\n```json\n{\n\t\"operation\": \"read_log\",\n\t\"limit\": 100,\n\t\"start\": 0,\n\t\"level\": \"error\",\n\t\"order\": \"desc\",\n\t\"from\": \"2024-01-01T00:00:00.000Z\",\n\t\"until\": \"2024-01-02T00:00:00.000Z\"\n}\n```\n\n### Parameters\n\n- `limit`: Number of log entries to return.\n- `start`: Offset for pagination.\n- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).\n- `from`: ISO 8601 timestamp to start reading from.\n- `until`: ISO 8601 timestamp to stop reading at.\n- `order`: Sort order, either `asc` or `desc`.\n- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.\n\n### Log Entry Structure\n\nEach log entry returned by `read_log` typically includes:\n\n- `level`: The severity level of the log.\n- `timestamp`: When the log was recorded.\n- `thread`: The execution thread.\n- `tags`: An array of tags (e.g., from `loggerWithTag`).\n- `node`: The node name in a Harper cluster.\n- `message`: The logged content.\n",
42
+ "logging": "---\nname: logging\ndescription: >-\n Best practices for logging in Harper, including console capture, the granular\n logger interface, and programmatic log retrieval.\nmetadata:\n mode: generate\n sources:\n - reference/v5/logging/overview.md\n - reference/v5/logging/api.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 46cd384598304e3b\n---\n\n# Harper Logging\n\nInstructions for the agent to follow when implementing logging in Harper applications, including direct logger usage, tagged loggers, and console capture behavior.\n\n## When to Use\n\nApply this rule when writing any JavaScript component, plugin, or resource that needs to emit structured log entries, filter logs by component, or capture existing `console.log` output into Harper's log system. Use it whenever you need to understand log levels, log entry format, or the `logger` global API.\n\n## How It Works\n\n1. **Use the `logger` global directly** — `logger` is available in all JavaScript components without any imports. Call the method matching the desired severity level:\n\n ```javascript\n logger.trace('detailed trace message');\n logger.debug('debug info', { someContext: 'value' });\n logger.info('informational message');\n logger.warn('potential issue');\n logger.error('error occurred', error);\n logger.fatal('fatal error');\n logger.notify('server is ready');\n ```\n\n Only entries at or above the configured `logging.level` (or `logging.external.level`) are written to `hdb.log`.\n\n2. **Create a tagged logger with `withTag(`** — Call `logger.withTag(tag)` once per module or class to get a `TaggedLogger` scoped to that tag. This prefixes every log entry with the tag, making log output filterable by component.\n\n ```javascript\n const log = logger.withTag('my-resource');\n ```\n\n Because `TaggedLogger` methods for disabled levels are `null`, always use optional chaining (`?.`) when calling them:\n\n ```javascript\n log.debug?.('Fetching record', { id });\n log.warn?.('Record not found', { id });\n log.error?.('Failed to update record', err);\n ```\n\n `TaggedLogger` does not have a `withTag()` method.\n\n3. **Understand the interface contracts** `MainLogger` always has all methods defined:\n\n ```typescript\n interface MainLogger {\n \ttrace(...messages: any[]): void;\n \tdebug(...messages: any[]): void;\n \tinfo(...messages: any[]): void;\n \twarn(...messages: any[]): void;\n \terror(...messages: any[]): void;\n \tfatal(...messages: any[]): void;\n \tnotify(...messages: any[]): void;\n \twithTag(tag: string): TaggedLogger;\n }\n ```\n\n `TaggedLogger` methods may be `null`:\n\n ```typescript\n interface TaggedLogger {\n \ttrace: ((...messages: any[]) => void) | null;\n \tdebug: ((...messages: any[]) => void) | null;\n \tinfo: ((...messages: any[]) => void) | null;\n \twarn: ((...messages: any[]) => void) | null;\n \terror: ((...messages: any[]) => void) | null;\n \tfatal: ((...messages: any[]) => void) | null;\n \tnotify: ((...messages: any[]) => void) | null;\n }\n ```\n\n4. **Know the log levels** From least to most severe:\n\n | Level | Description |\n | -------- | -------------------------------------------------------------------- |\n | `trace` | Highly detailed internal execution tracing. |\n | `debug` | Diagnostic information useful during development. |\n | `info` | General operational events. |\n | `warn` | Potential issues that don't prevent normal operation. |\n | `error` | Errors that affect specific operations. |\n | `fatal` | Critical errors causing process termination. |\n | `notify` | Important operational milestones. Always logged regardless of level. |\n\n The default log level is `warn`. Setting a level includes that level and all more-severe levels.\n\n5. **Enable console capture when porting existing code** — When `logging.console: true` is set, writes via `console.log`, `console.warn`, `console.error`, etc. are appended verbatim to `hdb.log`. Captured lines do **not** pass through `logger`'s level filter. Prefer `logger` directly in production code so that level filtering and tagging apply. Console capture is intended as a convenience for porting existing code and for debugging.\n\n6. **Know where logs are written** — All standard log output goes to `<ROOTPATH>/log/hdb.log` (default: `~/hdb/log/hdb.log`). To also log to `stdout`/`stderr`, set `logging.stdStreams: true`.\n\n## Examples\n\n### Basic logging in a resource\n\n```javascript\nexport class MyResource extends Resource {\n\tasync get(id) {\n\t\tlogger.debug('Fetching record', { id });\n\t\tconst record = await super.get(id);\n\t\tif (!record) {\n\t\t\tlogger.warn('Record not found', { id });\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync put(record) {\n\t\tlogger.info('Updating record', { id: record.id });\n\t\ttry {\n\t\t\treturn await super.put(record);\n\t\t} catch (err) {\n\t\t\tlogger.error('Failed to update record', err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n```\n\n### Tagged logging with `withTag()`\n\n```javascript\nconst log = logger.withTag('my-resource');\n\nexport class MyResource extends Resource {\n\tasync get(id) {\n\t\tlog.debug?.('Fetching record', { id });\n\t\tconst record = await super.get(id);\n\t\tif (!record) {\n\t\t\tlog.warn?.('Record not found', { id });\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync put(record) {\n\t\tlog.info?.('Updating record', { id: record.id });\n\t\ttry {\n\t\t\treturn await super.put(record);\n\t\t} catch (err) {\n\t\t\tlog.error?.('Failed to update record', err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n```\n\nTagged entries appear in `hdb.log` with the tag in the header:\n\n```\n2023-03-09T14:25:05.269Z [info] [my-resource]: Updating record\n```\n\n## Notes\n\n- All log output is written to `<ROOTPATH>/log/hdb.log`. The `logger` global writes to this file at the configured `logging.external` level.\n- Log entry format for `logger`: `<timestamp> [<level>] [<thread>/<id>]: <message>`\n- Log entry format for `TaggedLogger`: `<timestamp> [<level>] [<tag>]: <message>`\n- `console.log` output is only forwarded to `hdb.log` when `logging.console: true` is explicitly set; it is not forwarded by default.\n- When logging to standard streams, run Harper in the foreground (`harper`, not `harper start`).\n- `TaggedLogger` is bound to the configured log level at creation time — always use `?.` on its methods.\n",
43
43
  "programmatic-table-requests": "---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\nmetadata:\n mode: synthesized\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to follow when interacting with Harper tables via code.\n\n## When to Use\n\nUse this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.\n\n## How It Works\n\n1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).\n2. **Perform CRUD Operations**:\n - **Get**: `await tables.MyTable.get(id)` for a single record or `await tables.MyTable.get({ conditions: [...] })` for multiple.\n - **Create**: `await tables.MyTable.post(record)` (auto-generates ID) or `await tables.MyTable.put(id, record)`.\n - **Update**: `await tables.MyTable.patch(id, partialRecord)` for partial updates.\n - **Delete**: `await tables.MyTable.delete(id)`.\n3. **Use Updatable Records for Atomic Ops**: Call `update(id)` to get a reference, then use `addTo` or `subtractFrom` for atomic increments/decrements:\n ```typescript\n const stats = await tables.Stats.update('daily');\n stats.addTo('viewCount', 1);\n ```\n4. **Search and Stream**: Use `search(query)` for efficient streaming of large result sets:\n ```typescript\n for await (const record of tables.MyTable.search({ conditions: [...] })) {\n // process record\n }\n ```\n See the [Query Conditions](#query-conditions) section below for the full query object reference.\n5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:\n ```typescript\n for await (const event of tables.MyTable.subscribe(query)) {\n \t// handle event\n }\n ```\n6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.\n\n## Query Conditions\n\nWhen passing a query to `search()`, `get()`, or `subscribe()`, use a query object with a `conditions` array.\n\n### Condition Object Shape\n\n| Property | Description |\n| ------------ | ------------------------------------------------------------------------------------------ |\n| `attribute` | Field name, or array of field names to traverse a relationship (e.g., `['brand', 'name']`) |\n| `value` | The value to compare against |\n| `comparator` | One of the comparator strings below (default: `equals`) |\n| `operator` | `and` (default) or `or` — applies to a nested `conditions` block |\n| `conditions` | Nested array of condition objects for complex AND/OR logic |\n\n### Comparator Values\n\nUse these exact strings — incorrect comparator names will silently fail or error:\n\n| Comparator | Meaning |\n| -------------------- | ---------------------------------------------------------- |\n| `equals` | Exact match (default) |\n| `not_equal` | Not equal |\n| `greater_than` | `>` |\n| `greater_than_equal` | `>=` |\n| `less_than` | `<` |\n| `less_than_equal` | `<=` |\n| `starts_with` | String starts with value |\n| `contains` | String contains value |\n| `ends_with` | String ends with value |\n| `between` | Value is between two bounds (pass `value` as `[min, max]`) |\n\n### Query Object Parameters\n\n| Property | Description |\n| ------------ | ------------------------------------------------------------------------------------ |\n| `conditions` | Array of condition objects |\n| `limit` | Maximum number of records to return |\n| `offset` | Number of records to skip (for pagination) |\n| `select` | Array of attribute names to return; supports `$id` and `$updatedtime` |\n| `sort` | Object with `attribute`, `descending` (bool), and optional `next` for secondary sort |\n\n### Examples\n\n**Simple filter:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 100 }],\n limit: 20,\n})) { ... }\n```\n\n**AND + nested OR:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [\n { attribute: 'price', comparator: 'less_than', value: 100 },\n {\n operator: 'or',\n conditions: [\n { attribute: 'rating', comparator: 'greater_than', value: 4 },\n { attribute: 'featured', value: true },\n ],\n },\n ],\n})) { ... }\n```\n\n**Relationship traversal:**\n\n```javascript\nfor await (const record of tables.Book.search({\n conditions: [{ attribute: ['brand', 'name'], comparator: 'equals', value: 'Harper' }],\n})) { ... }\n```\n\n**Sort and paginate:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [{ attribute: 'inStock', value: true }],\n sort: { attribute: 'price', descending: false },\n limit: 10,\n offset: 20,\n})) { ... }\n```\n\n## Cautions\n\nBe very careful when performing updates and deletions! You may be dealing with live production data. The wrong request to delete, without approval from a human, could be devastating to a business. Always use the proper approval process.\n",
44
- "querying-rest-apis": "---\nname: querying-rest-apis\ndescription: How to use query parameters to filter, sort, and paginate Harper REST APIs.\nmetadata:\n mode: synthesized\n---\n\n# Querying REST APIs\n\nInstructions for the agent to follow when querying Harper's REST APIs.\n\n## When to Use\n\nUse this skill when you need to perform advanced data retrieval (filtering, sorting, pagination, joins) using Harper's automatic REST endpoints.\n\n## How It Works\n\n1. **Basic Filtering**: Use attribute names as query parameters: `GET /Table/?key=value`.\n2. **Use Comparison Operators**: Append operators like `gt`, `ge`, `lt`, `le`, `ne` using FIQL-style syntax: `GET /Table/?price=gt=100`.\n3. **Apply Logic and Grouping**: Use `&` for AND, `|` for OR, and `()` for grouping: `GET /Table/?(rating=5|featured=true)&price=lt=50`.\n4. **Select Specific Fields**: Use `select()` to limit returned attributes: `GET /Table/?select(name,price)`.\n5. **Paginate Results**: Use `limit(count)` or `limit(offset, count)` to set the number of records to return and skip.\n - Example (first 10): `GET /Table/?limit(10)`\n - Example (skip 20, return 10): `GET /Table/?limit(20, 10)`\n6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc) before the field name. Avoid `sort=field` format.\n - Example (asc): `GET /Table/?sort(+name)`\n - Example (desc): `GET /Table/?sort(-price)`\n - Example (combined): `GET /Table/?sort(-price,+name)`\n7. **Query Relationships**: Use dot syntax for tables linked with `@relationship`: `GET /Book/?author.name=Harper`.\n",
45
- "real-time-apps": "---\nname: real-time-apps\ndescription: How to build real-time features in Harper using WebSockets and Pub/Sub.\nmetadata:\n mode: synthesized\n---\n\n# Real-time Applications\n\nInstructions for the agent to follow when building real-time applications in Harper.\n\n## When to Use\n\nUse this skill when you need to stream live updates to clients, implement chat features, or provide real-time data synchronization between the database and a frontend.\n\n## How It Works\n\n1. **Check Automatic WebSockets**: If you only need to stream table changes, use [Automatic APIs](automatic-apis.md) which provide a WebSocket endpoint for every `@export`ed table.\n2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method.\n3. **Use Pub/Sub**: Use `tables.TableName.subscribe(query)` to listen for specific data changes and stream them to the client.\n4. **Handle SSE**: Ensure your `connect` method gracefully handles cases where `incomingMessages` is null (Server-Sent Events).\n5. **Connect from Client**: Use standard WebSockets (`new WebSocket('wss://...')`) to connect to your resource endpoint. Ensure you use the appropriate scheme (`ws://` for HTTP, `wss://` for HTTPS).\n\n## Examples\n\n### Bi-directional WebSocket Resource\n\n```typescript\nimport { Resource, tables } from 'harper';\n\nexport class MySocket extends Resource {\n\tasync *connect(target, incomingMessages) {\n\t\t// Subscribe to table changes\n\t\tconst subscription = await tables.MyTable.subscribe(target);\n\t\tif (!incomingMessages) {\n\t\t\treturn subscription; // SSE mode\n\t\t}\n\n\t\t// Handle incoming client messages\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield { received: message };\n\t\t}\n\t}\n}\n```\n",
44
+ "querying-rest-apis": "---\nname: querying-rest-apis\ndescription: 'How to use query parameters to filter, sort, and paginate Harper REST APIs.'\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/querying.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 9f8c981a629ef606\n---\n\n# Querying REST APIs\n\nInstructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.\n\n## When to Use\n\nApply this rule when building or modifying code that queries Harper REST endpoints with filtering, sorting, field selection, or pagination. Use it whenever constructing URLs against collection paths exposed by Harper's automatic REST interface (see [automatic-apis.md](automatic-apis.md)).\n\n## How It Works\n\n1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.\n\n ```\n GET /Product/?category=software\n GET /Product/?category=software&inStock=true\n ```\n\n2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators directly in query parameter values.\n\n | Operator | Meaning |\n | ------------ | -------------------------------------- |\n | `==` | Equal |\n | `=lt=` | Less than |\n | `=le=` | Less than or equal |\n | `=gt=` | Greater than |\n | `=ge=` | Greater than or equal |\n | `=ne=`, `!=` | Not equal |\n | `=ct=` | Contains (strings) |\n | `=sw=` | Starts with (strings) |\n | `=ew=` | Ends with (strings) |\n | `=`, `===` | Strict equality (no type conversion) |\n | `!==` | Strict inequality (no type conversion) |\n\n ```\n GET /Product/?price=gt=100\n GET /Product/?price=le=20\n GET /Product/?name==Keyboard*\n GET /Product/?category=software&price=gt=100&price=lt=200\n ```\n\n For date fields, URL-encode colons as `%3A`:\n\n ```\n GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z\n ```\n\n3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.\n\n ```\n GET /Product/?price=gt=100&lt=200\n ```\n\n4. **Combine conditions with OR logic**: Use `|` instead of `&`.\n\n ```\n GET /Product/?rating=5|featured=true\n ```\n\n5. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.\n\n ```\n GET /Product/?rating=5|(price=gt=100&price=lt=200)\n GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]\n ```\n\n Construct grouped queries from JavaScript:\n\n ```javascript\n let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join('|')}]`;\n ```\n\n6. **Select specific properties with `select(`**: Use `select()` to control which fields are returned.\n\n | Syntax | Returns |\n | -------------------------------------- | ------------------------------------------- |\n | `?select(property)` | Values of a single property directly |\n | `?select(property1,property2)` | Objects with only the specified properties |\n | `?select([property1,property2])` | Arrays of property values |\n | `?select(property1,)` | Objects with a single specified property |\n | `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |\n\n ```\n GET /Product/?category=software&select(name)\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n7. **Limit results with `limit(`**: Use `limit(end)` or `limit(start,end)` to paginate.\n\n ```\n GET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)\n GET /Product/?rating=gt=3&limit(10,30)\n ```\n\n8. **Sort results with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.\n\n ```\n GET /Product/?rating=gt=3&sort(+name)\n GET /Product/?sort(+rating,-price)\n ```\n\n9. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relation`.\n\n ```\n GET /Product/?brand.name=Microsoft\n GET /Brand/?products.name=Keyboard\n ```\n\n Use `select()` to include relationship attributes in the response (they are not included by default):\n\n ```\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n10. **Access a specific property by URL**: Append the property name with dot syntax to the record ID. Only works for properties declared in the schema.\n ```\n GET /MyTable/123.propertyName\n ```\n\n## Examples\n\n**Range filter with select and limit:**\n\n```\nGET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)&limit(20)\n```\n\n**Sort descending with multiple fields:**\n\n```\nGET /Product/?sort(+rating,-price)\n```\n\n**OR logic with grouping:**\n\n```\nGET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]\n```\n\n**Relationship join with nested select:**\n\n```\nGET /Product/?brand.name=Microsoft&select(name,brand{name,id})\n```\n\n**Schema defining a relationship for join queries:**\n\n```graphql\ntype Product @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tbrandId: Long @indexed\n\tbrand: Brand @relation(from: \"brandId\")\n}\ntype Brand @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tproducts: [Product] @relation(to: \"brandId\")\n}\n```\n\n**Many-to-many relationship query:**\n\n```graphql\ntype Product @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tresellerIds: [Long] @indexed\n\tresellers: [Reseller] @relation(from: \"resellerId\")\n}\n```\n\n```\nGET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})\n```\n\n**Type conversion with explicit prefix:**\n\n```\nGET /Product/?price==number:123\nGET /Product/?active==boolean:true\nGET /Product/?listDate==date:2024-01-05T20%3A07%3A27.955Z\n```\n\n## Notes\n\n- Only indexed attributes can be used as the primary filter; additional unindexed attributes can be combined with `&` once at least one indexed attribute is present.\n- For null value queries, use `?attribute=null`. Indexes must have been created with null indexing support; existing indexes must be removed and re-added to support null queries.\n- FIQL comparators (`==`, `!=`, `=gt=`, etc.) apply automatic type conversion based on value syntax or schema-declared type. Strict operators (`=`, `===`, `!==`) skip automatic type conversion.\n- Filtering by a related attribute produces INNER JOIN behavior (only records with a matching related record are returned). Using `select()` on a relationship without a filter produces LEFT JOIN behavior.\n- The array order of foreign key values in many-to-many relationships is preserved when resolving the relationship.\n- See [automatic-apis.md](automatic-apis.md) for how Harper tables are automatically exposed as REST endpoints.\n",
45
+ "real-time-apps": "---\nname: real-time-apps\ndescription: How to build real-time features in Harper using WebSockets and Pub/Sub.\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/websockets.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: a8afd4d3a52f77ba\n---\n\n# Real-Time Apps with WebSockets and Pub/Sub\n\nInstructions for the agent to follow when building real-time features in Harper using WebSockets and Pub/Sub.\n\n## When to Use\n\nApply this rule when implementing any feature that requires real-time bidirectional communication, live data streaming, or push-based updates in a Harper application. This includes chat, live dashboards, sensor feeds, and any scenario where clients must receive resource changes as they happen.\n\n## How It Works\n\n1. **Enable WebSocket support**: WebSocket support is enabled automatically when the `rest` plugin is enabled. To explicitly disable it, set the following in your config:\n\n ```yaml\n rest:\n webSocket: false\n ```\n\n2. **Connect a client to a resource**: A WebSocket connection to a resource URL automatically subscribes to that resource. When the record changes or a message is published to it, the connection receives the update.\n\n ```javascript\n let ws = new WebSocket('wss://server/my-resource/341');\n ws.onmessage = (event) => {\n \tlet data = JSON.parse(event.data);\n };\n ```\n\n `new WebSocket('wss://server/my-resource/341')` accesses the resource defined for `my-resource` with record id `341` and subscribes to it.\n\n3. **Implement a custom `connect()` handler**: Override the `connect(incomingMessages)` method on a resource class to control WebSocket behavior. The method must return an async iterable (or generator) that produces messages to send to the client. See [automatic-apis.md](automatic-apis.md) for more on defining resource classes.\n\n4. **Use the default `connect()` for event-style access**: Call `super.connect()` to get a streaming iterable that provides:\n - A `send(message)` method for pushing outgoing messages\n - A `close` event for cleanup on disconnect\n\n5. **Handle message ordering in distributed environments**: Harper delivers messages to local subscribers immediately without inter-node coordination delay.\n\n | Message Type | Behavior |\n | -------------------------------------------------------- | ----------------------------------------------------------------------- |\n | Non-retained (no `retain` flag) | Every message delivered in order received; suitable for chat |\n | Retained (published with `retain`, or PUT/updated in DB) | Only the latest-timestamp message is kept; suitable for sensor readings |\n\n6. **Use MQTT over WebSockets** when needed by setting the sub-protocol header:\n ```\n Sec-WebSocket-Protocol: mqtt\n ```\n\n## Examples\n\n**Simple echo server** override `connect(incomingMessages)` to yield each incoming message back to the client:\n\n```javascript\nexport class Echo extends Resource {\n\tasync *connect(incomingMessages) {\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield message; // echo each message back\n\t\t}\n\t}\n}\n```\n\n**Custom connect with timer and event-style access** — use `super.connect()` to get the outgoing stream, push periodic messages, echo incoming messages, and clean up on disconnect:\n\n```javascript\nexport class Example extends Resource {\n\tconnect(incomingMessages) {\n\t\tlet outgoingMessages = super.connect();\n\n\t\tlet timer = setInterval(() => {\n\t\t\toutgoingMessages.send({ greeting: 'hi again!' });\n\t\t}, 1000);\n\n\t\tincomingMessages.on('data', (message) => {\n\t\t\toutgoingMessages.send(message); // echo incoming messages\n\t\t});\n\n\t\toutgoingMessages.on('close', () => {\n\t\t\tclearInterval(timer);\n\t\t});\n\n\t\treturn outgoingMessages;\n\t}\n}\n```\n\n## Notes\n\n- WebSocket connections target a resource URL path. By default, connecting to a resource subscribes to changes for that resource.\n- The `connect(incomingMessages)` method **must** return an async iterable or generator; returning a plain value will not work.\n- `super.connect()` returns a streaming iterable with `send(message)` and a `close` event — use this when you need to push messages outside of the incoming message loop.\n- For one-way real-time streaming without bidirectional communication, consider Server-Sent Events instead.\n- For full pub/sub capabilities, Harper also supports MQTT; set `Sec-WebSocket-Protocol: mqtt` to use MQTT over WebSockets.\n",
46
46
  "schema-design-tooling": "---\nname: schema-design-tooling\ndescription: Best practices for Harper schema design, including core directives and GraphQL tooling configuration.\nmetadata:\n mode: synthesized\n---\n\n# Schema Design & Tooling\n\nHarper uses GraphQL schemas to define database tables, relationships, and APIs. To ensure the best development experience for both humans and AI agents, it's important to understand the core directives and configure your project tooling correctly.\n\n## Core Harper Directives\n\nHarper extends GraphQL with custom directives that define database behavior. These are typically defined in `node_modules/harper/schema.graphql`. If you don't have access to that file, here is a reference of the most important ones:\n\n### Table Definition\n\n- `@table`: Marks a GraphQL type as a Harper database table.\n- `@export`: Automatically generates REST and WebSocket APIs for the table.\n- `@table(expiration: Int)`: Configures a time-to-expire for records in the table (useful for caching).\n\n### Attribute Constraints & Indexing\n\n- `@primaryKey`: Specifies the unique identifier for the table.\n- `@indexed`: Creates a standard index on the field for faster lookups.\n- `@indexed(type: \"HNSW\", distance: \"cosine\" | \"euclidean\" | \"dot\")`: Creates a vector index for similarity search.\n\n### Relationships\n\n- `@relationship(from: String)`: Defines a relationship to another table. `from` specifies the local field holding the foreign key.\n\n### Authentication & Authorization\n\n- `@auth(role: String)`: Restricts access to a table or field based on user roles.\n\n## Configuring GraphQL Tooling\n\nTo get the best IDE support (autocompletion, validation) and to help AI agents understand your schema context, you should create a `graphql.config.yml` file in your project root.\n\nThis file tells GraphQL tools where to find Harper's built-in types and directives alongside your own schema files.\n\n### Creating `graphql.config.yml`\n\nCreate a file named `graphql.config.yml` in your project root with the following content:\n\n```yaml\nschema:\n - 'node_modules/harper/schema.graphql'\n - 'schema.graphql'\n - 'schemas/*.graphql'\n```\n\n### Why this is important:\n\n1. **Shared Directives**: It includes `@table`, `@primaryKey`, etc., so they aren't marked as \"unknown directives\".\n2. **Context for Agents**: When an agent reads your project, seeing this config helps it locate the core Harper definitions, leading to more accurate code generation.\n3. **Consistency**: The `npm create harper@latest` command includes this by default. Manually adding it to existing projects ensures they follow the same standards.\n\n## Example Project Structure\n\nA typical Harper project with proper schema tooling:\n\n```text\nmy-harper-app/\n├── config.yaml\n├── graphql.config.yml\n├── package.json\n├── schema.graphql\n└── resources.js\n```\n",
47
47
  "serving-web-content": "---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Serving Web Content\n\nInstructions for the agent to follow when serving web content from Harper.\n\n## When to Use\n\nUse this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.\n\n## How It Works\n\n1. **Choose a Method**: Decide between the simple Static Plugin or the integrated Vite Plugin.\n2. **Option A: Static Plugin (Simple)**:\n - Add to `config.yaml`:\n ```yaml\n static:\n files: 'web/*'\n ```\n - Place files in a `web/` folder in the project root.\n - Files are served at the root URL (e.g., `http://localhost:9926/index.html`).\n3. **Option B: Vite Plugin (Advanced/Development)**:\n - Add to `config.yaml`:\n ```yaml\n '@harperfast/vite-plugin':\n package: '@harperfast/vite-plugin'\n ```\n - Ensure `vite.config.ts` and `index.html` are in the project root.\n\n ```javascript\n import vue from '@vitejs/plugin-vue';\n import path from 'node:path';\n import { defineConfig } from 'vite';\n\n // https://vite.dev/config/\n export default defineConfig({\n \tplugins: [vue()],\n \tresolve: {\n \t\talias: {\n \t\t\t'@': path.resolve(import.meta.dirname, './src'),\n \t\t},\n \t},\n \tbuild: {\n \t\toutDir: 'web',\n \t\temptyOutDir: true,\n \t\trolldownOptions: {\n \t\t\texternal: ['**/*.test.*', '**/*.spec.*'],\n \t\t},\n \t},\n });\n ```\n\n - Install dependencies: `npm install --save-dev vite @harperfast/vite-plugin`.\n - Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.\n\n4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:\n ```json\n \"build\": \"vite build\",\n \"deploy\": \"rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ && (cd deploy && harper deploy_component . project=web restart=rolling replicated=true) && rm -Rf deploy\",\n ```\n Then in production, the \"Static Plugin\" option will performantly and securely serve your assets. `npm create harper@latest` scaffolds all of this for you.\n",
48
48
  "typescript-type-stripping": "---\nname: typescript-type-stripping\ndescription: How to run TypeScript files directly in Harper without a build step.\nmetadata:\n mode: synthesized\n---\n\n# TypeScript Type Stripping\n\nInstructions for the agent to follow when using TypeScript in Harper.\n\n## When to Use\n\nUse this skill when you want to write Harper Resources in TypeScript and have them execute directly in Node.js without an intermediate build or compilation step.\n\n## How It Works\n\n1. **Verify Node.js Version**: Ensure you are using Node.js v22.6.0 or higher.\n2. **Name Files with `.ts`**: Create your resource files in the `resources/` directory with a `.ts` extension.\n3. **Use TypeScript Syntax**: Write your resource classes using standard TypeScript (interfaces, types, etc.).\n ```typescript\n import { Resource } from 'harper';\n export class MyResource extends Resource {\n \tasync get(): Promise<{ message: string }> {\n \t\treturn { message: 'Running TS directly!' };\n \t}\n }\n ```\n4. **Use Explicit Extensions in Imports**: When importing other local modules, include the `.ts` extension: `import { helper } from './helper.ts'`.\n5. **Configure `config.yaml`**: Ensure `jsResource` points to your `.ts` files:\n ```yaml\n jsResource:\n files: 'resources/*.ts'\n ```\n",
49
49
  "using-blob-datatype": "---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Using Blob Datatype\n\nInstructions for the agent to follow when working with the Blob data type in Harper.\n\n## When to Use\n\nUse this skill when you need to store unstructured or large binary data (media, documents) that is too large for standard JSON fields. Blobs provide efficient storage and integrated streaming support.\n\n## How It Works\n\n1. **Define Blob Fields**: In your GraphQL schema, use the `Blob` type:\n ```graphql\n type MyTable @table {\n \tid: ID @primaryKey\n \tdata: Blob\n }\n ```\n2. **Create and Store Blobs**: Use `createBlob()` from Harper's globals to wrap Buffers or Streams:\n ```javascript\n import { tables } from 'harper';\n const blob = createBlob(largeBuffer);\n await tables.MyTable.put('my-id', { data: blob });\n ```\n3. **Use Streaming (Optional)**: For very large files, pass a stream to `createBlob()` to avoid loading the entire file into memory.\n4. **Read Blob Data**: Retrieve the record and use `.bytes()` or streaming interfaces on the blob field:\n ```javascript\n const record = await tables.MyTable.get('my-id');\n const buffer = await record.data.bytes();\n ```\n5. **Ensure Write Completion**: Use `saveBeforeCommit: true` in `createBlob` options if you need the blob fully written before the record is committed.\n6. **Handle Errors**: Attach error listeners to the blob object to handle streaming failures.\n",
50
- "vector-indexing": "---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 6d4a30ccd5b32528e0e9963565782dca9fff5ada\n inputHash: 3732961c671aac00\n---\n\n# Vector Indexing\n\nInstructions for the agent to follow when enabling and querying vector indexes for similarity search in Harper using the HNSW algorithm.\n\n## When to Use\n\nApply this rule when adding a vector index to a Harper table schema or writing similarity search queries against high-dimensional vector fields. Use it whenever you need approximate nearest-neighbor search, distance-threshold filtering, or distance-scored results.\n\n## How It Works\n\n1. **Declare a vector index on a `[Float]` field**: Add `@indexed(type: \"HNSW\")` to any `[Float]` attribute in a `@table` type. See [adding-tables-with-schemas.md](adding-tables-with-schemas.md) for general schema setup.\n\n ```graphql\n type Document @table {\n \tid: Long @primaryKey\n \ttextEmbeddings: [Float] @indexed(type: \"HNSW\")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `Document.search()` with a `sort` object specifying `attribute` (the indexed field) and `target` (the query vector). Include `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n3. **Combine HNSW with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n \tconditions: [{ attribute: 'price', comparator: 'lt', value: 50 }],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: Place `target` directly on a condition (alongside `attribute`, `comparator`, and `value`) to return only records whose distance to the target vector is below a threshold. Use this form to bound result quality by a similarity cutoff rather than ranking.\n\n ```javascript\n let results = Document.search({\n \tconditions: {\n \t\tattribute: 'textEmbeddings',\n \t\tcomparator: 'lt',\n \t\tvalue: 0.1,\n \t\ttarget: searchVector,\n \t},\n });\n ```\n\n5. **Include computed distance in results**: Add `'$distance'` to the `select` array to return the computed distance from the target vector alongside each record. `$distance` works in both `sort`-based and `conditions`-based queries.\n\n ```javascript\n let results = Document.search({\n \tselect: ['name', '$distance'],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n6. **Tune HNSW parameters**: Pass additional parameters to `@indexed(type: \"HNSW\", ...)` to control index quality and performance:\n\n | Parameter | Default | Description |\n | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |\n | `distance` | `\"cosine\"` | Distance function: `\"euclidean\"` or `\"cosine\"` (negative cosine similarity) |\n | `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n | `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n | `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n | `mL` | computed from `M` | Normalization factor for level generation |\n | `efSearchConstruction` | `50` | Max nodes explored during search |\n\n## Examples\n\n**Schema with custom HNSW parameters:**\n\n```graphql\ntype Document @table {\n\tid: Long @primaryKey\n\ttextEmbeddings: [Float]\n\t\t@indexed(type: \"HNSW\", distance: \"euclidean\", optimizeRouting: 0, efSearchConstruction: 100)\n}\n```\n\n**Nearest-neighbor search with distance output:**\n\n```javascript\nlet results = Document.search({\n\tselect: ['name', '$distance'],\n\tsort: { attribute: 'textEmbeddings', target: searchVector },\n\tlimit: 5,\n});\n```\n\n**Distance-threshold filter (no ranking):**\n\n```javascript\nlet results = Document.search({\n\tconditions: {\n\t\tattribute: 'textEmbeddings',\n\t\tcomparator: 'lt',\n\t\tvalue: 0.1,\n\t\ttarget: searchVector,\n\t},\n});\n```\n\n## Notes\n\n- The default `distance` function is `cosine`. To use Euclidean distance, set `distance: \"euclidean\"` in the `@indexed` directive.\n- `efConstruction` controls index build quality; increase it to improve recall at the cost of slower indexing.\n- `$distance` is a special field prefix it with `$` exactly as shown; it is not a schema attribute.\n- `target` is required in both `sort`-based and threshold-based condition queries to identify the reference vector for distance computation.\n"
50
+ "vector-indexing": "---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 3732961c671aac00\n---\n\n# Vector Indexing\n\nInstructions for the agent to follow when enabling and querying vector indexes for similarity search in Harper using the HNSW algorithm.\n\n## When to Use\n\nApply this rule when adding a vector index to a Harper table schema or writing similarity search queries against high-dimensional vector fields. Use it whenever you need approximate nearest-neighbor search, distance-threshold filtering, or distance-scored results.\n\n## How It Works\n\n1. **Declare the vector index on a `[Float]` field**: Add `@indexed(type: \"HNSW\")` to any `[Float]` attribute in a `@table` type. See [adding-tables-with-schemas.md](adding-tables-with-schemas.md) for general schema setup.\n\n ```graphql\n type Document @table {\n \tid: Long @primaryKey\n \ttextEmbeddings: [Float] @indexed(type: \"HNSW\")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `Document.search()` with a `sort` object containing `attribute` (the indexed field name) and `target` (the query vector). Include `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n \tconditions: [{ attribute: 'price', comparator: 'lt', value: 50 }],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. Omit `sort`.\n\n ```javascript\n let results = Document.search({\n \tconditions: {\n \t\tattribute: 'textEmbeddings',\n \t\tcomparator: 'lt',\n \t\tvalue: 0.1,\n \t\ttarget: searchVector,\n \t},\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Works with both `sort`-based and `conditions`-based queries.\n\n ```javascript\n let results = Document.search({\n \tselect: ['name', '$distance'],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n6. **Tune HNSW parameters**: Pass additional parameters to `@indexed(type: \"HNSW\", ...)` to control index quality and performance.\n\n | Parameter | Default | Description |\n | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |\n | `distance` | `\"cosine\"` | Distance function: `\"euclidean\"` or `\"cosine\"` (negative cosine similarity) |\n | `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n | `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n | `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n | `mL` | computed from `M` | Normalization factor for level generation |\n | `efSearchConstruction` | `50` | Max nodes explored during search |\n\n## Examples\n\n**Schema with custom HNSW parameters:**\n\n```graphql\ntype Document @table {\n\tid: Long @primaryKey\n\ttextEmbeddings: [Float]\n\t\t@indexed(type: \"HNSW\", distance: \"euclidean\", optimizeRouting: 0, efSearchConstruction: 100)\n}\n```\n\n**Nearest-neighbor search with distance score:**\n\n```javascript\nlet results = Document.search({\n\tselect: ['name', '$distance'],\n\tsort: { attribute: 'textEmbeddings', target: searchVector },\n\tlimit: 5,\n});\n```\n\n**Distance-threshold filter (no ranking):**\n\n```javascript\nlet results = Document.search({\n\tconditions: {\n\t\tattribute: 'textEmbeddings',\n\t\tcomparator: 'lt',\n\t\tvalue: 0.1,\n\t\ttarget: searchVector,\n\t},\n});\n```\n\n## Notes\n\n- The default `distance` function is `cosine`. Pass `distance: \"euclidean\"` to switch.\n- `efConstruction` controls index build quality; raising it improves recall at the cost of build time.\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- Use the threshold (`conditions` + `target`) form when you want to bound result quality by a similarity cutoff rather than ranking by similarity.\n"
51
51
  };
52
52
 
53
53
  /**
54
54
  * The content of the Harper Best Practices SKILL.md.
55
55
  */
56
- export const skillSummary = "---\nname: harper-best-practices\ndescription: Best practices for building Harper applications, covering schema definition,\n automatic APIs, authentication, custom resources, and data handling.\n Triggers on tasks involving Harper database design, API implementation,\n and deployment.\nlicense: Apache-2.0\nmetadata:\n author: harper\n version: '1.0.0'\n---\n\n# Harper Best Practices\n\nGuidelines for building scalable, secure, and performant applications on Harper. These practices cover everything from initial schema design to advanced deployment strategies.\n\n## When to Use\n\nReference these guidelines when:\n\n- Defining or modifying database schemas\n- Implementing or extending REST/WebSocket APIs\n- Handling authentication and session management\n- Working with custom resources and extensions\n- Optimizing data storage and retrieval (Blobs, Vector Indexing)\n- Deploying applications to Harper Fabric\n\n## How It Works\n\n1. Review the requirements for the task (schema design, API needs, or infrastructure setup).\n2. Consult the relevant category under \"Rule Categories by Priority\" to understand the impact of your decisions.\n3. Apply specific rules from the \"Quick Reference\" section below by reading their detailed rule files.\n4. If you're building a new table, prioritize the `schema-` rules.\n5. If you're extending functionality, consult the `logic-` and `api-` rules.\n6. Validate your implementation against the `ops-` rules before deployment.\n\n## Examples\n\nSee the concrete examples embedded in each rule subsection below (GraphQL schemas, REST query patterns, and deployment workflow snippets).\n\n## Rule Categories by Priority\n\n| Priority | Category | Impact | Prefix |\n| -------- | -------------------- | ------ | --------- |\n| 1 | Schema & Data Design | HIGH | `schema-` |\n| 2 | API & Communication | HIGH | `api-` |\n| 3 | Logic & Extension | MEDIUM | `logic-` |\n| 4 | Infrastructure & Ops | MEDIUM | `ops-` |\n\n## Quick Reference\n\n### 1. Schema & Data Design (HIGH)\n\n- `adding-tables-with-schemas` - Define tables using GraphQL schemas and directives\n- `schema-design-tooling` - Core directives and GraphQL IDE/agent configuration\n- `defining-relationships` - Link tables using the `@relationship` directive\n- `vector-indexing` - Efficient similarity search with vector indexes\n- `using-blob-datatype` - Store and retrieve large data (Blobs)\n- `handling-binary-data` - Manage binary data like images or MP3s\n\n### 2. API & Communication (HIGH)\n\n- `automatic-apis` - Leverage automatically generated CRUD endpoints\n- `querying-rest-apis` - Filters, sorting, and pagination in REST requests\n- `real-time-apps` - WebSockets and Pub/Sub for Real-Time Apps\n- `checking-authentication` - Secure apps with session-based identity verification\n\n### 3. Logic & Extension (MEDIUM)\n\n- `custom-resources` - Define custom REST endpoints using JS/TS\n- `extending-tables` - Add custom logic to generated table resources\n- `programmatic-table-requests` - Advanced filtering and sorting in code\n- `typescript-type-stripping` - Use TypeScript without build tools\n- `caching` - Implement and define caching for performance\n\n### 4. Infrastructure & Ops (MEDIUM)\n\n- `deploying-to-harper-fabric` - Scale globally with Harper Fabric\n- `creating-a-fabric-account-and-cluster` - Setting up your Harper Fabric cloud infrastructure\n- `creating-harper-apps` - Quickstart with `npm create harper@latest`\n- `serving-web-content` - Ways to serve web content from Harper\n- `logging` - Use standard console and Harper's granular logger\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/adding-tables-with-schemas.md\nrules/schema-design-tooling.md\nrules/automatic-apis.md\nrules/creating-harper-apps.md\nrules/logging.md\n```\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded: `AGENTS.md`\n";
56
+ export const skillSummary = "---\nname: harper-best-practices\ndescription: Best practices for building Harper applications, covering schema definition,\n automatic APIs, authentication, custom resources, and data handling.\n Triggers on tasks involving Harper database design, API implementation,\n and deployment.\nlicense: Apache-2.0\nmetadata:\n author: harper\n version: '1.0.0'\n---\n\n# Harper Best Practices\n\nGuidelines for building scalable, secure, and performant applications on Harper. These practices cover everything from initial schema design to advanced deployment strategies.\n\n## When to Use\n\nReference these guidelines when:\n\n- Defining or modifying database schemas\n- Implementing or extending REST/WebSocket APIs\n- Handling authentication and session management\n- Working with custom resources and extensions\n- Optimizing data storage and retrieval (Blobs, Vector Indexing)\n- Deploying applications to Harper Fabric\n\n## How It Works\n\n1. Review the requirements for the task (schema design, API needs, or infrastructure setup).\n2. Consult the relevant category under \"Rule Categories by Priority\" to understand the impact of your decisions.\n3. Apply specific rules from the \"Quick Reference\" section below by reading their detailed rule files.\n4. If you're building a new table, prioritize the `schema-` rules.\n5. If you're extending functionality, consult the `logic-` and `api-` rules.\n6. Validate your implementation against the `ops-` rules before deployment.\n\n## Examples\n\nSee the concrete examples embedded in each rule subsection below (GraphQL schemas, REST query patterns, and deployment workflow snippets).\n\n<!-- BEGIN GENERATED INDEX -->\n\n## Rule Categories by Priority\n\n| Priority | Category | Impact | Prefix |\n| -------- | -------------------- | ------ | --------- |\n| 1 | Schema & Data Design | HIGH | `schema-` |\n| 2 | API & Communication | HIGH | `api-` |\n| 3 | Logic & Extension | MEDIUM | `logic-` |\n| 4 | Infrastructure & Ops | MEDIUM | `ops-` |\n\n## Quick Reference\n\n### 1. Schema & Data Design (HIGH)\n\n- `adding-tables-with-schemas` Guidelines for adding tables to a Harper database using GraphQL schemas.\n- `schema-design-tooling` Best practices for Harper schema design, including core directives and GraphQL tooling configuration.\n- `defining-relationships` How to define and use relationships between tables in Harper using GraphQL.\n- `vector-indexing` How to enable and query vector indexes for similarity search in Harper.\n- `using-blob-datatype` How to use the Blob data type for efficient binary storage in Harper.\n- `handling-binary-data` How to store and serve binary data like images or audio in Harper.\n\n### 2. API & Communication (HIGH)\n\n- `automatic-apis` How to use Harper's automatically generated REST and WebSocket APIs.\n- `querying-rest-apis` How to use query parameters to filter, sort, and paginate Harper REST APIs.\n- `real-time-apps` — How to build real-time features in Harper using WebSockets and Pub/Sub.\n- `checking-authentication` How to handle user authentication and sessions in Harper Resources.\n\n### 3. Logic & Extension (MEDIUM)\n\n- `custom-resources` How to define custom REST endpoints with JavaScript or TypeScript in Harper.\n- `extending-tables` How to add custom logic to automatically generated table resources in Harper.\n- `programmatic-table-requests` How to interact with Harper tables programmatically using the `tables` object.\n- `typescript-type-stripping` How to run TypeScript files directly in Harper without a build step.\n- `caching` How to implement integrated data caching in Harper from external sources.\n\n### 4. Infrastructure & Ops (MEDIUM)\n\n- `deploying-to-harper-fabric` How to deploy a Harper application to the Harper Fabric cloud.\n- `creating-a-fabric-account-and-cluster` How to create a Harper Fabric account, organization, and cluster.\n- `creating-harper-apps` How to initialize a new Harper application using the CLI.\n- `serving-web-content` How to serve static files and integrated Vite/React applications in Harper.\n- `logging` Best practices for logging in Harper, including console capture, the granular logger interface, and programmatic log retrieval.\n\n<!-- END GENERATED INDEX -->\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/adding-tables-with-schemas.md\nrules/schema-design-tooling.md\nrules/automatic-apis.md\nrules/creating-harper-apps.md\nrules/logging.md\n```\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded: `AGENTS.md`\n";