Skip to content
Back to skills

Author Hook Policy

ASecurity

Declare, bind, inspect, and test a LunCoSim function-shaped Rhai hook policy through the owner macro and authored policy manifest.

  • 112 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 7, 2026
businessrustgo

Security analysis

A100/100

Scanned November 7, 2026

npx -y skills add LunCoSim/lunco-sim --skill author-hook-policy --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Author Hook Policy?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Author Hook Policy
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/luncosim-author-hook-policy/badge)](https://www.skillsdirectory.com/skills/luncosim-author-hook-policy)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: author-hook-policy
description: Declare, bind, inspect, and test a LunCoSim function-shaped Rhai hook policy through the owner macro and authored policy manifest.
---

# Author a hook policy

Use this skill when a decision should be changeable without recompiling the
engine. A hook is a function-shaped seam: Rust publishes a small typed fact
boundary and Rhai supplies the policy implementation.

Treat hook candidacy as a mandatory design step. Prefer a hook for changeable
lifecycle, routing/selection, presentation, permission, deployment, or
Twin-specific behavior. A hook may expose substantial behavior with nested
maps/arrays and return a typed decision or action plan. Its owner must validate
and consume that result through a generic mechanism; use `Unit` for a pure
notification and never leave a decision result unread. Keep continuous math,
kinematics, dynamics, invariants, and hot paths in Rust or Modelica. Before
adding a Rust branch, identify the owner, fact inputs, result consumer,
installation scope, lifecycle, failure/required semantics, and the production
Rhai test.

## Read first

- [`AGENTS.md`](../../AGENTS.md) for ownership, failure, asset, and test rules.
- [`hook-policies.md`](../../docs/architecture/hook-policies.md) for the
  active hook contract.
- [`native-hook-providers.md`](../../docs/architecture/native-hook-providers.md)
  when a trusted native implementation or an expensive domain kernel is under
  consideration.
- [`rust-rhai-modelica-boundary`](../rust-rhai-modelica-boundary/SKILL.md) when
  deciding whether the seam belongs in Rust, Rhai, USD, or Modelica.
- [`validate-assets`](../validate-assets/SKILL.md) for authored production
  scene-test execution.

## Declare the seam at its owner

Place one `lunco_hooks::declare_hook!` invocation beside the owner’s hook id
and decision function. It is collected automatically; do not edit a central
list. Declare the function-shaped ABI with named parameters and a
`HookValueType` for each parameter and the result:

```rust
lunco_hooks::declare_hook! {
    id: MY_HOOK,
    owner: "my-owner",
    description: "Choose a generic engine action from authored facts.",
    signature: [ctx: Map],
    output: String,
    deterministic: false,
    required: false,
    installable: true,
}
```

Keep the map contents as owner facts, not a second ad-hoc registry. Use a
deterministic contract only when identical inputs must produce the same result
on every peer. Set `required` only when the generic mechanism cannot operate
safely without a policy.

For scheduled or async owner work, consume the `runtime_context` supplied by
the hook owner and reject calls from the wrong cycle or phase. The owner must
capture the context before dispatch, preserve it through worker completion,
and reject stale results before publication. Test the scheduled path and an
intentional off-cycle call in production authored Rhai.

## Author and select the policy

Put the implementation in `assets/scripting/policy/<name>.rhai` and add one
entry to `assets/scripting/policy/index.toml`:

```toml
kind = "lunco.policy.v1"
scope = "application" # use "twin" for a Twin-owned manifest

[[policies]]
hook = "my.hook"
source = "my_policy.rhai"
entry = "decide"
deterministic = false
required = false
```

The required `scope` separates `application` policy discovery from the mounted
Twin's `twin` policy layer. The manifest's single `[startup]` entry names the
Rhai function that receives and installs all resolved policy records. The
application manifest is loaded at simulation startup. A Twin may provide its
own uniquely marked `scope = "twin"` policy manifest; its
matching entries replace application records before its own startup function
runs when that Twin becomes active. The Twin startup function receives the
Twin-owned records; application policies remain active for seams the Twin does
not replace. A Twin manifest that contains policy records must declare its own
`[startup]` source and entry; an empty Twin policy directory may omit it. Do
not add a Rust-side policy list or a second bootstrap path. Twin policy
manifests are selected from the mounted Twin's indexed file inventory, so keep
them inside that Twin root; activation does not rescan the directory tree.
When `skip_when_hook_unavailable = true`, the runtime omits the policy only
when that hook owner is not linked into the selected build and reports its id
in `policy_status().unavailable`. Source, compile, and activation failures
remain visible, and required policies cannot use this flag.
The source path is resolved by the asset/storage layer. Do not read policy
files through `std::fs` in a runtime/domain crate.

Inline `bind_policy(id, entry, source)` is useful for a local non-deterministic
experiment. It mutates the caller's existing application or Twin layer through
the policy owner. A Twin caller needs its exact active identity; a scene-bound
caller also needs its current lifecycle generation. UI calls remain available
during preparation, while simulation calls require committed scene readiness.
Retired callbacks are rejected. Application calls cannot
overwrite Twin-owned policies, and USD-authored policies require editing their
USD owner. Twin closure restores the retained application implementation.
It must not claim a deterministic contract. Use `unbind_policy`
to remove exactly that implementation; reloading the authored manifest is the
explicit operation that installs the authored policy again.

For a trusted native implementation, add an explicit `[[native_plugins]]`
entry to the Twin manifest. Use a portable Twin-relative path without a root,
volume, parent traversal, or alternate data stream. The loader checks canonical
containment before admitting a library, including symlinks and Windows junctions.
The provider must implement an existing reflected
installable hook and return the declared typed result through the native ABI;
it does not declare a second hook list or mutate the owner's ECS/USD state.
Use a native provider for expensive or platform-specific computation, not for
changeable product policy. An eventual terrain provider belongs at the
consumed `lunco-terrain-bake` boundary.

## Inspect and test

Use `list_hooks()` to inspect the reflected declaration. It reports
`parameters: [{name, type}]`, `output`, ownership, policy binding, determinism,
requirement, and installation state. Use `policy_status()` for startup/Twin
load diagnostics and the last typed Twin lifecycle result. The owner must
consume every non-`Unit` result; the lifecycle dispatcher retains its returned
map and exact invocation context in that status surface. Twin lifecycle calls
use a `Twin/Lifecycle` route whose generation is the mounted Twin's nonzero
`TwinId`; startup/reload, asset events, and teardown use `Start`, `Event`, and
`Stop` phases with no elapsed clock. The `assets_mounted` lifecycle event receives the
parsed Twin manifest, indexed relative paths, exact `twin://` authority, and
active-Twin fact. It also receives `scene_override` and `scene_loading` with
the admitted `load_default` value and scope `source`. An explicit override
must be opened exactly once; when automatic loading is disabled the policy
must not select the manifest default. Its ordered `{command, params}` actions go through the generic
typed command bridge; Rhai chooses loaders and order, while each domain owner
validates paths and performs asynchronous work. A malformed plan faults and
queues no commands; a rejected command is reported while later actions
continue. `invoke_hook(id, [args])` distinguishes unavailable hooks from
installed functions that fault.

Keep helper arguments proportional to what the helper reads. A policy may
receive rich nested facts, but scalar/status helpers should receive the needed
fields rather than repeatedly passing the complete map. This preserves the
public hook ABI while avoiding unnecessary Rhai value copies. Measure policy
evaluation separately from fact construction and verify the real owner output.

Scheduled owner calls supply an immutable `runtime_context` map with their
route, cycle, phase, clock, and logical sequence. If a policy is valid only in
one cycle, reject other contexts and verify the real scheduled owner path in
an authored production test. For example, `readiness.action` runs under
`Core/Simulation/Behavior` with fixed-clock time and the latest `SimTick`; its
policy rejects direct calls from other cycles.
Physics initialization is a discrete lifecycle decision: use the required
`physics.initialization(facts)` seam, a generation-qualified
`Twin/Lifecycle/Preparation` route, and no clock sample. Its stable facts include
the selector, validation status, pose, assembly size, and measured penetration
when present. `accept` admits the authored pose unchanged, `pause` disables the
validated penetrating assembly and removes it from scene readiness, and
`reject` keeps it held. The shipped Application policy pauses measured terrain
penetrations and remains installed across Twin reloads; a mounted Twin may
replace it. Keep authored selector names in `facts.policy`; do not construct
dynamic hook ids or expose process-local ECS entity ids as deterministic policy
facts.

The application `twin.lifecycle` policy selects the active Twin's explicit or
enabled default USD scene, tool libraries, timeline data, SysML/KerML sources, and Modelica roots
from its typed manifest and indexed file inventory. Loader commands keep only
generic ownership, safe-path, asset-read, and domain-registration mechanics.
An ephemeral workspace uses the application policy only for explicit scene
selection; it has no Twin policy overrides, tools, timelines, or source sets.

For application UI contributions, reuse the optional
`application.asset.lifecycle(event, ctx)` hook. The shared asset layer emits
JSON-scope loading/changed events after asynchronous reads, including the
canonical `asset_root_uri` and each JSON record's typed `persisted_result` fact.
Completed-history records carry identity only, with unit `text` and `error`.
The application menu policy skips those records before parsing;
keep that selection in Rhai and the storage classification at the asset/Twin
owner. Eligible authored records use `parse_json(text)` and return a generic
`menus` tree. Scene completion is also delivered with the canonical loaded `path` and `root_prim`; return selected declared
dataset ids in `dataset_text_artifacts` when the scene needs their text. The
Rust host validates the complete action map, while `DatasetArtifactPlugin`
resolves each registry id to its canonical asset URI and reads through the
shared `TextAsset` loader. Missing or unreadable requested datasets are
reported; unrequested datasets remain quiet. `SceneTransitionStarted` retires pending reads. Keep
asset selection and menu policy in Rhai; Rust owns typed lifecycle facts, safe
asset delivery, action-shape validation, rendering, and provider cleanup.

Put policy and observable runtime assertions in an authored Rhai production
scene test. Cover the declared signature, successful binding/invocation,
missing-policy status, rejected deterministic inline binding, and exact
unbinding. Keep Rust coverage to the low-level `HookValue` conversion and
registry mechanics; do not embed long USD or load Twin assets in Rust tests.

The primary USD scene lifecycle also owns required deterministic
`usd.scene_composition(facts: Map) -> Map` for incomplete composition closures.
Its facts contain the scene address and ordered unresolved arcs. The shipped
application policy returns `#{action: "allow_partial"}` to preserve the
existing partial-load behavior; a Twin may replace it with `reject_scene`.
The owner invokes it after structural projection but before releasing the
simulation hold. Rejection tears down the partial primary scene, and missing,
faulting, or malformed policy results fail admission visibly. Keep the loader's
missing-arc warning and the policy's admission decision as separate owner
responsibilities.

## Handoff

Report the owner-side declaration, manifest/source files, reflected signature,
failure semantics, focused checks, and the production Rhai test evidence.

## Scene avatar availability

`lunco-camera-core` declares `camera.scene_avatar(ctx: Map) -> Map` independently
of camera selection. The windowed camera owner calls it in
Application/Presentation/Preparation on scene/projection/policy changes. The
application policy returns `create: bool` and, for creation, `bindings` containing
`[intent, port, f64 factor]` rows. Rust validates the shared control vocabulary,
installs the scene-owned transient rig, and reports invalid results through the
camera contract. The rig has no USD prim identity and does not enter saved
layers. Keep director/operator selection independent of avatar availability;
reuse an authored avatar and retire transient rigs at scene teardown.

Verify both avatar-free and authored-avatar cases with
[`scene_avatar_presence.rhai`](../../assets/scenarios/tests/scene_avatar_presence.rhai)
in an owned windowed production session, supplying its exact `doc_id` and
`authored_avatar_path` (unit for a transient avatar). The scenario saves an
ignored artifact and compares all document layers. The production
[`test_hook_policies.rhai`](../../assets/scripting/tests/test_hook_policies.rhai)
covers declaration and off-cycle rejection.

### Live camera presentation

`camera.follow(ctx)` is a per-presentation-frame, optional camera-core seam.
Use its typed rig/subject/obstruction facts for vessel-specific framing and easing.
The native adapter validates decisions and commits collision-constrained poses;
it holds the camera and reports `camera-follow` on an invalid callback result.
Use a Twin-scoped operator tool (`RunRhaiToolHook`) to replace a Twin policy;
an application-scoped REPL cannot replace its ownership layer. Policy updates
must not reload the scene or advance held physics. Full contract and acceptance
boundaries: [camera follow policy](../../docs/architecture/camera-follow-policy.md).

## Task perspectives

Use `workbench.perspectives.twin(facts)` for custom layouts shipped with a Twin;
the application defaults use `workbench.perspectives.defaults`. Both return
arrays of typed semantic layout maps, consumed by the existing dock owner.
Discover exact panel and instance capabilities with `InspectWorkbench` and read
[the perspective tutorial](../../docs/tutorials/05-twin-perspectives.md).
Evaluation is revision-driven Visualization/Preparation work over immutable
facts; a policy reload does not reset a visited layout. Verify positive and
rejected plans, explicit reset, and Twin replacement through the production app.

## Recipe-local asset planning

For `Assets.toml` processing customization, use the recipe-local
`assets.process.plan` contract documented in
[artifact processing](../../docs/architecture/asset-processing.md). The recipe
selects a declared, hashed Rhai file and entry. The asset owner invokes the
shared `RhaiHook` interpreter with immutable `plan`, `settings`, input hashes
and processor facts, validates the returned plan and consumes it on its worker.
This non-installable binding lives for one preparation attempt and has no
live-World access or simulation clock. It does not install an application/Twin
policy layer. Keep heavy processing in native operations, WESL kernels,
Modelica or an explicit external stage. Cover code-change invalidation and
failure without replacement in the production artifact gate.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in business →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.