{"version":3,"sources":["../src/stats/hash.ts","../src/audit/chain.ts","../src/errors.ts","../src/capability/match.ts","../src/identity/fingerprint.ts","../src/lifecycle/transitions.ts","../src/state/memory.ts","../src/core/createKrikos.ts","../src/state/file.ts","../src/state/kv.ts"],"names":["snapshot","activate","verifyAuditChain"],"mappings":";;;AAuBA,IAAM,gBAAA,GAAmB,mBAAA;AACzB,IAAM,SAAA,GAAY,cAAA;AAClB,IAAM,OAAA,GAAU,mBAAA;AAOhB,IAAM,aAAA,GAAgB,GAAA;AAStB,SAAS,aAAa,IAAA,EAAsB;AAC1C,EAAA,IAAI,IAAA,GAAO,gBAAA;AACX,EAAA,KAAA,IAAS,QAAQ,CAAA,EAAG,KAAA,GAAQ,IAAA,CAAK,MAAA,EAAQ,SAAS,CAAA,EAAG;AACnD,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,UAAA,CAAW,KAAK,CAAA;AAClC,IAAA,IAAA,IAAQ,MAAA,CAAO,OAAO,GAAI,CAAA;AAC1B,IAAA,IAAA,GAAQ,OAAO,SAAA,GAAa,OAAA;AAC5B,IAAA,IAAA,IAAQ,MAAA,CAAO,SAAS,CAAC,CAAA;AACzB,IAAA,IAAA,GAAQ,OAAO,SAAA,GAAa,OAAA;AAAA,EAC9B;AACA,EAAA,OAAO,IAAA;AACT;AAqBO,SAAS,QAAQ,IAAA,EAAsB;AAC5C,EAAA,OAAO,YAAA,CAAa,IAAI,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,IAAI,GAAG,CAAA;AACzD;AAgBO,SAAS,YAAY,KAAA,EAAkC;AAC5D,EAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,IAAA,CAAK,aAAa,CAAC,CAAA;AAC1C;AAmBO,SAAS,OAAA,CAAQ,eAAuB,IAAA,EAAsB;AACnE,EAAA,OAAO,YAAA,CAAa,CAAA,EAAG,IAAI,CAAA,EAAG,aAAa,CAAA,EAAG,MAAA,CAAO,aAAa,CAAC,CAAA,C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Q,GAAI,MAAM,OAAO,WAAW,CAAA;AAC5C,MAAA,MAAM,EAAA,CAAG,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAEjD,MAAA,YAAA,IAAgB,CAAA;AAChB,MAAA,MAAM,UAAU,CAAA,EAAG,IAAI,IAAI,OAAA,CAAQ,GAAG,IAAI,YAAY,CAAA,IAAA,CAAA;AACtD,MAAA,MAAM,GAAG,SAAA,CAAU,OAAA,EAAS,KAAK,SAAA,CAAU,QAAQ,GAAG,MAAM,CAAA;AAC5D,MAAA,MAAM,EAAA,CAAG,MAAA,CAAO,OAAA,EAAS,IAAI,CAAA;AAAA,IAC/B;AAAA,GACF;AACF;;;AC5FO,SAAS,OAAA,CAAQ,EAAA,EAAY,GAAA,GAAM,cAAA,EAA8B;AACtE,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,GAA2C;AAC/C,MAAA,MAAM,GAAA,GAAM,MAAM,EAAA,CAAG,GAAA,CAAI,GAAG,CAAA;AAC5B,MAAA,IAAI,GAAA,KAAQ,MAAA,IAAa,GAAA,KAAQ,IAAA,EAAM;AACrC,QAAA,OAAO,MAAA;AAAA,MACT;AACA,MAAA,OAAO,aAAA,CAAc,GAAA,EAAK,CAAA,QAAA,EAAW,GAAG,CAAA,CAAA,CAAG,CAAA;AAAA,IAC7C,CAAA;AAAA,IACA,MAAM,KAAK,QAAA,EAAwC;AACjD,MAAA,MAAM,GAAG,GAAA,CAAI,GAAA,EAAK,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAC,CAAA;AAAA,IAC5C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Deterministic, non-cryptographic hashing primitives for Krikos: agent fingerprints (the\n * content identity of an agent at a credential epoch), audit-chain digests, and seeded short\n * identifiers.\n *\n * Everything here is pure, allocation-light, dependency-free, and runs identically in browsers,\n * edge runtimes, workers, and Node. No randomness, no clock, no platform globals, so two\n * processes that canonicalize byte-identical agents derive byte-identical fingerprints.\n *\n * Security stance: FNV-1a is NOT a cryptographic hash. It is trivially invertible and\n * collision-constructible by an adversary, so values produced by this module must never gate a\n * security decision on their own (authentication, authorization, integrity verification). They\n * exist to give byte-equal inputs equal keys for agent identity, deduplication, and\n * tamper-evident audit bookkeeping. Cryptographic agent identity is a separate, opt-in layer:\n * the Ed25519 signer in `@takk/krikos/a2a`, which signs the fingerprint produced here.\n *\n * @packageDocumentation\n */\n\n/**\n * FNV-1a 64-bit offset basis and prime, per the reference parameters published by Fowler,\n * Noll, and Vo (http://www.isthe.com/chongo/tech/comp/fnv/, retrieved June 2026).\n */\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\n/**\n * Joins key parts with the ASCII unit separator (U+001F). Hex output is confined to `[0-9a-f]`,\n * so the separator can never occur inside a hash and joined keys cannot collide by\n * concatenation ambiguity (\"ab\" + \"c\" versus \"a\" + \"bc\").\n */\nconst KEY_SEPARATOR = '\u001f';\n\n/**\n * Core FNV-1a 64-bit loop over the UTF-16 code units of `text`, two bytes per unit, low byte\n * first. Hashing code units directly, instead of UTF-8 bytes, keeps the function free of any\n * encoder dependency and free of per-call allocations, at the cost of producing digests that\n * differ from byte-wise UTF-8 FNV implementations. That is fine: these digests are compared\n * only against other digests produced by this same function.\n */\nfunction fnv1a64Value(text: string): bigint {\n  let hash = FNV_OFFSET_BASIS;\n  for (let index = 0; index < text.length; index += 1) {\n    const unit = text.charCodeAt(index);\n    hash ^= BigInt(unit & 0xff);\n    hash = (hash * FNV_PRIME) & MASK_64;\n    hash ^= BigInt(unit >>> 8);\n    hash = (hash * FNV_PRIME) & MASK_64;\n  }\n  return hash;\n}\n\n/**\n * Hashes `text` with FNV-1a 64-bit over its UTF-16 code units (two bytes per code unit, low\n * byte first) and returns the digest as a fixed-width 16-character lowercase hex string.\n *\n * Determinism: pure function of the input, identical across runtimes and runs.\n *\n * Collision odds, non-adversarial inputs: with a 64-bit digest the birthday bound puts the\n * probability of any collision among n distinct inputs at roughly n^2 / 2^65, about 1 in 37\n * million for one million distinct agents, reaching 50 percent only near 5 billion inputs.\n * Acceptable for fingerprint bookkeeping, where a collision costs at worst one misattributed\n * deduplication, never a wrong authorization decision (authorization keys off the agent id and\n * lifecycle state, not the fingerprint).\n *\n * Non-cryptographic: an adversary can construct collisions at will. Never use the result alone\n * for security decisions, see the module-level security stance.\n *\n * @param text - The string to hash, hashed as-is with no normalization.\n * @returns 16 lowercase hex characters, zero-padded, for example '0a1b2c3d4e5f6789'.\n */\nexport function fnv1a64(text: string): string {\n  return fnv1a64Value(text).toString(16).padStart(16, '0');\n}\n\n/**\n * Derives one key from several parts by joining them with a separator that cannot appear in hex\n * output (U+001F) and hashing the joined string with {@link fnv1a64}.\n *\n * The separator guarantees that part boundaries contribute to the digest, so\n * `combineKeys(['ab', 'c'])` and `combineKeys(['a', 'bc'])` differ even though their\n * concatenations are equal. Krikos uses it to fuse an agent's identity-defining fields into a\n * stable fingerprint and to chain audit events into a tamper-evident log.\n *\n * Same non-cryptographic caveats and collision odds as {@link fnv1a64}.\n *\n * @param parts - Key components in significance order, empty parts are preserved.\n * @returns 16 lowercase hex characters identifying the part sequence.\n */\nexport function combineKeys(parts: readonly string[]): string {\n  return fnv1a64(parts.join(KEY_SEPARATOR));\n}\n\n/**\n * Produces a deterministic short identifier from a seeded counter and a salt: the FNV-1a 64-bit\n * digest of `salt`, the separator, and the counter rendered in decimal, encoded in base36. Same\n * counter and salt always yield the same id, which is how Krikos keeps agent ids reproducible\n * without ever calling the global random generator.\n *\n * Output is 1 to 13 lowercase base36 characters (a 64-bit value needs at most 13 digits in\n * base36), typically 13.\n *\n * Non-cryptographic and predictable by design: anyone knowing the salt and counter can recompute\n * the id. Never use it as a secret, a session token, or any security-relevant value. Collision\n * odds follow {@link fnv1a64}.\n *\n * @param seededCounter - Monotonic counter from the registry's seeded id generator.\n * @param salt - Stable namespace string, for example the registry seed rendered as text.\n * @returns Deterministic base36 identifier, for example '2kgal12c8744o'.\n */\nexport function shortId(seededCounter: number, salt: string): string {\n  return fnv1a64Value(`${salt}${KEY_SEPARATOR}${String(seededCounter)}`).toString(36);\n}\n","/**\n * Hash-chained audit trail primitives for Krikos.\n *\n * Every lifecycle operation appends one {@link AuditEvent}. Each event's `hash` folds the\n * previous event's `hash` together with this event's own fields, so the chain is tamper-evident:\n * altering any earlier event changes its `hash`, which breaks the `prevHash` link of the next\n * event, and so on to the head. {@link verifyAuditChain} walks the chain and reports whether it\n * is intact.\n *\n * This is integrity bookkeeping with a non-cryptographic digest (FNV-1a), strong enough to catch\n * accidental corruption and naive edits, not strong enough to resist a determined adversary who\n * can recompute the whole tail. A host that needs cryptographic non-repudiation signs the\n * snapshot or individual events with the Ed25519 signer. The events are also frozen with\n * `Object.freeze` on creation and on load, so a caller holding a reference cannot mutate history\n * in place.\n *\n * @packageDocumentation\n */\n\nimport { combineKeys } from '../stats/hash.js';\nimport type { AgentId, AuditEvent, AuditKind } from '../types.js';\n\n/** The prevHash of the first event: a fixed 16-zero sentinel, never a real digest. */\nexport const GENESIS_HASH = '0000000000000000';\n\n/** The fields that define one event's content, before its own hash is folded in. */\nexport interface AuditEventInput {\n  /** Monotonic sequence number, starting at 1. */\n  readonly sequence: number;\n  /** Transaction instant (epoch ms). */\n  readonly at: number;\n  /** What happened. */\n  readonly kind: AuditKind;\n  /** The agent the event concerns. */\n  readonly agentId: AgentId;\n  /** Who performed the operation. */\n  readonly actor: string;\n  /** Human-readable detail. */\n  readonly detail: string;\n}\n\n/**\n * Computes the digest of one event chained onto `prevHash`. Pure and deterministic: the same\n * inputs always yield the same digest, across runs and runtimes.\n *\n * @param input - The event content.\n * @param prevHash - The preceding event's hash, or {@link GENESIS_HASH} for the first event.\n * @returns A 16-character lowercase hex digest.\n */\nexport function hashEvent(input: AuditEventInput, prevHash: string): string {\n  return combineKeys([\n    prevHash,\n    String(input.sequence),\n    String(input.at),\n    input.kind,\n    input.agentId,\n    input.actor,\n    input.detail,\n  ]);\n}\n\n/**\n * Builds the next frozen audit event from its content and the current chain head.\n *\n * @param input - The event content.\n * @param prevHash - The current head hash, or {@link GENESIS_HASH} when the trail is empty.\n * @returns A frozen {@link AuditEvent}.\n */\nexport function makeEvent(input: AuditEventInput, prevHash: string): AuditEvent {\n  const hash = hashEvent(input, prevHash);\n  return Object.freeze({\n    sequence: input.sequence,\n    at: input.at,\n    kind: input.kind,\n    agentId: input.agentId,\n    actor: input.actor,\n    detail: input.detail,\n    prevHash,\n    hash,\n  });\n}\n\n/**\n * Walks an audit trail and verifies the hash chain: each event's `prevHash` must equal the prior\n * event's `hash` (the first must be {@link GENESIS_HASH}), and each event's `hash` must equal the\n * recomputed digest of its content. An empty trail is trivially intact.\n *\n * @param events - The audit trail in sequence order.\n * @returns Whether the chain is intact.\n */\nexport function verifyAuditChain(events: readonly AuditEvent[]): boolean {\n  let prevHash = GENESIS_HASH;\n  for (const event of events) {\n    if (event.prevHash !== prevHash) {\n      return false;\n    }\n    const expected = hashEvent(event, prevHash);\n    if (event.hash !== expected) {\n      return false;\n    }\n    prevHash = event.hash;\n  }\n  return true;\n}\n","/**\n * Error model for Krikos, the identity registry and lifecycle manager for fleets of Massive\n * Intelligence (IM) agents and non-human entities (NHE).\n *\n * Krikos throws exactly one error class so that host applications can catch and branch on a\n * single type, then dispatch on the stable machine-readable {@link KrikosError.code}. New codes\n * may be added in minor versions, so consumers must treat the code space as open and fall back\n * gracefully on codes they do not recognize.\n *\n * @packageDocumentation\n */\n\n/**\n * The only error type thrown by Krikos.\n *\n * Invariants:\n * - `name` is always the literal string `'KrikosError'`, safe for cross-realm checks where\n *   `instanceof` fails (multiple bundles, workers, iframes).\n * - `code` is a stable, machine-readable, SCREAMING_SNAKE identifier prefixed with `ERR_`.\n *   It never changes meaning across versions, although new codes may appear in minors.\n * - `message` is human-readable English prose intended for logs, never for parsing.\n *\n * @example\n * ```ts\n * try {\n *   krikos.activate(id);\n * } catch (error) {\n *   if (error instanceof KrikosError && error.code === 'ERR_INVALID_TRANSITION') {\n *     // The agent cannot move to active from its current lifecycle state.\n *   }\n * }\n * ```\n */\nexport class KrikosError extends Error {\n  /**\n   * Stable machine-readable error code, for example `'ERR_INVALID_TRANSITION'`.\n   *\n   * Branch on this field, never on `message`. The code space is minor-extensible.\n   */\n  readonly code: string;\n\n  /**\n   * @param message - Human-readable description of what went wrong and how to fix it.\n   * @param code - Stable machine-readable code, see {@link KrikosError.code}.\n   */\n  constructor(message: string, code: string) {\n    super(message);\n    this.name = 'KrikosError';\n    this.code = code;\n  }\n\n  /**\n   * Builds a {@link KrikosError} with code `'ERR_INVALID_INPUT'`.\n   *\n   * Used for every caller-side contract violation: an agent with no name, an empty capability\n   * name, a non-finite expiration timestamp, a capability action that is not a string, and any\n   * other input the type system cannot reject for untyped JavaScript callers.\n   *\n   * @param message - Human-readable description of the invalid input.\n   * @returns A new error instance, never thrown by this factory itself.\n   */\n  static invalid(message: string): KrikosError {\n    return new KrikosError(message, 'ERR_INVALID_INPUT');\n  }\n\n  /**\n   * Builds a {@link KrikosError} with code `'ERR_NOT_FOUND'`.\n   *\n   * Used when a caller references an agent by id that the registry does not hold, for example\n   * activating an id that was never issued.\n   *\n   * @param message - Human-readable description of what was not found.\n   * @returns A new error instance, never thrown by this factory itself.\n   */\n  static notFound(message: string): KrikosError {\n    return new KrikosError(message, 'ERR_NOT_FOUND');\n  }\n\n  /**\n   * Builds a {@link KrikosError} with code `'ERR_INVALID_TRANSITION'`.\n   *\n   * Used when a lifecycle operation is requested from a state that does not allow it, for\n   * example resuming an agent that was revoked, or activating one that is archived. The\n   * registry stays consistent; the offending transition is rejected whole.\n   *\n   * @param message - Human-readable description of the illegal transition.\n   * @returns A new error instance, never thrown by this factory itself.\n   */\n  static transition(message: string): KrikosError {\n    return new KrikosError(message, 'ERR_INVALID_TRANSITION');\n  }\n\n  /**\n   * Builds a {@link KrikosError} with code `'ERR_CONFLICT'`.\n   *\n   * Used when an operation collides with existing state, for example issuing an agent with an\n   * explicit id that is already registered.\n   *\n   * @param message - Human-readable description of the conflict.\n   * @returns A new error instance, never thrown by this factory itself.\n   */\n  static conflict(message: string): KrikosError {\n    return new KrikosError(message, 'ERR_CONFLICT');\n  }\n\n  /**\n   * Builds a {@link KrikosError} with code `'ERR_LIMIT_REACHED'`.\n   *\n   * Used when an operation would exceed a configured bound, for example issuing past\n   * `maxAgents`. The registry stays consistent; the offending write is rejected whole.\n   *\n   * @param message - Human-readable description of the limit that was hit.\n   * @returns A new error instance, never thrown by this factory itself.\n   */\n  static limit(message: string): KrikosError {\n    return new KrikosError(message, 'ERR_LIMIT_REACHED');\n  }\n}\n","/**\n * Capability matching for Krikos: the pure predicate behind every authorization decision.\n *\n * A capability grants a set of actions, optionally scoped to a set of resource patterns. This\n * module decides whether a declared capability set admits a requested (capability, action,\n * resource) triple. It is the only place resource-pattern semantics live, so the rule is stated\n * once and shared by the engine, the Vercel tool guard, the MCP guard, and the edge verifier.\n *\n * Determinism: pure functions of their inputs, no clock, no randomness, no platform globals.\n *\n * @packageDocumentation\n */\n\nimport { KrikosError } from '../errors.js';\nimport type { Capability } from '../types.js';\n\n/**\n * Validates one capability's shape, throwing on a malformed declaration so a bad capability is\n * rejected at the boundary (issue, grant) rather than silently never matching.\n *\n * @param capability - The capability to validate.\n * @throws KrikosError `ERR_INVALID_INPUT` for an empty name, an empty actions list, a non-string\n *   action, or a non-string resource pattern.\n */\nexport function assertValidCapability(capability: Capability): void {\n  if (typeof capability.name !== 'string' || capability.name.length === 0) {\n    throw KrikosError.invalid('a capability requires a non-empty name.');\n  }\n  if (!Array.isArray(capability.actions) || capability.actions.length === 0) {\n    throw KrikosError.invalid(`capability '${capability.name}' requires at least one action.`);\n  }\n  for (const action of capability.actions) {\n    if (typeof action !== 'string' || action.length === 0) {\n      throw KrikosError.invalid(\n        `capability '${capability.name}' has a non-string or empty action.`,\n      );\n    }\n  }\n  if (capability.resources !== undefined) {\n    if (!Array.isArray(capability.resources)) {\n      throw KrikosError.invalid(`capability '${capability.name}' resources must be an array.`);\n    }\n    for (const resource of capability.resources) {\n      if (typeof resource !== 'string' || resource.length === 0) {\n        throw KrikosError.invalid(\n          `capability '${capability.name}' has a non-string or empty resource pattern.`,\n        );\n      }\n    }\n  }\n}\n\n/**\n * True when `pattern` admits `resource`.\n *\n * Pattern semantics, deliberately small and unsurprising:\n * - `*` alone matches any resource.\n * - A pattern ending in `*` is a prefix match: `/data/*` admits `/data/x` and `/data/`.\n * - Any other pattern is an exact match.\n *\n * No regex, no path normalization, no globbing beyond the trailing star, so the rule cannot\n * surprise an operator reasoning about what a capability grants.\n *\n * @param pattern - A resource pattern from a capability.\n * @param resource - The concrete resource being requested.\n * @returns Whether the pattern admits the resource.\n */\nexport function resourceMatches(pattern: string, resource: string): boolean {\n  if (pattern === '*') {\n    return true;\n  }\n  if (pattern.endsWith('*')) {\n    return resource.startsWith(pattern.slice(0, -1));\n  }\n  return pattern === resource;\n}\n\n/**\n * True when a single capability admits the requested action and resource.\n *\n * The capability must permit `action`. If `resource` is provided and the capability declares\n * `resources`, one of the patterns must admit it; a capability with no `resources` admits any\n * resource. If `resource` is omitted, resource scope is not checked.\n *\n * @param capability - The capability to test.\n * @param action - The requested action.\n * @param resource - The requested resource, or undefined to skip resource scoping.\n * @returns Whether this capability alone authorizes the request.\n */\nexport function capabilityAdmits(\n  capability: Capability,\n  action: string,\n  resource: string | undefined,\n  requireResourceScope = false,\n): boolean {\n  if (!capability.actions.includes(action)) {\n    return false;\n  }\n  if (resource === undefined) {\n    return true;\n  }\n  if (capability.resources === undefined) {\n    // An unscoped capability admits any resource by default. Under least-privilege enforcement\n    // (requireResourceScope), a request that names a resource must hit an explicitly scoped\n    // capability, so an unscoped one is denied for resource-bearing requests.\n    return !requireResourceScope;\n  }\n  return capability.resources.some((pattern) => resourceMatches(pattern, resource));\n}\n\n/**\n * True when a declared capability set authorizes the (capability name, action, resource) triple.\n *\n * Finds capabilities matching `name` and returns whether any one of them admits the action and\n * resource. This is the lexical half of authorization; the engine combines it with the agent's\n * lifecycle state to produce the final fail-closed decision.\n *\n * @param capabilities - The agent's declared capabilities.\n * @param name - The capability name requested.\n * @param action - The action requested.\n * @param resource - The resource requested, or undefined.\n * @param requireResourceScope - When true, a resource-bearing request is admitted only by a\n *   capability that declares explicit resource patterns; an unscoped capability is denied. Enforces\n *   least privilege.\n * @returns Whether the capability set admits the request.\n */\nexport function capabilitiesAuthorize(\n  capabilities: readonly Capability[],\n  name: string,\n  action: string,\n  resource: string | undefined,\n  requireResourceScope = false,\n): boolean {\n  return capabilities.some(\n    (capability) =>\n      capability.name === name &&\n      capabilityAdmits(capability, action, resource, requireResourceScope),\n  );\n}\n","/**\n * Deterministic agent fingerprinting and the canonical signable passport.\n *\n * The fingerprint is a stable content hash of an agent's identity-defining fields at a given\n * credential version. Two registries that canonicalize the same identity derive the same\n * fingerprint, which is what lets a signature produced anywhere be verified anywhere. The\n * canonical passport is the exact byte string a cryptographic signer signs, so signing and\n * verification never disagree about what was covered.\n *\n * Determinism: pure functions, no clock, no randomness, no platform globals. Capability order\n * and resource order are normalized by sorting, so a reordered-but-equal capability set yields\n * an identical fingerprint.\n *\n * @packageDocumentation\n */\n\nimport { combineKeys } from '../stats/hash.js';\nimport type { Agent, Capability, Issuer } from '../types.js';\n\n/**\n * Canonicalizes a capability set into a single stable string.\n *\n * Within each capability the actions and resources are sorted; the capabilities themselves are\n * sorted by name then by their canonical body, so set-equal capability lists in any order map to\n * the same canonical form. Field and element boundaries use control separators that cannot occur\n * in normal capability text, so distinct sets cannot collide by concatenation ambiguity.\n *\n * @param capabilities - The capabilities to canonicalize.\n * @returns A stable canonical string.\n */\nexport function canonicalCapabilities(capabilities: readonly Capability[]): string {\n  // ASCII control separators (record, field, element) that cannot occur in capability text, so\n  // distinct sets cannot collide by concatenation ambiguity. Written as escapes, never raw chars.\n  const RECORD = '\u001e';\n  const FIELD = '\u001f';\n  const ELEMENT = '\u001d';\n  const parts = capabilities.map((capability) => {\n    const actions = [...capability.actions].sort().join(ELEMENT);\n    const resources =\n      capability.resources === undefined ? '*' : [...capability.resources].sort().join(ELEMENT);\n    return `${capability.name}${FIELD}${actions}${FIELD}${resources}`;\n  });\n  return parts.sort().join(RECORD);\n}\n\n/**\n * Canonicalizes the issuer into a stable string. The optional name is included so two issuers\n * that share an id but differ in name produce different fingerprints.\n *\n * @param issuer - The issuer to canonicalize.\n * @returns A stable canonical string.\n */\nexport function canonicalIssuer(issuer: Issuer): string {\n  return `${issuer.id}${issuer.name ?? ''}`;\n}\n\n/**\n * Computes the deterministic fingerprint of an identity from its identity-defining fields: name,\n * issuer, canonical capabilities, and credential version. Lifecycle state, timestamps, and\n * metadata are deliberately excluded, so the fingerprint is the stable identity of the agent at\n * a credential epoch and changes only on rotation or a capability change.\n *\n * @param name - The agent name.\n * @param issuer - The issuing principal.\n * @param capabilities - The declared capabilities.\n * @param credentialVersion - The credential epoch.\n * @returns A 16-character lowercase hex fingerprint.\n */\nexport function computeFingerprint(\n  name: string,\n  issuer: Issuer,\n  capabilities: readonly Capability[],\n  credentialVersion: number,\n): string {\n  return combineKeys([\n    name,\n    canonicalIssuer(issuer),\n    canonicalCapabilities(capabilities),\n    String(credentialVersion),\n  ]);\n}\n\n/**\n * The claim set a cryptographic signer signs to bind an agent's identity. Plain data,\n * JSON-stable: serializing it always yields the same bytes for the same identity because every\n * field is canonical and the key order is fixed by {@link canonicalPassportString}.\n */\nexport interface AgentPassport {\n  /** Opaque agent id. */\n  readonly id: string;\n  /** Agent name. */\n  readonly name: string;\n  /** Canonical issuer string. */\n  readonly issuer: string;\n  /** Canonical capabilities string. */\n  readonly capabilities: string;\n  /** Credential epoch. */\n  readonly credentialVersion: number;\n  /** The identity fingerprint, redundant with the fields above but convenient for verifiers. */\n  readonly fingerprint: string;\n  /** Expiration instant (epoch ms) or null. */\n  readonly expiresAt: number | null;\n}\n\n/**\n * Builds the canonical passport for an agent. The passport is what the Ed25519 signer in\n * `@takk/krikos/a2a` signs; the verifier rebuilds the same passport from a presented agent and\n * checks the signature against it.\n *\n * @param agent - The agent to build a passport for.\n * @returns The canonical passport.\n */\nexport function buildPassport(agent: Agent): AgentPassport {\n  return {\n    id: agent.id,\n    name: agent.name,\n    issuer: canonicalIssuer(agent.issuer),\n    capabilities: canonicalCapabilities(agent.capabilities),\n    credentialVersion: agent.credentialVersion,\n    fingerprint: agent.fingerprint,\n    expiresAt: agent.expiresAt,\n  };\n}\n\n/**\n * Serializes a passport to its canonical signable string with a fixed field order, so the exact\n * bytes are reproducible and a signer and verifier never disagree about what was covered.\n *\n * @param passport - The passport to serialize.\n * @returns The canonical UTF-8 string to sign or verify.\n */\nexport function canonicalPassportString(passport: AgentPassport): string {\n  return [\n    passport.id,\n    passport.name,\n    passport.issuer,\n    passport.capabilities,\n    String(passport.credentialVersion),\n    passport.fingerprint,\n    passport.expiresAt === null ? 'null' : String(passport.expiresAt),\n  ].join('\\n');\n}\n","/**\n * The Krikos lifecycle state machine: the single source of truth for which agent status\n * transitions are legal.\n *\n * An agent identity moves through a small, explicit set of states. Modeling the legal moves as\n * data, instead of scattering `if` checks through the engine, means the rules are auditable in\n * one place and the same table answers both \"may I do this?\" and \"what could I do next?\".\n *\n * @packageDocumentation\n */\n\nimport type { AgentStatus } from '../types.js';\n\n/**\n * Adjacency list of legal transitions, keyed by source state.\n *\n * - `provisioned` may activate, or be revoked before ever going live, or expire, or archive\n *   (a provisioned identity that is no longer wanted can be retired directly).\n * - `active` may suspend, revoke, expire, or rotate-in-place (rotation is not a state change,\n *   handled separately; active is listed as its own target to express the no-op identity move).\n * - `suspended` may resume to active, be revoked, or expire.\n * - `expired` may be renewed back to active (its expiry extended) or archived.\n * - `revoked` may only be archived; revocation is permanent.\n * - `archived` is terminal.\n *\n * The targets are the states reachable by an operator-driven transition. Auto-expiry is modeled\n * as a transition to `expired` and is therefore a legal target from the live states.\n */\nexport const ALLOWED_TRANSITIONS: Readonly<Record<AgentStatus, readonly AgentStatus[]>> = {\n  provisioned: ['active', 'revoked', 'expired', 'archived'],\n  active: ['suspended', 'revoked', 'expired'],\n  suspended: ['active', 'revoked', 'expired'],\n  expired: ['active', 'archived'],\n  revoked: ['archived'],\n  archived: [],\n};\n\n/**\n * True when an agent may move from `from` to `to` under the lifecycle rules.\n *\n * A transition from a state to itself is never legal here; same-state operations (such as a\n * credential rotation that preserves status) do not go through this check.\n *\n * @param from - Current lifecycle state.\n * @param to - Proposed next state.\n * @returns Whether the move is permitted.\n */\nexport function canTransition(from: AgentStatus, to: AgentStatus): boolean {\n  return ALLOWED_TRANSITIONS[from].includes(to);\n}\n\n/**\n * The states an agent can authorize from. Only `active` qualifies; every other state is\n * fail-closed. Kept as a named predicate so the rule is stated once and reused by the engine,\n * the edge verifier, and the stats counter.\n *\n * @param status - The lifecycle state to test.\n * @returns Whether an agent in this state may ever authorize an action.\n */\nexport function isAuthorizableStatus(status: AgentStatus): boolean {\n  return status === 'active';\n}\n\n/**\n * Whether a state is terminal in the sense that no operator transition other than archival (or,\n * for expired, renewal) remains. Used by {@link import('../types.js').Krikos.prune} eligibility\n * checks and dashboards.\n *\n * @param status - The lifecycle state to test.\n * @returns Whether the state is terminal.\n */\nexport function isTerminalStatus(status: AgentStatus): boolean {\n  return status === 'revoked' || status === 'archived';\n}\n","/**\n * In-memory state backend of Krikos: the zero-config default persistence shape, a snapshot held\n * in a closure variable. Nothing survives the process, which is exactly right for tests, demos,\n * and hosts that persist elsewhere.\n *\n * @packageDocumentation\n */\n\nimport type { StateBackend, StateSnapshot } from '../types.js';\n\n/**\n * Creates a state backend that keeps the latest snapshot in memory.\n *\n * Each call returns an independent backend with its own closure variable; two registries given\n * two `memoryState()` results never see each other's snapshots. The snapshot object is stored by\n * reference, callers must treat saved snapshots as immutable, which the {@link StateSnapshot}\n * readonly contract already requires.\n *\n * @returns A {@link StateBackend} whose `load` resolves to the last saved snapshot, or\n *   `undefined` before the first save.\n */\nexport function memoryState(): StateBackend {\n  let snapshot: StateSnapshot | undefined;\n  return {\n    load(): Promise<StateSnapshot | undefined> {\n      return Promise.resolve(snapshot);\n    },\n    save(next: StateSnapshot): Promise<void> {\n      snapshot = next;\n      return Promise.resolve();\n    },\n  };\n}\n","/**\n * The Krikos engine: an identity registry with an enforced lifecycle state machine, declarative\n * capability authorization, and a hash-chained audit trail, over a pluggable state backend.\n *\n * Design invariants, all load-bearing:\n * - Deterministic: the engine never reads the wall clock or the global random generator. Time\n *   comes from an injected `clock`, ids from a seeded counter. Two registries with the same seed,\n *   clock, and operations produce byte-identical snapshots.\n * - Immutable records: an agent is never mutated in place. Every transition builds a fresh frozen\n *   record and swaps it in, so a snapshot taken at any instant is a stable view.\n * - Fail-closed authorization: {@link Krikos.can} returns true only for an `active` agent that is\n *   not past its expiry and declares an admitting capability. Expiry is enforced on the read even\n *   before an explicit sweep, regardless of the `autoExpire` option.\n * - Append-only audit: every operation appends one frozen, hash-chained event. The trail is never\n *   rewritten or pruned.\n * - Non-fatal persistence: a save fault never crashes the host or aborts an in-memory operation.\n *\n * @packageDocumentation\n */\n\nimport { makeEvent, verifyAuditChain as verifyChain } from '../audit/chain.js';\nimport { assertValidCapability, capabilitiesAuthorize } from '../capability/match.js';\nimport { KrikosError } from '../errors.js';\nimport { computeFingerprint } from '../identity/fingerprint.js';\nimport { canTransition, isAuthorizableStatus } from '../lifecycle/transitions.js';\nimport { memoryState } from '../state/memory.js';\nimport { shortId } from '../stats/hash.js';\nimport type {\n  Agent,\n  AgentFilter,\n  AgentId,\n  AgentInput,\n  AgentSignature,\n  AgentStatus,\n  AuditEvent,\n  AuditKind,\n  AuditOptions,\n  Capability,\n  Issuer,\n  Krikos,\n  KrikosOptions,\n  RegistryStats,\n  StateSnapshot,\n  TelemetryEvent,\n  TelemetryListener,\n} from '../types.js';\n\nconst DEFAULT_SEED = 0x6b72; // \"kr\"\n\n/** Internal mutable engine state, never exposed; reads return frozen copies or views. */\ninterface EngineState {\n  readonly agents: Map<AgentId, Agent>;\n  order: AgentId[];\n  audit: AuditEvent[];\n  counter: number;\n  sequence: number;\n  headHash: string;\n}\n\n/** Freezes an agent record and its nested capability array deeply enough to be tamper-resistant. */\nfunction freezeAgent(agent: Agent): Agent {\n  for (const capability of agent.capabilities) {\n    Object.freeze(capability.actions);\n    if (capability.resources !== undefined) {\n      Object.freeze(capability.resources);\n    }\n    Object.freeze(capability);\n  }\n  Object.freeze(agent.capabilities);\n  Object.freeze(agent.metadata);\n  Object.freeze(agent.issuer);\n  if (agent.signature !== undefined) {\n    Object.freeze(agent.signature);\n  }\n  return Object.freeze(agent);\n}\n\n/**\n * Creates a Krikos registry.\n *\n * With the default in-memory backend the registry is immediately usable and synchronous. With a\n * persistent backend ({@link import('../state/file.js').fileState} or\n * {@link import('../state/kv.js').kvState}), call {@link Krikos.flush} once before the first read\n * or write to guarantee the prior snapshot has been restored.\n *\n * @param options - See {@link KrikosOptions}.\n * @returns A {@link Krikos} registry.\n */\nexport function createKrikos(options: KrikosOptions = {}): Krikos {\n  const clock = options.clock ?? ((): number => Date.now());\n  const seed = options.seed ?? DEFAULT_SEED;\n  const salt = String(seed);\n  const idPrefix = options.idPrefix ?? 'agt';\n  const backend = options.state ?? memoryState();\n  const maxAgents = options.maxAgents;\n  const defaultTtlMs = options.defaultTtlMs;\n  const autoExpire = options.autoExpire ?? true;\n  const requireResourceScope = options.requireResourceScope ?? false;\n\n  const state: EngineState = {\n    agents: new Map(),\n    order: [],\n    audit: [],\n    counter: 0,\n    sequence: 0,\n    headHash: '0000000000000000',\n  };\n\n  const listeners = new Set<TelemetryListener>();\n  if (options.telemetry !== undefined) {\n    listeners.add(options.telemetry);\n  }\n\n  let restored = false;\n  let saveChain: Promise<void> = Promise.resolve();\n\n  const restorePromise: Promise<void> = Promise.resolve(backend.load())\n    .then((snapshot) => {\n      if (snapshot !== undefined && !restored && state.order.length === 0) {\n        hydrate(snapshot);\n      }\n      restored = true;\n    })\n    .catch(() => {\n      // A load fault must not crash the host; the registry degrades to empty. The fault surfaces\n      // again on the next flush, which awaits a real save.\n      restored = true;\n    });\n\n  function hydrate(snapshot: StateSnapshot): void {\n    state.agents.clear();\n    state.order = [];\n    for (const agent of snapshot.agents) {\n      const frozen = freezeAgent({ ...agent });\n      state.agents.set(frozen.id, frozen);\n      state.order.push(frozen.id);\n    }\n    state.audit = snapshot.audit.map((event) => Object.freeze({ ...event }));\n    state.counter = snapshot.counter;\n    state.sequence = snapshot.sequence;\n    const last = state.audit[state.audit.length - 1];\n    state.headHash = last !== undefined ? last.hash : '0000000000000000';\n  }\n\n  function emit(event: TelemetryEvent): void {\n    for (const listener of listeners) {\n      try {\n        listener(event);\n      } catch {\n        // Telemetry is best-effort; a listener fault never reaches a caller.\n      }\n    }\n  }\n\n  function buildSnapshot(): StateSnapshot {\n    return Object.freeze({\n      version: 1,\n      agents: state.order.map((id) => {\n        const agent = state.agents.get(id);\n        if (agent === undefined) {\n          throw new KrikosError('internal: order references a missing agent.', 'ERR_INTERNAL');\n        }\n        return agent;\n      }),\n      audit: [...state.audit],\n      counter: state.counter,\n      sequence: state.sequence,\n    }) as StateSnapshot;\n  }\n\n  function scheduleSave(): void {\n    const snapshot = buildSnapshot();\n    saveChain = saveChain\n      .then(() => Promise.resolve(backend.save(snapshot)).then(() => undefined))\n      .catch(() => {\n        // Non-fatal: a transient save fault never crashes the host. flush() re-attempts and can\n        // surface the error to a caller that wants durability confirmation.\n      });\n  }\n\n  function record(\n    kind: AuditKind,\n    agentId: AgentId,\n    actor: string,\n    detail: string,\n    at: number,\n  ): void {\n    state.sequence += 1;\n    const event = makeEvent(\n      { sequence: state.sequence, at, kind, agentId, actor, detail },\n      state.headHash,\n    );\n    state.audit.push(event);\n    state.headHash = event.hash;\n    emit({\n      kind,\n      agentId,\n      at,\n      detail: { actor, info: detail },\n    });\n  }\n\n  function nextId(): AgentId {\n    state.counter += 1;\n    return `${idPrefix}_${shortId(state.counter, salt)}` as AgentId;\n  }\n\n  /** The status an agent presents on a read, applying auto-expiry without mutating the record. */\n  function viewStatus(agent: Agent, now: number): AgentStatus {\n    if (\n      autoExpire &&\n      agent.expiresAt !== null &&\n      agent.expiresAt <= now &&\n      (agent.status === 'provisioned' || agent.status === 'active' || agent.status === 'suspended')\n    ) {\n      return 'expired';\n    }\n    return agent.status;\n  }\n\n  /** Returns a read view of an agent, reflecting auto-expiry. */\n  function viewAgent(agent: Agent, now: number): Agent {\n    const status = viewStatus(agent, now);\n    return status === agent.status ? agent : freezeAgent({ ...agent, status });\n  }\n\n  function mustGet(id: string): Agent {\n    const agent = state.agents.get(id as AgentId);\n    if (agent === undefined) {\n      throw KrikosError.notFound(`no agent with id '${id}'.`);\n    }\n    return agent;\n  }\n\n  function replace(agent: Agent): Agent {\n    const frozen = freezeAgent(agent);\n    state.agents.set(frozen.id, frozen);\n    scheduleSave();\n    return frozen;\n  }\n\n  function issue(input: AgentInput): Agent {\n    if (typeof input.name !== 'string' || input.name.length === 0) {\n      throw KrikosError.invalid('issue requires a non-empty name.');\n    }\n    if (\n      input.issuer === undefined ||\n      typeof input.issuer.id !== 'string' ||\n      input.issuer.id.length === 0\n    ) {\n      throw KrikosError.invalid('issue requires an issuer with a non-empty id.');\n    }\n    const capabilities = input.capabilities ?? [];\n    for (const capability of capabilities) {\n      assertValidCapability(capability);\n    }\n    if (\n      input.expiresAt !== undefined &&\n      input.expiresAt !== null &&\n      !Number.isFinite(input.expiresAt)\n    ) {\n      throw KrikosError.invalid('expiresAt must be a finite epoch-ms number or null.');\n    }\n    if (maxAgents !== undefined && state.agents.size >= maxAgents) {\n      throw KrikosError.limit(`registry is at its maxAgents limit of ${maxAgents}.`);\n    }\n\n    const now = clock();\n    let id: AgentId;\n    if (input.id !== undefined) {\n      if (input.id.length === 0) {\n        throw KrikosError.invalid('an explicit id must be non-empty.');\n      }\n      if (state.agents.has(input.id as AgentId)) {\n        throw KrikosError.conflict(`an agent with id '${input.id}' already exists.`);\n      }\n      id = input.id as AgentId;\n    } else {\n      id = nextId();\n    }\n\n    const issuer: Issuer =\n      input.issuer.name !== undefined\n        ? { id: input.issuer.id, name: input.issuer.name }\n        : { id: input.issuer.id };\n    const expiresAt =\n      input.expiresAt !== undefined\n        ? input.expiresAt\n        : defaultTtlMs !== undefined\n          ? now + defaultTtlMs\n          : null;\n    const fingerprint = computeFingerprint(input.name, issuer, capabilities, 1);\n    const activate = input.activate === true;\n\n    const agent: Agent = {\n      id,\n      name: input.name,\n      status: activate ? 'active' : 'provisioned',\n      capabilities: capabilities.map((capability) => ({ ...capability })),\n      issuer,\n      ...(input.framework !== undefined ? { framework: input.framework } : {}),\n      fingerprint,\n      credentialVersion: 1,\n      metadata: { ...(input.metadata ?? {}) },\n      issuedAt: now,\n      activatedAt: activate ? now : null,\n      expiresAt,\n      revokedAt: null,\n      archivedAt: null,\n      updatedAt: now,\n    };\n\n    const frozen = freezeAgent(agent);\n    state.agents.set(id, frozen);\n    state.order.push(id);\n    record('agent.issued', id, input.issuer.id, `name=${input.name}`, now);\n    if (activate) {\n      record('agent.activated', id, input.issuer.id, 'issued active', now);\n    }\n    scheduleSave();\n    return frozen;\n  }\n\n  function transition(\n    id: string,\n    to: AgentStatus,\n    kind: AuditKind,\n    actor: string,\n    detail: string,\n    patch: (agent: Agent, now: number) => Agent,\n  ): Agent {\n    const agent = mustGet(id);\n    if (!canTransition(agent.status, to)) {\n      throw KrikosError.transition(`agent '${id}' cannot move from '${agent.status}' to '${to}'.`);\n    }\n    const now = clock();\n    const next = replace(patch(agent, now));\n    record(kind, agent.id, actor, detail, now);\n    return next;\n  }\n\n  function activate(id: string, actor = 'system'): Agent {\n    const agent = mustGet(id);\n    if (agent.status !== 'provisioned') {\n      throw KrikosError.transition(\n        `activate expects a provisioned agent; '${id}' is '${agent.status}'. Use resume for a suspended agent.`,\n      );\n    }\n    return transition(id, 'active', 'agent.activated', actor, 'activated', (current, now) => ({\n      ...current,\n      status: 'active',\n      activatedAt: current.activatedAt ?? now,\n      updatedAt: now,\n    }));\n  }\n\n  function suspend(id: string, reason = '', actor = 'system'): Agent {\n    return transition(\n      id,\n      'suspended',\n      'agent.suspended',\n      actor,\n      reason || 'suspended',\n      (current, now) => ({\n        ...current,\n        status: 'suspended',\n        updatedAt: now,\n      }),\n    );\n  }\n\n  function resume(id: string, actor = 'system'): Agent {\n    const agent = mustGet(id);\n    if (agent.status !== 'suspended') {\n      throw KrikosError.transition(\n        `resume expects a suspended agent; '${id}' is '${agent.status}'.`,\n      );\n    }\n    return transition(id, 'active', 'agent.resumed', actor, 'resumed', (current, now) => ({\n      ...current,\n      status: 'active',\n      updatedAt: now,\n    }));\n  }\n\n  function revoke(id: string, reason = '', actor = 'system'): Agent {\n    return transition(\n      id,\n      'revoked',\n      'agent.revoked',\n      actor,\n      reason || 'revoked',\n      (current, now) => ({\n        ...current,\n        status: 'revoked',\n        revokedAt: now,\n        updatedAt: now,\n      }),\n    );\n  }\n\n  function archive(id: string, actor = 'system'): Agent {\n    return transition(id, 'archived', 'agent.archived', actor, 'archived', (current, now) => ({\n      ...current,\n      status: 'archived',\n      archivedAt: now,\n      updatedAt: now,\n    }));\n  }\n\n  function rotate(id: string, actor = 'system'): Agent {\n    const agent = mustGet(id);\n    if (\n      agent.status !== 'provisioned' &&\n      agent.status !== 'active' &&\n      agent.status !== 'suspended'\n    ) {\n      throw KrikosError.transition(\n        `rotate is only allowed for a usable agent (provisioned, active, suspended); '${id}' is '${agent.status}'.`,\n      );\n    }\n    const now = clock();\n    const credentialVersion = agent.credentialVersion + 1;\n    const fingerprint = computeFingerprint(\n      agent.name,\n      agent.issuer,\n      agent.capabilities,\n      credentialVersion,\n    );\n    const { signature: _dropped, ...rest } = agent;\n    void _dropped;\n    const next = replace({ ...rest, credentialVersion, fingerprint, updatedAt: now });\n    record('agent.rotated', agent.id, actor, `credentialVersion=${credentialVersion}`, now);\n    return next;\n  }\n\n  function renew(id: string, expiresAt: number | null, actor = 'system'): Agent {\n    if (expiresAt !== null && !Number.isFinite(expiresAt)) {\n      throw KrikosError.invalid('renew expiresAt must be a finite epoch-ms number or null.');\n    }\n    const agent = mustGet(id);\n    if (agent.status === 'revoked' || agent.status === 'archived') {\n      throw KrikosError.transition(`renew is not allowed for a '${agent.status}' agent.`);\n    }\n    const now = clock();\n    const reactivate = agent.status === 'expired';\n    const next = replace({\n      ...agent,\n      status: reactivate ? 'active' : agent.status,\n      activatedAt: reactivate ? (agent.activatedAt ?? now) : agent.activatedAt,\n      expiresAt,\n      updatedAt: now,\n    });\n    record(\n      'agent.renewed',\n      agent.id,\n      actor,\n      expiresAt === null ? 'expiresAt=never' : `expiresAt=${expiresAt}`,\n      now,\n    );\n    return next;\n  }\n\n  function grant(id: string, capability: Capability, actor = 'system'): Agent {\n    assertValidCapability(capability);\n    const agent = mustGet(id);\n    if (agent.status === 'revoked' || agent.status === 'archived') {\n      throw KrikosError.transition(`grant is not allowed for a '${agent.status}' agent.`);\n    }\n    const now = clock();\n    const capabilities = [\n      ...agent.capabilities.filter((existing) => existing.name !== capability.name),\n      { ...capability },\n    ];\n    const fingerprint = computeFingerprint(\n      agent.name,\n      agent.issuer,\n      capabilities,\n      agent.credentialVersion,\n    );\n    const { signature: _dropped, ...rest } = agent;\n    void _dropped;\n    const next = replace({ ...rest, capabilities, fingerprint, updatedAt: now });\n    record('capability.granted', agent.id, actor, capability.name, now);\n    return next;\n  }\n\n  function ungrant(id: string, capabilityName: string, actor = 'system'): Agent {\n    const agent = mustGet(id);\n    if (agent.status === 'revoked' || agent.status === 'archived') {\n      throw KrikosError.transition(`ungrant is not allowed for a '${agent.status}' agent.`);\n    }\n    const now = clock();\n    const capabilities = agent.capabilities.filter((existing) => existing.name !== capabilityName);\n    const fingerprint = computeFingerprint(\n      agent.name,\n      agent.issuer,\n      capabilities,\n      agent.credentialVersion,\n    );\n    const { signature: _dropped, ...rest } = agent;\n    void _dropped;\n    const next = replace({ ...rest, capabilities, fingerprint, updatedAt: now });\n    record('capability.revoked', agent.id, actor, capabilityName, now);\n    return next;\n  }\n\n  function attachSignature(id: string, signature: AgentSignature, actor = 'system'): Agent {\n    const agent = mustGet(id);\n    if (agent.status === 'archived') {\n      throw KrikosError.transition('cannot attach a signature to an archived agent.');\n    }\n    if (signature.algorithm !== 'ed25519') {\n      throw KrikosError.invalid(`unsupported signature algorithm '${signature.algorithm}'.`);\n    }\n    if (signature.signedFingerprint !== agent.fingerprint) {\n      throw KrikosError.invalid(\n        'signature does not attest to the current fingerprint; re-sign after the last change.',\n      );\n    }\n    if (signature.signedCredentialVersion !== agent.credentialVersion) {\n      throw KrikosError.invalid(\n        'signature does not attest to the current credential version; re-sign after rotation.',\n      );\n    }\n    const now = clock();\n    const next = replace({ ...agent, signature: { ...signature }, updatedAt: now });\n    record('agent.signed', agent.id, actor, signature.publicKey, now);\n    return next;\n  }\n\n  function can(id: string, capability: string, action: string, resource?: string): boolean {\n    const agent = state.agents.get(id as AgentId);\n    if (agent === undefined) {\n      return false;\n    }\n    if (!isAuthorizableStatus(agent.status)) {\n      return false;\n    }\n    const now = clock();\n    if (agent.expiresAt !== null && agent.expiresAt <= now) {\n      return false;\n    }\n    return capabilitiesAuthorize(\n      agent.capabilities,\n      capability,\n      action,\n      resource,\n      requireResourceScope,\n    );\n  }\n\n  function authorize(\n    id: string,\n    capability: string,\n    action: string,\n    resource?: string,\n    actor = 'system',\n  ): boolean {\n    const allowed = can(id, capability, action, resource);\n    const agent = state.agents.get(id as AgentId);\n    if (agent === undefined) {\n      // Record the denial against a placeholder so audit shows the attempt on an unknown id.\n      record(\n        'access.denied',\n        id as AgentId,\n        actor,\n        `${capability}:${action}${resource !== undefined ? `@${resource}` : ''} (unknown agent)`,\n        clock(),\n      );\n      return false;\n    }\n    const detail = `${capability}:${action}${resource !== undefined ? `@${resource}` : ''}`;\n    record(allowed ? 'access.allowed' : 'access.denied', agent.id, actor, detail, clock());\n    return allowed;\n  }\n\n  function sweepExpired(now = clock()): readonly Agent[] {\n    const swept: Agent[] = [];\n    for (const id of state.order) {\n      const agent = state.agents.get(id);\n      if (agent === undefined) {\n        continue;\n      }\n      if (\n        agent.expiresAt !== null &&\n        agent.expiresAt <= now &&\n        (agent.status === 'provisioned' ||\n          agent.status === 'active' ||\n          agent.status === 'suspended')\n      ) {\n        const next = replace({ ...agent, status: 'expired', updatedAt: now });\n        record('agent.expired', agent.id, 'system', `expiresAt=${agent.expiresAt}`, now);\n        swept.push(next);\n      }\n    }\n    if (swept.length > 0) {\n      emit({ kind: 'registry.swept', at: now, detail: { count: swept.length } });\n    }\n    return swept;\n  }\n\n  function get(id: string): Agent | undefined {\n    const agent = state.agents.get(id as AgentId);\n    if (agent === undefined) {\n      return undefined;\n    }\n    return viewAgent(agent, clock());\n  }\n\n  function list(filter: AgentFilter = {}): readonly Agent[] {\n    const now = clock();\n    const statuses =\n      filter.status === undefined\n        ? undefined\n        : new Set<AgentStatus>(Array.isArray(filter.status) ? filter.status : [filter.status]);\n    const result: Agent[] = [];\n    for (const id of state.order) {\n      const stored = state.agents.get(id);\n      if (stored === undefined) {\n        continue;\n      }\n      const agent = viewAgent(stored, now);\n      if (statuses !== undefined && !statuses.has(agent.status)) {\n        continue;\n      }\n      if (filter.issuer !== undefined && agent.issuer.id !== filter.issuer) {\n        continue;\n      }\n      if (filter.framework !== undefined && agent.framework !== filter.framework) {\n        continue;\n      }\n      if (\n        filter.capability !== undefined &&\n        !agent.capabilities.some((capability) => capability.name === filter.capability)\n      ) {\n        continue;\n      }\n      if (\n        filter.expiringBefore !== undefined &&\n        (agent.expiresAt === null || agent.expiresAt > filter.expiringBefore)\n      ) {\n        continue;\n      }\n      result.push(agent);\n    }\n    return result;\n  }\n\n  function auditTrail(opts: AuditOptions = {}): readonly AuditEvent[] {\n    let events: readonly AuditEvent[] = state.audit;\n    if (opts.agentId !== undefined) {\n      events = events.filter((event) => event.agentId === opts.agentId);\n    }\n    if (opts.kind !== undefined) {\n      events = events.filter((event) => event.kind === opts.kind);\n    }\n    if (opts.limit !== undefined && Number.isFinite(opts.limit) && opts.limit >= 0) {\n      events = events.slice(Math.max(0, events.length - opts.limit));\n    }\n    return [...events];\n  }\n\n  function verifyAuditChain(): boolean {\n    return verifyChain(state.audit);\n  }\n\n  function stats(): RegistryStats {\n    const now = clock();\n    const byStatus: Record<AgentStatus, number> = {\n      provisioned: 0,\n      active: 0,\n      suspended: 0,\n      revoked: 0,\n      expired: 0,\n      archived: 0,\n    };\n    const issuers = new Set<string>();\n    let authorizable = 0;\n    for (const id of state.order) {\n      const stored = state.agents.get(id);\n      if (stored === undefined) {\n        continue;\n      }\n      const status = viewStatus(stored, now);\n      byStatus[status] += 1;\n      issuers.add(stored.issuer.id);\n      if (\n        isAuthorizableStatus(stored.status) &&\n        (stored.expiresAt === null || stored.expiresAt > now)\n      ) {\n        authorizable += 1;\n      }\n    }\n    return {\n      total: state.order.length,\n      byStatus,\n      authorizable,\n      issuers: issuers.size,\n      auditEvents: state.audit.length,\n    };\n  }\n\n  function prune(beforeArchivedAt: number): number {\n    const keep: AgentId[] = [];\n    let pruned = 0;\n    for (const id of state.order) {\n      const agent = state.agents.get(id);\n      if (\n        agent !== undefined &&\n        agent.status === 'archived' &&\n        agent.archivedAt !== null &&\n        agent.archivedAt <= beforeArchivedAt\n      ) {\n        state.agents.delete(id);\n        pruned += 1;\n      } else {\n        keep.push(id);\n      }\n    }\n    state.order = keep;\n    if (pruned > 0) {\n      emit({ kind: 'registry.pruned', at: clock(), detail: { count: pruned } });\n      scheduleSave();\n    }\n    return pruned;\n  }\n\n  async function flush(): Promise<void> {\n    await restorePromise;\n    await saveChain;\n    await backend.save(buildSnapshot());\n  }\n\n  function snapshot(): StateSnapshot {\n    return buildSnapshot();\n  }\n\n  function on(listener: TelemetryListener): () => void {\n    listeners.add(listener);\n    return () => {\n      listeners.delete(listener);\n    };\n  }\n\n  return {\n    issue,\n    get,\n    list,\n    activate,\n    suspend,\n    resume,\n    revoke,\n    rotate,\n    renew,\n    archive,\n    grant,\n    ungrant,\n    can,\n    authorize,\n    attachSignature,\n    sweepExpired,\n    auditTrail,\n    verifyAuditChain,\n    stats,\n    prune,\n    flush,\n    snapshot,\n    on,\n  };\n}\n","/**\n * File state backend of Krikos: one JSON file on disk, written atomically, the persistence shape\n * for single-process Node hosts.\n *\n * This module is allowed to touch Node built-ins, and only through lazy dynamic imports inside\n * function bodies, so merely importing it stays safe in browsers and edge runtimes; the platform\n * requirement only materializes when `load` or `save` actually runs.\n *\n * @packageDocumentation\n */\n\nimport { KrikosError } from '../errors.js';\nimport type { StateBackend, StateSnapshot } from '../types.js';\n\n/** Options of {@link fileState}. */\nexport interface FileStateOptions {\n  /** Filesystem path of the snapshot file, absolute or relative to the working directory. */\n  readonly path: string;\n}\n\n/** True when the value looks like a Node errno error carrying the given code. */\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n  return typeof error === 'object' && error !== null && 'code' in error && error.code === code;\n}\n\n/** Human-readable rendering of an unknown thrown value for error messages. */\nfunction describe(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Parses and validates one serialized Krikos snapshot.\n *\n * @throws KrikosError code `'ERR_STATE_LOAD'` when the text is not valid JSON or not a\n *   snapshot-shaped object.\n * @throws KrikosError code `'ERR_STATE_VERSION'` unless `version` is the literal 1, so a future\n *   layout never half-loads into an engine that cannot interpret it.\n */\nexport function parseSnapshot(text: string, source: string): StateSnapshot {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text);\n  } catch (error: unknown) {\n    throw new KrikosError(\n      `Krikos state at ${source} is not valid JSON: ${describe(error)}`,\n      'ERR_STATE_LOAD',\n    );\n  }\n  if (typeof parsed !== 'object' || parsed === null) {\n    throw new KrikosError(\n      `Krikos state at ${source} is not a snapshot object, found ${typeof parsed}.`,\n      'ERR_STATE_LOAD',\n    );\n  }\n  const record = parsed as Record<string, unknown>;\n  if (record.version !== 1) {\n    throw new KrikosError(\n      `Krikos state at ${source} has unsupported snapshot version ${String(record.version)}, expected 1.`,\n      'ERR_STATE_VERSION',\n    );\n  }\n  if (\n    !Array.isArray(record.agents) ||\n    !Array.isArray(record.audit) ||\n    typeof record.counter !== 'number' ||\n    typeof record.sequence !== 'number'\n  ) {\n    throw new KrikosError(\n      `Krikos state at ${source} is missing a required field of a version 1 snapshot.`,\n      'ERR_STATE_LOAD',\n    );\n  }\n  return parsed as StateSnapshot;\n}\n\n/** Per-process monotonic counter, so each write and each quarantine gets a unique suffix. */\nlet writeCounter = 0;\n\n/**\n * Creates a state backend persisting snapshots to one JSON file.\n *\n * Save is atomic via tmp-then-rename: the snapshot is written to a unique temp file and renamed\n * over `<path>`, so readers see either the old complete file or the new complete file, never a\n * torn write. Single-writer is the supported topology; two processes saving to the same path\n * race at the host's own risk. Missing parent directories are created.\n *\n * Load returns `undefined` when the file does not exist yet (ENOENT), the normal first-run case.\n * A present but unparseable or wrong-version file is quarantined aside (`<path>.corrupt-...`) and\n * the parse error is surfaced, so the next save never silently overwrites recoverable history.\n *\n * @param options - See {@link FileStateOptions}.\n */\nexport function fileState(options: FileStateOptions): StateBackend {\n  const { path } = options;\n  return {\n    async load(): Promise<StateSnapshot | undefined> {\n      const fs = await import('node:fs/promises');\n      let text: string;\n      try {\n        text = await fs.readFile(path, 'utf8');\n      } catch (error: unknown) {\n        if (hasErrnoCode(error, 'ENOENT')) {\n          return undefined;\n        }\n        throw new KrikosError(\n          `Failed to read Krikos state from ${path}: ${describe(error)}`,\n          'ERR_STATE_LOAD',\n        );\n      }\n      try {\n        return parseSnapshot(text, path);\n      } catch (error: unknown) {\n        // Quarantine an unreadable snapshot instead of letting the next save overwrite it: the\n        // bad bytes are renamed aside so the registry can degrade to fresh without destroying\n        // any recoverable history.\n        writeCounter += 1;\n        const quarantine = `${path}.corrupt-${process.pid}-${writeCounter}`;\n        try {\n          await fs.rename(path, quarantine);\n        } catch {\n          // If the quarantine rename fails, still surface the original parse error below.\n        }\n        throw error;\n      }\n    },\n    async save(snapshot: StateSnapshot): Promise<void> {\n      const fs = await import('node:fs/promises');\n      const { dirname } = await import('node:path');\n      await fs.mkdir(dirname(path), { recursive: true });\n      // Unique temp name per write so two overlapping saves never collide on one temp file.\n      writeCounter += 1;\n      const tmpPath = `${path}.${process.pid}.${writeCounter}.tmp`;\n      await fs.writeFile(tmpPath, JSON.stringify(snapshot), 'utf8');\n      await fs.rename(tmpPath, path);\n    },\n  };\n}\n","/**\n * Key-value state backend of Krikos: one JSON string under one key in any structural\n * {@link KvLike} store, the persistence shape for edge runtimes and multi-instance hosts that\n * already run Redis, Upstash, or Cloudflare KV.\n *\n * Krikos never constructs the client and never sees connection credentials; the host passes a\n * ready object.\n *\n * @packageDocumentation\n */\n\nimport type { KvLike, StateBackend, StateSnapshot } from '../types.js';\nimport { parseSnapshot } from './file.js';\n\n/**\n * Creates a state backend persisting snapshots as one JSON string in a key-value store.\n *\n * Any client exposing string get and set wraps into {@link KvLike} in one line, no adapter\n * package needed:\n *\n * @example\n * ```ts\n * // Redis (node-redis or ioredis):\n * const state = kvState({ get: (k) => redis.get(k), set: (k, v) => redis.set(k, v) });\n *\n * // Upstash Redis:\n * const state = kvState({ get: (k) => upstash.get<string>(k), set: (k, v) => upstash.set(k, v) });\n *\n * // Cloudflare KV (a binding named KRIKOS_KV):\n * const state = kvState({\n *   get: (k) => env.KRIKOS_KV.get(k),\n *   set: (k, v) => env.KRIKOS_KV.put(k, v),\n * });\n * ```\n *\n * Load tolerates both `null` and `undefined` from `get`, the two absence conventions in the\n * wild, and returns `undefined` for either, the normal first-run case. A present but unparseable\n * value throws KrikosError `'ERR_STATE_LOAD'`, and a parseable value with the wrong snapshot\n * version throws KrikosError `'ERR_STATE_VERSION'`.\n *\n * @param kv - The ready client, see {@link KvLike}.\n * @param key - Storage key for the snapshot, namespace it per registry when several share one\n *   store.\n */\nexport function kvState(kv: KvLike, key = 'krikos:state'): StateBackend {\n  return {\n    async load(): Promise<StateSnapshot | undefined> {\n      const raw = await kv.get(key);\n      if (raw === undefined || raw === null) {\n        return undefined;\n      }\n      return parseSnapshot(raw, `kv key \"${key}\"`);\n    },\n    async save(snapshot: StateSnapshot): Promise<void> {\n      await kv.set(key, JSON.stringify(snapshot));\n    },\n  };\n}\n"]}