Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions doc/2026-11-11_design_id5998.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Design: used-capability derivation tool — static call-graph scan producing the registry used-set

- Date: 2026-11-11
- Status: **design** — specification only; the tool is not implemented here.
- Issue: [#5998](https://github.com/developing-today/code/issues/5998), part of the worlds design program [#5955](https://github.com/developing-today/code/issues/5955); parent topic [#5958](https://github.com/developing-today/code/issues/5958).
- Scope: the static discovery producer for the registry's `used.static` set — inputs, algorithm, over-approximation rules, and output schema, specified tightly enough to implement without further design decisions. Out of scope: implementing the tool; the observed-use (profiling) producer, which already exists as `CapLedger` usage counts; the permission-UX surfacing of over-declaration (sibling under #5955); the dynamic-loading exception policy (follow-up under #5955 — this spec defines only the *uncertified* marking that policy consumes).

## Decision to make

Given a world program's Roc source closure and the capability catalog, which catalog capabilities can the program's code reach — computed statically, deterministically, and in exactly the registry representation #5958 defines, so that `requested − used_static` (the narrowing delta) is a plain set difference?

#5958's design record (issue comment 6720327099) settles the model this tool serves:

- Discovery is evidence, never authority: the discovered set informs the registry picture and narrowing recommendations; it never grants or widens anything.
- The used set is two properties, never collapsed: `used_static` (a property of the code, per build — "uses at most this") and `used_observed` (a property of runs so far). This tool produces **only** `used_static`.
- The registry stores the pair with provenance and never silently merges; a static/observed disagreement is a flagged defect, stored, not hidden.

## Context and current state (verified against main, 2026-11-11)

- **The catalog namespace is concrete.** `pkgs/id/crates/id-core/src/world_caps.rs` defines the provider catalog as a const registry: `PROVIDER_REGISTRY` / `CATALOG` built by the `define_provider_registry!` macro over manifest entries (`ProviderManifest { name, version, kind, argument_schema, bounds, required_scope, default_ceiling }`). Two entry kinds matter here: host providers named like `chat.say`, `records.read`, `time.now` (Request/Subscription kinds), and `ProviderKind::PlatformModule` entries named `Key`, `Screen`, `RocJson`, `RocGrid`, `RocCap`, `RocText`. `catalog_names() -> BTreeSet<String>` and `is_known(name)` already exist.
- **Capabilities are exercised by naming them as data.** A world program is a Roc app on the roc-world platform (`pkgs/id/examples/roc-world/`). It never calls the host directly; it returns a `wants` document whose `requests`/`subscribe` entries name catalog capabilities as strings — e.g. `RocCap.issue(session, "chat.say")` in `pkgs/id/examples/roc-chat/main.roc`, with request documents built by `RocCap` helper defs (`chat_request`, `history_request`, …) that embed the same `"cap"` names. Subscriptions may carry an argument suffix: `"time.tick:5000"`. Using a platform module is likewise explicit: `import pf.RocCap`.
- **The declared set has the same shape.** `Wants` (`parse_wants`, `WANTS_VERSION = 1`) and `CapLedger`'s `granted`/`allowed` sets are `BTreeSet<String>` over catalog names, and `UNKNOWN_CAP_USAGE_KEY = "<unknown>"` already names the unattributable-use bucket. The tool's output is that same set type, per #5958 §5.
- **No derivation tool exists.** Code search over `pkgs/id` finds no call-graph / used-capability derivation implementation.
- **#5963 (programming model) is open** and constrains only the first-class-function rule. Per the #5998 triage of record (issue comment 6700990165), the spec adopts the conservative sound rule now — a platform function passed as a value counts as used — and may narrow it later only if #5963's model makes value-passing trackable.

## Specification

### 1. Tool identity and home

The tool is a Rust binary target in `pkgs/id` (working name `capscan`), linking `id-core` so the catalog it scans against is `PROVIDER_REGISTRY` from the same source tree it ships with — never a copied name list. It is a pure function of its inputs (§2): no network, no clock, no environment reads beyond its arguments. Invocation:

```
capscan --entry <main.roc> [--entry <extra.roc> ...] \
--platform <roc-world platform dir> \
--world-id <id> \
[--out <file>] # default: stdout
```

Exit codes: `0` scan complete (certified or not — certification is data, §6); `2` incomplete closure or unreadable input (§3, step 1); `3` catalog mismatch (a name the program names is neither in the catalog nor resolvable to the `<unknown>` rule of §5.4 — reserved; see §5.4 for why this is currently unreachable and kept for forward compatibility).

### 2. Inputs

1. **Entry modules** — one or more Roc source files: the world's app module(s) (the module(s) the platform instantiates; typically one `main.roc`).
2. **Platform directory** — the roc-world platform tree (contains `RocCap.roc`, `RocJson.roc`, `RocGrid.roc`, `RocText.roc`, `Key.roc`, `Screen.roc`, `main.roc`/`platform.roc`). Platform modules are part of the scanned closure (§3) because capability names live inside their helper defs.
3. **World id** — an opaque string copied into the output (§6); the tool attaches no semantics to it.
4. **The catalog** — `PROVIDER_REGISTRY` from the linked `id-core`, recorded in the output by source commit (§6). The tool refuses no catalog version; it reports the one it used.

Nothing else is an input. In particular the tool does **not** read the world's declared `wants`, its ceiling, or any registry state: `used_static` is a property of code + catalog only (that is what makes the registry's later diff meaningful).

### 3. Algorithm

**Step 1 — Source closure.** Starting from the entry modules, follow `import` edges (`import pf.<Module>`, `import <Module>`) across the app tree and the platform directory until fixpoint. Every import must resolve to a file in one of the two trees; an unresolvable import is an incomplete closure → exit `2` with the unresolved edge named. Files in the trees that are never imported are not scanned.

**Step 2 — Def graph.** For each file in the closure, enumerate its top-level definitions (Roc `name = value` / `name : type` + definition pairs, including defs inside nominal-type namespaces such as `RocCap.{ … }` blocks). A def's identity is `(module, name)`. Build edges def → def for every identifier reference in a def's body that resolves to a top-level def in the closure (qualified `Module.name` references resolve directly; unqualified references resolve within the module, then via its imports). String literals and comments are stripped before reference extraction (but see step 4: literal extraction happens first, per def). References that resolve to Roc builtin/stdlib names (not in the closure) are leaves.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve executable references inside string interpolations

For a reachable definition such as wants = |model| "${make_wants(model)}", stripping the string before reference extraction removes the call to make_wants. The helper is then classified as dead, and any capability literals in its request builders disappear from the supposedly certified upper bound. Roc interpolation executes ordinary expressions, as existing examples demonstrate in pkgs/id/examples/territory/main.roc:110. Strip literal text while recursively retaining references inside interpolation expressions.

Useful? React with 👍 / 👎.


**Step 3 — Reachability.** Roots are the defs the platform calls: in each entry module, the defs named `init`, `update`, `view`, `wants`, and — when defined — `layout`, `restore`, `snapshot`, `records` (the Roc-level counterparts of the `plaza_*` host exports in `pkgs/id/examples/roc-world/ABI.md`), plus every def referenced by the entry module's top-level app expression. The reachable set is the transitive closure of the def graph from the roots. Defs outside it are dead for this build and contribute nothing (§5.1).

**Step 4 — Use extraction.** For each reachable def, collect:

- **(a) Module uses.** An `import` of a module whose name is a `PlatformModule` catalog entry (`Key`, `Screen`, `RocJson`, `RocGrid`, `RocCap`, `RocText`) adds that entry. The import counts when the importing module contains at least one reachable def. (Importing a platform module is how a program gains the module's values at all, so the module entry is used exactly when reachable code can name it.)
- **(b) Capability literals.** Every string literal in the def whose content — after stripping one optional `:<args>` suffix (the subscription argument form, e.g. `time.tick:5000`) — is a host-provider catalog name adds that name. This is the primary rule: capabilities are named as data (§Context), so the literal *is* the use site, whether it appears as a `RocCap.issue` argument, inside a `"cap"` field of a request document the def builds, or in a `subscribe` list. It applies equally to literals inside platform-module defs (the `RocCap.chat_request` builder's embedded `"chat.say"` counts when — and only when — that builder def is reachable).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Extract capabilities from serialized wants documents

The existing pkgs/id/examples/territory/main.roc:115 returns its entire wants document as one escaped JSON string containing a players subscription. That literal's content is not itself a catalog name, so this extraction rule omits players; because there is no computed capability expression, §5.4 also provides no reason to mark the result uncertified. An implementation following this specification would therefore certify an incomplete set for an existing world. Specify extraction from serialized wants documents, or require an uncertified result when their capability contents cannot be resolved.

Useful? React with 👍 / 👎.

- **(c) Value-passed platform defs.** If a reachable def references a platform-module def in **value position** (passed as an argument, stored, returned — anywhere other than the head of a call), add **every** catalog name that def's own body can emit (its rule-(b) literal set, computed over the platform closure). See §5.2.

**Step 5 — Emit.** The used-set is the union over all reachable defs, as a sorted `BTreeSet<String>` of catalog names, plus the diagnostics of §5.4 and the output document of §6. Set construction is order-independent; diagnostics are sorted by (file, line, column) so output is byte-for-byte deterministic for identical inputs.

### 4. What is deliberately not analysed

- **No dataflow beyond §5.3.** The tool does not track values through variables across defs, does not evaluate expressions, and does not prune by reachability of *call sites within* a def (a literal in an untaken branch of a reachable def counts — that is the documented static over-approximation #5958 already expects: "over-approximates along dead or never-taken paths" *within* live code; only whole-def dead code is excluded, by step 3).
- **No compiled-artifact analysis.** The scan is over source. A build system that transforms source before compiling must scan the transformed source (the `build_hash` in §6 is over the scanned closure, so a mismatch is detectable, never silent).

### 5. Over-approximation and limitation rules (normative)

**5.1 Dead code.** A capability literal in an unreachable def does **not** count. Rationale: def-level reachability is decidable from the def graph alone; anything finer (branch-level) is §4's accepted over-approximation. This rule is what keeps a library's unused helpers from inflating every consumer's used-set: only defs reachable from *this* program's roots count, including library defs pulled in transitively.

**5.2 First-class platform functions (the #5998 over-approximation).** Roc programs pass functions as values freely, and a platform helper passed as a value can be invoked anywhere its recipient pleases. Rule: **a platform function passed as a value counts as used — with its full emitted set.** Concretely (§3 step 4c): referencing a platform-module def in value position adds every catalog name that def can emit, not merely the names at the reference site. There is no attempt to track where the value flows. This is the conservative sound rule the #5998 triage adopted pending #5963; if #5963 lands a model in which value-passing is trackable, this section — and only this section — is revisited. Symmetrically, an *app* def passed as a value needs no rule: it is in the def graph, and reachability already includes defs referenced as values (step 2 counts value references as edges).

**5.3 Resolved forwarding.** Capability names are data, so app code may forward them: `issue_twice = |cap| RocCap.issue(session, cap)`. Literals are counted at their literal sites (§3 step 4b), which are the call sites that supply concrete names — forwarding defs themselves contain no literal and add nothing. To keep that sound without dataflow analysis, one syntactic rule is normative: a def that takes a parameter and passes it **directly** (the parameter itself, unmodified) into a capability position — the `cap` argument of a `RocCap.issue`-shaped call, a `"cap"` record field, or a `subscribe` list element — is a *forwarder*, and every call site of a forwarder is a use site whose literal arguments are extracted by rule (b) as if they appeared in the forwarder. Any transformation of the parameter (concatenation, casing, lookup) breaks the forwarder shape and falls under §5.4.

**5.4 Dynamic dispatch, computed names, runtime loading (the limitation, stated explicitly).** If a capability position is filled by an expression the rules above cannot resolve to literals — a computed or concatenated string, a value loaded from the model or an event, a name obtained by dynamic/runtime loading of code not in the source closure — the tool:

- adds **no** guessed names for that site;
- records a diagnostic `{ file, line, column, kind: "unresolved-capability" }` in the output (§6);
- sets `certified: false` on the output.

A scan with any such site is an **uncertified** result: its `used_static` is a lower bound for that build, not the upper bound #5958's presentation requires, and consumers (the registry, the #5955 dynamic-loading exception policy) must treat it as such. Unknown names that are literal but absent from the catalog are **not** diagnostics: they are dropped from the set (the catalog is the vocabulary; `is_known` already teaches the runtime the same convention) — exit code `3` is reserved for a future catalog-attestation mode and is not produced by this version. Runtime-loaded code is out of the closure by definition; worlds that load code dynamically are exactly the uncertified case, and marking them — not analysing them — is this tool's whole obligation under #5955's split.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid promising a lower bound for uncertified results

When a reachable definition contains both a capability literal in a never-taken branch and an unresolved computed request, §4 retains the former while §5.4 omits the latter. The resulting set can contain capabilities the build cannot exercise and omit capabilities it can exercise, so it is neither an upper nor a lower bound. Calling it a lower bound and requiring registry/policy consumers to treat it that way incorrectly promises that every retained member is a genuine possible use. Specify uncertified output as incomplete candidate evidence with possible false positives, rather than a guaranteed subset.

Useful? React with 👍 / 👎.


**5.5 Subscriptions with arguments.** `time.tick:5000` is a use of `time.tick` (suffix stripped, §3 step 4b), matching how `parse_wants` treats subscription entries. Two different argument values are one used-set entry.

### 6. Output schema (normative)

The tool emits one JSON document. Field names and types are the contract; `used.static` is designed to drop into the #5958 §5 registry entry unchanged.

```json
{
"world_id": "…",
"build_hash": "blake3:…",
"catalog_commit": "0865aad9a9d6",
"vocab_version": 1,
"certified": true,
"used": {
"static": ["chat.say", "time.now"]
},
"unresolved": [
{ "file": "main.roc", "line": 41, "column": 13, "kind": "unresolved-capability" }
]
}
```

- `world_id` — the `--world-id` input, verbatim.
- `build_hash` — BLAKE3 over the canonical concatenation of the source closure: for each file in closure order (sorted by path relative to its tree root, app tree before platform tree), the relative path bytes, a NUL, the file bytes, a NUL. This is the identity #5958's registry keys `used_static` by ("exact for a given build hash"); a different closure is a different build and must produce a different entry, never an updated one.
- `catalog_commit` — the git commit of the `id-core` source the tool was built from (embedded at build time; `unknown` for a build outside a checkout, which registries should treat like an uncertified provenance).
- `vocab_version` — `1`, the catalog vocabulary version of #5958 §2.
- `certified` — `false` iff `unresolved` is non-empty (§5.4). A certified scan asserts: every capability this build's reachable code can name is in `used.static` (the over-approximation rules of §5 are the only slack).
- `used.static` — the used-set: a JSON array of catalog names, sorted ascending, duplicates removed — precisely the serialization of the Rust `BTreeSet<String>` the declared sets use, and exactly the `used.static` array of the #5958 registry schema (§5 of the design record). `requested − used.static` and `used.static − requested` are plain set differences over these arrays.
- `unresolved` — diagnostics as in §5.4, sorted by (file, line, column); `file` is the path relative to its tree root. Empty when `certified` is `true`.

The tool emits no other output on stdout. Human progress/diagnostic chatter, if any, goes to stderr and is not part of the contract.

### 7. Worked expectations (acceptance fixtures for the implementer)

Against `pkgs/id/examples/roc-chat` (entry `main.roc`, platform `pkgs/id/examples/roc-world`):

1. `used.static` contains `RocCap` and `RocJson` (platform modules imported by reachable code), `chat.say` and `chat.history` (literals at `RocCap.issue` call sites in reachable defs, and inside the reachable `RocCap` builders), and `certified` is `true` with `unresolved` empty.
2. Deleting the send-message branch's def from the app (making `chat.say`'s only sites unreachable) removes `chat.say` and keeps `chat.history` (§5.1).
3. Passing `RocCap.chat_request` as a value to an app helper keeps `chat.say` in the set even if no call site names it (§5.2).
4. Building a cap name by `Str.concat("chat.", verb)` in a reachable def yields `certified: false` and one `unresolved-capability` diagnostic at that site (§5.4).
5. A reachable literal `"time.tick:5000"` in a subscribe list yields `time.tick` (§5.5).
6. A literal naming a non-catalog string (e.g. `"chat.fax"`) in a reachable def changes nothing in the output (§5.4).

## Consequences

- **Implementable as specified.** Inputs, closure, graph, roots, extraction rules, the forwarder rule, the uncertified rule, and the output bytes are all pinned; the remaining implementation choices (Roc lexing/parsing mechanics) cannot change results on inputs the fixtures cover.
- **The registry pairing works unchanged.** `used.static` is #5958's representation, so the S16 line — "it asks for {requested}, its code can reach {used_static}, and it has been seen using {used_observed}" — needs no adapter, and the narrowing delta is a set difference.
- **Soundness is stated, not implied.** Certified ⇒ over-approximating upper bound for the scanned build. Uncertified ⇒ explicitly marked lower bound with named sites. Neither case silently pretends exactness, which is the honesty property #5958 §4 requires of the used set.
- **One open seam, deliberately.** §5.2 narrows only if #5963 makes value-passing trackable; §5.4's uncertified marking is the input the #5955 dynamic-loading exception policy grades. Both follow-ups consume this spec without amending its output schema.
Loading