@quality-sh/provenance
v0.4.0
Published
Typed traceability declarations backed by the Provenance Rust engine
Maintainers
Readme
@quality-sh/provenance TypeScript SDK
This package is an optional typed façade over the Provenance Rust engine. It does not implement graph semantics or persistence in JavaScript.
npx --yes @quality-sh/create-provenanceThe initializer detects npm, pnpm, Yarn, Bun, Deno, or Nub. It adds this SDK as
an exact development dependency, installs the engine for the current platform,
writes .provenance/state/, and confirms that npx provenance check reports
ok.
SDK connection
SDK operations require an explicitly configured HTTP host. The local CLI remains available through the package bin shim; SDK calls do not discover or start it.
import { configure } from "@quality-sh/provenance";
configure({
endpoint: process.env.PROVENANCE_ENDPOINT,
bearer: process.env.PROVENANCE_TOKEN,
repositoryId: process.env.PROVENANCE_REPOSITORY_ID,
localRoot: process.env.PROVENANCE_LOCAL_ROOT,
scope: "default",
});The repository ID is an opaque host target. localRoot describes the caller's
checkout, so inferred implementation and test paths become portable relative
paths before transmission. It does not select the host repository. Legacy
engine and repository settings are rejected; PROVENANCE_REPO is not an
HTTP target. Host deployment and access setup must be supplied separately.
Browser callers can import the named HttpClient and error classes from
@quality-sh/provenance/client. That subpath has no Node or subprocess imports.
Both clients validate responses against generated contracts and bound them to
16 MiB. OperationError carries a validated declared failure; ConnectionError
and MalformedResponseError identify transport or contract failures. A write
returns success or one of these typed errors. The clients keep no uncertain
write ledger. They never retry mutations or replay redirects automatically.
Consumer CI
Install the locked project dependencies before each check. Use npx --no in
CI. This command invokes only the provenance executable installed in the
project. It does not approve a registry installation for a missing executable.
npm ci
npx --no provenance check --repo . --strict --base "$BASE_SHA" --format jsonThe check runs the graph, statement, and Rule binding checks. With --strict,
every binding finding also fails the check.
Set BASE_SHA to the target branch commit for a pull request. If --base is
not present, strict statement checking compares Git HEAD with its first parent.
It uses an empty base for an initial commit. The statement check prints its
complete ASD-STE100 report before it exits nonzero for a finding.
Configure the CI checkout to include BASE_SHA. If the command uses the
default first parent, the checkout must include that parent. A depth-one
checkout is not sufficient for a commit that has a parent.
The coverage command is a separate policy gate. Its --strict option rejects
Rule binding and coverage warnings. It does not check Requirement or Rule
prose. Keep --path . when CI must detect missing bindings across the complete
repository.
Runtime Rule bindings
The same install supplies inert helpers that put Rule IDs next to production
implementations and tests. Import these helpers from the rules subpath:
import { rule, verifies } from "@quality-sh/provenance/rules";
export const paysOvertime = rule("rule_overtime", (hours: number) =>
hours > 38,
);
test("hours above 38 attract overtime", function overtimeExamples() {
verifies("rule_overtime", "examples");
expect(paysOvertime(39)).toBe(true);
});rule returns the exact function. verifies returns nothing. Neither helper
registers state or changes application behavior. The scanner reads both calls
and creates the Implementation binding and Verification binding. Keep
rule("id", on one line. Put verifies("id", "method") in a named function or
in a function-valued const.
The top-level rule("local-key") export remains the Rule declaration builder.
The rules subpath keeps the scanner helpers separate from that authoring
interface.
Define a spec without touching the engine:
import { defineSpec, requirement, rule, source } from "@quality-sh/provenance";
import { createShareLink } from "./share-links.js";
export const shareLinks = defineSpec("share-links")
.requirements(
requirement("sharing")
.statement("Users can securely share documentation")
.from(source("sharing-policy").document("docs/sharing-policy.md"))
.rules(
rule("expiry")
.statement("Share links must expire within 30 days")
.implementedBy(createShareLink),
),
)
.build();Each fluent call returns a new immutable declaration. build() validates and
finalizes the desired-state document and collects Sources linked with
Requirement.from(...); they do not need to be repeated in .sources(...).
Construction is synchronous and in-memory: importing this module does not write
state or start a process. build() returns the frozen, typed objects that tests
import. Rust remains responsible for reconciling them.
Sources can add a display name with .name(...); Requirements can add more
context with .description(...).
Compatibility helpers
Existing code that uses spec-scoped factories can keep declarations in typed helpers, including helpers in other files:
import type {
RequirementDeclaration,
RuleDeclaration,
SpecAuthoring,
} from "@quality-sh/provenance";
export function expiryRule<
const Spec extends string,
const RequirementKey extends string,
>(
requirement: RequirementDeclaration<Spec, RequirementKey>,
): RuleDeclaration<Spec, "expiry", RequirementKey> {
return requirement.rule("expiry").statement("Share links expire");
}
export function sharing<const Spec extends string>(author: SpecAuthoring<Spec>) {
return author.requirement("sharing").statement("Shares expire");
}SourceDeclaration, RequirementDeclaration, and RuleDeclaration describe
immutable declarations before build(). Their literal spec and Requirement
parameters stop helpers from mixing declarations from different specs.
In this compatibility API, a Rule created through a Requirement belongs to that Requirement. Equal local keys under different Requirements remain distinct. A Rule created through the spec context can be shared:
export const authenticatedExpiry = provenance
.rule("authenticated-expiry")
.statement("Authenticated access expires");
const shares = provenance
.requirement("shares")
.statement("Shares expire")
.rules(authenticatedExpiry);
const sessions = provenance
.requirement("sessions")
.statement("Sessions expire")
.rules(authenticatedExpiry);
export default provenance.build(shares, sessions);This emits one Rule with two relationships. Shared versus local identity is
chosen by where the Rule is declared, not inferred from JavaScript object
reuse. Sources linked with .from(...) are collected transitively by build().
A spec cannot set a Rule status. Apply creates each new spec Rule as draft.
To make the Rule active, a person changes its status with
provenance <id> update --status active --declared-by <owner> --if-match <etag>,
where <owner> is the declaration owner from PROVENANCE_SPEC_OWNER. A later
apply keeps that status. A new key or a move to a different Requirement gives a
new draft Rule, and apply deletes the old Rule. A move between a Requirement
and the spec context keeps the Rule and its status when apply finds one
existing Rule.
implementedBy() accepts an exported function or class through a direct named
import or a non-computed namespace member. The SDK reads that expression from
the spec source and records the imported module and exported symbol; the runtime
value exists only for TypeScript assignability. It never inspects a function or
class name, body, prototype, or object identity, and it never constructs a class.
Calls, conditionals, computed members, instance methods, anonymous closures,
constructed values, and local functions fail clearly because they do not provide
one durable source identity. Rust checks that the resolved file belongs to the
repository and owns the canonical implementation binding. Production code does
not import the authoring interface to create this link.
Moving a local Rule to a shared declaration, or back, preserves its canonical
ID when Rust finds exactly one owned candidate. If several local Rules could
become the shared Rule, apply fails instead of guessing. An immutable
.id(existingId) call can choose the canonical record. Other declarations
omitted from that complete spec are deleted. Git preserves their history.
Adopt existing unowned declarations
Use Declaration adoption only for a migration from existing canonical state. The method requires one explicit Stable ID and adds one exact wire target:
const policy = source("policy")
.adoptUnowned("source_policy")
.document("docs/policy.md");
export const migration = defineSpec("existing-requirements")
.requirements(
requirement("sharing")
.adoptUnowned("req_sharing")
.statement("Users can securely share documentation")
.from(policy),
)
.build();
const preview = await plan(migration);
if (preview.conflicts !== 0) throw new Error("Declaration adoption conflicts");
await apply(migration);An existing record that is not a document keeps its source type only when the
declaration states that type. Use .kind("external_integration") in place of
.document(...). kind gives no locator, so the canonical URL and reference
stay as they are. document(reference) is the short form of kind("document")
that also gives the reference.
SourceDeclaration, RequirementDeclaration, and RuleDeclaration provide
the same immutable adoptUnowned(existingId) method. Use .id(existingId)
when identity must be explicit but adoption is not requested.
Plan must show no create and no conflict for a valid adoption. Apply keeps the
Stable ID and definition and adds only the Declaration owner and Declaration
address. Richer canonical metadata outside the typed declaration surface is
preserved and does not block adoption. The same request then plans as unchanged.
After adoption, replace adoptUnowned(existingId) with id(existingId) before
a later definition change.
Adoption refuses a missing declaration, an implicit or different ID, a duplicate target, a nonexistent record, a definition or relationship change, and a record owned by another declaration. One refusal makes the complete apply a no-op. A document with no adoption request keeps the default ownership conflict behavior.
Materialize only this spec at a deliberate entry point:
import { apply, plan } from "@quality-sh/provenance";
import { shareLinks } from "./provenance.spec.js";
await apply(shareLinks);Preview the same reconciliation without writing canonical state:
const proposed = await plan(shareLinks);Updated resources include field-level before and after values. Affected
Rules also list the implementation and verification sites that may need
review. Provenance computes both plan and apply through the same Rust
reconciliation path.
Each affected Rule carries an evidence object saying whether its evidence is
review_required, and why. Rewording a Requirement statement puts every Rule
it produces up for review, because the obligation those tests vouch for is no
longer the one that was written down. Each reason names the Requirement, the
field, and its value before and after, so a reviewer can see the wording change
that prompted it. Reasons for a change already applied also carry changed_at.
Review required is not the same as stale. Stale means the code holding the
evidence changed and is reported by provenance stale. A Requirement wording
change never claims anything about the code. Running the tests for a Rule again
clears its review automatically; the recorded reason stays as history. Ask for
--format markdown to read the same explanation as prose.
The result classifies each declaration as created, updated, moved,
deleted, conflict, or unchanged. Omission deletes only records owned by
that same spec. Git preserves their prior versions. Adding the declaration back
creates a new record with the same deterministic ID. A Rule move
replaces its active owned Requirement edge. Plan returns ownership conflicts as
data; apply refuses them. Hard deletion and ownership transfer are separate and
are not part of this API.
Ask the engine what a change reaches before making it:
import { evidence, impact, neighbors, trace } from "@quality-sh/provenance";
const reached = await impact({ id: sharing.id });
const behind = await evidence({ rule: expiry.id, base: "origin/main" });impact answers the Rules a Source or Requirement reaches, each with the
implementation and verification sites behind it. evidence answers one Rule's
implementation_bindings, verification_bindings, verification_runs,
latest_verification_run, review_required with the reviews that raised it,
and stale. Stale is read from a diff, so stale is null unless the request
names a base commit.
get, search, neighbors, trace, and resolveSymbol answer the rest:
one record by id, records whose text contains a phrase, the records one edge
away, a bounded walk outward, and the Rules bound to a code site. stale
answers the evidence sites a commit range disturbed.
import { get, resolveSymbol, search, stale } from "@quality-sh/provenance";
const around = await neighbors({ id: expiry.id, direction: "in" });
const walked = await trace({ id: retention.id, direction: "out", max_depth: 2 });Every answer uses {data,meta}. Lists place records in data.items. Bounded
reads take limit, 50 by default and 200 at most, and report paging fields in
meta. These functions send their request to the engine and return its answer
unchanged: walking, filtering, and paging all happen in Rust.
Removing .implementedBy(...) from an active Rule deletes that
spec's canonical implementation binding. Plan reports the Rule as updated with
the old implementation and null as its field-level before/after values. Adding
the link back recreates the same binding ID, while changing the imported
symbol updates it in place. Git preserves deleted bindings. A deleted binding does not make the Rule appear implemented.
A test imports the actual rule handle and runs its callback:
import { shareLinks } from "./provenance.spec.js";
await shareLinks.requirements.sharing.rules.expiry.verify(
"share-link-expiry",
async () => {
// Exercise ordinary production code with the test runner of your choice.
},
import.meta,
);Every verification binding names the file the test runs in. Node and Deno report
the calling file, so the third argument is optional there. Bun does not always
report it: JavaScriptCore takes proper tail calls, so a test written as
test("...", () => rule.verify(key, callback)) leaves the SDK a stack of SDK
frames and nothing else. Passing import.meta states the file on every runtime.
{ file: import.meta.url } says the same thing and leaves room for method and
symbol; under Bun { file: import.meta.path } also works. A call that can
name no file fails before the callback runs and says what to add.
Pointing an owner-local verification key at a different Rule from the same
test file deletes the binding that key previously named. Calling it again
recreates the same binding ID, and moving the key to another file updates it
in place. Git preserves deleted bindings. A deleted binding does not make the Rule appear verified. Because one run only sees the call sites it ran,
nothing else is deleted, and a binding whose test file disappeared is reported
by provenance stale instead.
The handle keeps an owner-local declaration address, not a mutable database
ID. Rust resolves that address to the canonical Rule when verification begins.
Calling verify before applying the spec fails before the callback runs. A
failed callback is recorded and the original error is rethrown.
The package installs a matching Rust engine through a platform-specific optional dependency. It does not download a binary from an install script, compile Rust, or require a global CLI. This binary is used by explicit CLI commands. SDK operations instead check their configured HTTP host protocol.
This package owns the provenance command and forwards it to that engine
unchanged, so npx provenance runs what the install supplied. When the platform
package is absent, after npm install --omit=optional or on a host with no
published engine, the command names the missing package and the supported
targets rather than reaching the registry for a command of the same name.
Published targets follow the release target inventory. An unsupported host
fails with the supported target list. PROVENANCE_BIN selects a development
binary for the CLI shim. SDK environment settings are:
PROVENANCE_ENDPOINT: explicit HTTP host URLPROVENANCE_TOKEN: bearer credentialPROVENANCE_REPOSITORY_ID: opaque host repository IDPROVENANCE_LOCAL_ROOT: caller checkout root for portable file pathsPROVENANCE_SCOPE: scope; defaultdefaultPROVENANCE_SPEC_OWNER: declaration owner; defaultspec://typescriptPROVENANCE_VERIFICATION_OWNER: evidence producer; defaultci://typescript
configure() provides the SDK settings in code. The SDK keeps HTTP connections
and never starts a subprocess for an operation.
Spec-scoped declaration factories, object-options declarations, and the
callback form of defineSpec() remain available as compatibility surfaces. The
older object-options API uses a process-local registry and verify() applies
pending declarations automatically. New code should prefer the nested fluent
form above plus explicit apply(spec) so imports stay free of hidden
persistence.
See examples/typescript-sdk/ for package-name consumption through a local npm
dependency.
Build from a source checkout
Generated operation source and the platform lookup module are not tracked in Git. Install the generator dependencies once, then build the SDK:
npm ci --prefix tools/operation-codegen
npm ci --prefix packages/provenance
npm run build --prefix packages/provenanceRun these commands from the repository root. The first source build also needs the repository's Rust toolchain to export the operation contract. Later builds reuse generated output only when its source fingerprint and output checksums match. CI supplies this output as a build artifact to npm-only jobs.
Published npm packages contain compiled clients and validators. Installing or using a published package does not run the generator or require Rust or a host server toolchain. The explicit CLI remains a separate packaged executable.
Effect HTTP calls
The @quality-sh/provenance/effect entry supplies generated Effect operations,
runtime wire schemas, and ProvenanceApi. Applications install the exact peer
[email protected]. The existing Promise client requires no Effect setup.
Use an explicitly connected EffectHttpClient through ProvenanceClient with
Atom.runtime to preserve the shared client policy. Keep the client while
mutation outcomes remain unresolved. See the
Effect SDK guide
for examples and the integration handoff.
