# AGENTS.md

```yaml
audience: AI coding agents (Claude Code, Cursor, Codex, Copilot, Gemini CLI and similar)
purpose: Add LAP to an existing website, web app, service or device hub so that any AI agent can act on it through intent links.
normative_spec: spec/PROTOCOL.md
schemas: [spec/lap.schema.json, spec/resolution.schema.json]
examples: spec/examples/ (booking, render, publish, device manifests; a resolution)
reference_implementation: site/ in this repository (the LAP directory: one read action with lap=json, one propose action with JSON receipts)
language_of_your_reply_to_the_user: the user's language
```

## 0. Goal and non-goals

Goal: after your change, a user can say to any AI "do X on <their site>", the AI writes a link, and the user lands on a page that shows exactly what will happen (or sees the result directly, for read and render actions). Where something changes, the user confirms, or a registered device commits it within a grant.

Non-goals: do not build an MCP server, an API for agents, or a browser automation layer. Do not change existing URLs or flows. Everything you add is additive.

## 1. Hard rules for you (the coding agent)

1. Read `spec/PROTOCOL.md` sections 0 to 8 before writing code. Cite rule IDs (INV-, SEC-, C-) in code comments where a rule drives a decision.
2. INV-1 is absolute: no GET handler you add may change state. Put every real effect behind POST (or signed POST).
3. Never put personal data or secrets in query strings. Prefill only through the URL fragment, read client-side.
4. Every fact that appears in more than one place (manifest, `llms.txt`, HTML, structured data) must be generated from one config source (INV-9). Add a test that proves it.
5. Stop and ask the human before: enabling `execute` actions or grants, adding any R3 action, exposing personal data in any new response, changing existing routes, choosing public action names or legal text.
6. Write all user-visible text in the language of the site. Write code comments in the language of the codebase.
7. How the site computes its own values (availability, rules, any cost) stays the site's business. Do not redesign it; expose it through resolve and recompute it at commit.

## 2. Procedure

### STEP 1. Survey (read-only)

Produce an inventory before writing code:

| Item | What to record |
|---|---|
| Stack | language, framework, router, rendering (server, client, static), hosting, database |
| Entry points | existing routes and forms that cause effects (booking, contact, post, message, device control) |
| Data | where services, slots, destinations, documents, devices live; how to read them |
| Auth | how the owner and users authenticate; session cookies; CSRF protection in place |
| Existing AI surfaces | `llms.txt`, schema.org, robots.txt rules for agent user agents |

### STEP 2. Choose actions

For each user goal the site supports, decide:

```
if the result can be computed in the browser from text in the link -> kind=render, risk=R0
elif it only returns information                                  -> kind=read,   risk=R0
elif it involves money or physical safety (pay, unlock, heat)     -> kind=propose, risk=R3, consent=strong
elif it is public or hard to undo (booking, post, message, form)  -> kind=propose, risk=R2 (or execute with grants, ask human first)
else (reversible, private: draft, note, calendar, lights)          -> kind=propose or execute, risk=R1
```

Read and render actions need no confirmation: the page shows the result as soon as the link opens. Only ask for a click where something changes (PROTOCOL 4.4).

Name actions `noun.verb` (`booking.create`, `post.publish`, `note.create`, `light.set`). Start with the 1 to 3 actions that matter most to the owner.

### STEP 3. Design each intent link

- Path: reuse a short route (`/book`, `/post`, `/act/light`) or the site's existing language. Declare it; agents use what you declare.
- Params: short names, plain-text values, codes from a data source. Prefer formats agents already know: comma-separated codes, `YYYY-MM-DD`, `HH:MM`, ASCII grids, Markdown, CSV.
- Keep typical links under 500 characters (PROTOCOL 3.3).
- Mark agent-supplied values the server must not trust with `trusted: false` (for example an expected value the agent quotes).
- Fragment keys only for personal prefill (`name`, `phone`, `email`, `address`, `note`, mapped to local names) or client-side payloads.

### STEP 4. Implement resolve (GET, read-only)

Pseudocode, stack-agnostic:

```
GET {action path}?{params}
  parsed  = parse(params)                     # never throws; collects issues
  result  = evaluate(parsed, live_data, now)  # recompute availability, permissions, device state
  issues  = result.issues + suggestions(parsed, live_data)   # nearest codes, nearest free slots, alternatives
  if query.lap == "json" or accepts("application/vnd.lap+json"):
      return json(resolution(result, issues))  # validate against spec/resolution.schema.json
  return html(preview_page(result, issues))    # provider identity, effects, official values, issues as links, commit form
preview_page client script:
  read location.hash -> prefill editable fields -> show "prefilled, please check" -> history.replaceState(remove hash)
headers: Cache-Control no-cache, Referrer-Policy no-referrer, X-Robots-Tag noindex
```

Share `parse` and `evaluate` between browser and server when the stack allows.

### STEP 5. Implement commit (POST)

```
POST {commit endpoint}
  require same-origin (or CSRF token); require Idempotency-Key
  if key seen: return previous receipt
  result = evaluate(parsed, live_data, now)            # recompute again (INV-3)
  if result.version != body.seen_version: return 409 changed + fresh resolution
  if risk == R3: require strong consent (WebAuthn user verification)
  validate personal data typed on the page; rate-limit by address and by principal identifier
  create record in state awaiting_consent | committed; hold resources with expiry
  return 201 { id, receipt_url }
```

### STEP 6. Implement receipts

`GET {receipt path}` shows status for humans; with `lap=json` returns the receipt object (PROTOCOL 5.5). Ids: random, at least 30 bits, rate-limited lookups. Mask personal data.

### STEP 7. Optional: execute and grants (L3, ask the human first)

Follow PROTOCOL 6.2 and 6.3 exactly: Ed25519 JWS, 60-second window, `jti` replay store, grant check, no R3, audit log visible to the owner, one-step revocation, `stop` action for every actuator. This is what lets a chain of steps (for example render a result, then publish it) run without clicks (PROTOCOL C.3).

### STEP 8. Publish discovery

1. Generate `/.well-known/lap.json` from config; validate against `spec/lap.schema.json`. Include at least one example per action.
2. Generate `/llms.txt` from the same config: a paragraph telling agents that preparing the link is the help they should give (PROTOCOL AGT-1), the grammar, codes or a pointer to the data source, one example per action.
3. Home page: `<link rel="describedby" href="/.well-known/lap.json" type="application/json">`, a visible "for AI assistants" section, and a direct action link next to each item.
4. schema.org `potentialAction` with `target.urlTemplate` per item.
5. robots.txt: allow `/.well-known/`, `/llms.txt` and resolve paths; block only private areas.
6. Do not use `/.well-known/agent-card.json` (A2A owns it); do not delete it if it exists.

### STEP 9. Tests (must pass before you report done)

Implement the checks in PROTOCOL 12.2 that apply to the chosen level, at minimum:

- C-01 manifest valid against schema; C-02 every example URL opens with no side effects (assert record counts unchanged).
- C-03 GET never commits; C-04 soft failures produce suggestions; C-05 untrusted params do not change outcomes.
- C-06 resolution JSON valid and free of personal data; C-07 idempotency; C-08 stale value rejected.
- C-09 receipts; C-10 headers; C-11 manifest, `llms.txt` and HTML agree (toggle a config value in a test and assert every surface changes).
- One end-to-end test in a real browser: open an example link with a fragment, assert fields prefilled and hash removed, commit, assert receipt state.

### STEP 10. Report to the human

Reply in the user's language with: actions added (id, risk, example link), conformance level reached, tests run and results, decisions you made that change behavior, and the list of items that need a human (legal text, grants, R3 actions, data quality).

## 3. Reference implementation map (this repository)

The LAP directory in `site/` is itself a LAP provider (`directory.search` read action, `site.submit` propose action).

| Concern | File |
|---|---|
| Single config source and generated surfaces (manifest, `llms.txt`, HTML) | `site/src/catalog.js` |
| Routes, read action with `lap=json`, submit, receipts, headers | `site/src/app.js` |
| Server-rendered pages, escaping | `site/src/render.js` |
| Automated conformance checker for submitted sites | `site/src/checker.js`, `site/src/safefetch.js` |
| Proof-of-work challenge for anonymous commits | `site/src/captcha.js` |
| Tests (GET has no side effects, INV-9 consistency, schemas) | `test/` |

## 4. Done checklist

- [ ] No GET changes state (C-02, C-03 pass)
- [ ] No personal data or secrets in any query string or log
- [ ] Manifest valid; every action has at least one example that opens cleanly
- [ ] Soft failures with suggestion links for every parameter
- [ ] Commit recomputes, is idempotent, rejects stale values
- [ ] Receipts reachable, ids unguessable, personal data masked
- [ ] `llms.txt`, manifest and HTML generated from one source; consistency test passes
- [ ] Existing site behavior unchanged; existing tests pass
- [ ] Human informed of everything in STEP 10
