@feltdb/feltkit 0.3.30 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/app.d.ts +27 -9
  2. package/dist/app.js +36 -2
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +2 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest.js +23 -1
  7. package/dist/appboundry/guest.js.map +1 -1
  8. package/dist/authorize.d.ts +24 -3
  9. package/dist/authorize.js.map +1 -1
  10. package/dist/docs.d.ts +1 -1
  11. package/dist/docs.js +1 -0
  12. package/dist/docs.js.map +1 -1
  13. package/dist/index.d.ts +5 -2
  14. package/dist/index.js +1 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/policy.d.ts +172 -0
  17. package/dist/policy.js +311 -0
  18. package/dist/policy.js.map +1 -0
  19. package/dist/runtime/activity.d.ts +16 -0
  20. package/dist/runtime/activity.js.map +1 -1
  21. package/dist/runtime/application-authority.d.ts +20 -1
  22. package/dist/runtime/application-authority.js +60 -12
  23. package/dist/runtime/application-authority.js.map +1 -1
  24. package/dist/runtime/assemble.d.ts +13 -0
  25. package/dist/runtime/assemble.js +29 -1
  26. package/dist/runtime/assemble.js.map +1 -1
  27. package/dist/runtime/content.d.ts +50 -0
  28. package/dist/runtime/content.js +98 -1
  29. package/dist/runtime/content.js.map +1 -1
  30. package/dist/runtime/context.d.ts +62 -11
  31. package/dist/runtime/contract.js +11 -2
  32. package/dist/runtime/contract.js.map +1 -1
  33. package/dist/runtime/data.d.ts +25 -0
  34. package/dist/runtime/data.js +92 -8
  35. package/dist/runtime/data.js.map +1 -1
  36. package/dist/runtime/image-variants.d.ts +48 -0
  37. package/dist/runtime/image-variants.js +295 -0
  38. package/dist/runtime/image-variants.js.map +1 -0
  39. package/dist/runtime/integrations.js +1 -3
  40. package/dist/runtime/integrations.js.map +1 -1
  41. package/dist/runtime/live.d.ts +10 -7
  42. package/dist/runtime/live.js +24 -12
  43. package/dist/runtime/live.js.map +1 -1
  44. package/dist/runtime/local-authority.d.ts +47 -5
  45. package/dist/runtime/local-authority.js +195 -13
  46. package/dist/runtime/local-authority.js.map +1 -1
  47. package/dist/runtime/policies.d.ts +89 -0
  48. package/dist/runtime/policies.js +152 -0
  49. package/dist/runtime/policies.js.map +1 -0
  50. package/dist/runtime/runtime.d.ts +19 -1
  51. package/dist/runtime/runtime.js +192 -4
  52. package/dist/runtime/runtime.js.map +1 -1
  53. package/dist/runtime/services-rules.d.ts +9 -0
  54. package/dist/runtime/services-rules.js +47 -1
  55. package/dist/runtime/services-rules.js.map +1 -1
  56. package/dist/runtime/services.d.ts +117 -9
  57. package/dist/runtime/services.js +154 -13
  58. package/dist/runtime/services.js.map +1 -1
  59. package/dist/server/admin.d.ts +21 -0
  60. package/dist/server/admin.js +114 -0
  61. package/dist/server/admin.js.map +1 -1
  62. package/dist/server/index.js +33 -6
  63. package/dist/server/index.js.map +1 -1
  64. package/dist/server/operators.d.ts +1 -0
  65. package/dist/server/operators.js +1 -1
  66. package/dist/server/operators.js.map +1 -1
  67. package/dist/testing/index.d.ts +11 -0
  68. package/dist/testing/index.js +7 -0
  69. package/dist/testing/index.js.map +1 -1
  70. package/docs/AGENT-OPERATIONS.md +1 -1
  71. package/docs/ARCHITECTURE.md +2 -1
  72. package/docs/GUARANTEES.md +80 -6
  73. package/docs/POLICIES.md +121 -0
  74. package/docs/README.md +3 -2
  75. package/docs/SECURITY.md +30 -0
  76. package/docs/TRANSACTIONS.md +4 -0
  77. package/package.json +11 -7
  78. package/skills/.claude-plugin/marketplace.json +1 -1
  79. package/skills/.claude-plugin/plugin.json +1 -1
  80. package/skills/feltkit-services/SKILL.md +1 -1
@@ -1,3 +1,5 @@
1
+ import { type PolicyDecision } from "../policy.js";
2
+ import { PolicyStore } from "./policies.js";
1
3
  import { type Authorizer } from "@appport/sdk";
2
4
  import type { AppPortApplication } from "@appport/sdk";
3
5
  import { type AgentDefinition, type FeltKitApp, type FunctionDefinition, type PrincipalInput } from "../app.js";
@@ -31,6 +33,8 @@ export interface LoadedProject {
31
33
  app: FeltKitApp;
32
34
  /** "module:export" → definition */
33
35
  functions: Map<string, FunctionDefinition>;
36
+ /** Declared policies (`app.policy`), resolved to function names. */
37
+ policies: import("../policy.js").ResolvedPolicyRule[];
34
38
  modules: string[];
35
39
  loadedAt: string;
36
40
  }
@@ -226,7 +230,8 @@ export declare class FeltKitRuntime {
226
230
  /** One AuthBoundry decision as the application's executor (a person's connection: runtime/integrations.ts). Recorded like ctx.authority's. */
227
231
  decideAsExecutor(principal: Principal | null, requestId: string, request: {
228
232
  capability: string;
229
- onBehalfOf: string;
233
+ onBehalfOf: import("./context.js").OnBehalfOf;
234
+ agent?: string;
230
235
  context?: Record<string, string>;
231
236
  }): Promise<import("./context.js").ApplicationAuthorityDecision>;
232
237
  /** `ctx.integrations`: a declared integration operation, as the caller, under the operation's own permission. */
@@ -398,6 +403,19 @@ export declare class FeltKitRuntime {
398
403
  recordAuth(name: string, principal: Principal | null, detail: Record<string, unknown>, outcome?: "success" | "denied" | "error", via?: ActivityVia): void;
399
404
  /** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
400
405
  call(name: string, rawArgs: unknown, options: CallOptions): Promise<CallResult>;
406
+ /** Managed policies and decision evidence (runtime/policies.ts), in the application's FeltDB instance. */
407
+ get policyStore(): PolicyStore;
408
+ /**
409
+ * Evaluate the policies for a call without running it (no handler, no writes, no evidence): what a
410
+ * policy permits, for whom, and why. Reads the real records the policy would read. A delegation
411
+ * condition asks AuthBoundry, as the call would.
412
+ */
413
+ simulatePolicy(input: {
414
+ function: string;
415
+ principal: Principal | null;
416
+ args?: Record<string, unknown>;
417
+ requestId?: string;
418
+ }): Promise<PolicyDecision>;
401
419
  /** An MCP tool surface for one agent identity, backed by AppPort's MCP bridge. */
402
420
  mcpBridge(principal: Principal | null, session?: Awaited<ReturnType<FeltDbSessionStore["get"]>>): import("@appport/sdk").McpBridge;
403
421
  overview(): {
@@ -10,6 +10,8 @@
10
10
  import { JOB_CONTEXTS_COLLECTION, jobIdOfRun } from "./job-context.js";
11
11
  import { checkTokenBytes } from "./crypto-token.js";
12
12
  import { evaluateAuthorize, evaluateOwnership } from "../authorize.js";
13
+ import { evaluatePolicies, viaCollections } from "../policy.js";
14
+ import { PolicyStore } from "./policies.js";
13
15
  import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
14
16
  import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
15
17
  import { grantsPermission } from "@appport/authorization";
@@ -31,7 +33,7 @@ import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toApp
31
33
  import { ChangeFeed } from "./changes.js";
32
34
  import { generationDigest } from "./generation.js";
33
35
  import { ModelHost } from "./decisions.js";
34
- import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
36
+ import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, ensureOrderedIndexes, feltdbRefusalJSON, readAll } from "./data.js";
35
37
  import { describeStorage } from "./environment.js";
36
38
  import { defaultInstanceFactory } from "./instance.js";
37
39
  import { explainServiceDenials, ServicesHost } from "./services.js";
@@ -117,6 +119,7 @@ export class FeltKitRuntime {
117
119
  startedAt = new Date().toISOString();
118
120
  #project;
119
121
  #authority;
122
+ #policyStore;
120
123
  #services;
121
124
  #appport;
122
125
  #resolver;
@@ -194,6 +197,7 @@ export class FeltKitRuntime {
194
197
  await runtime.#ensureSchema(options.project.app, "start");
195
198
  step("schema");
196
199
  await ensureCollectionMarkers(instance.handle("feltkit.runtime"), options.project.app.collections.keys());
200
+ await runtime.#orderedIndexes(options.project.app);
197
201
  step("markers");
198
202
  await runtime.#services.check();
199
203
  step("services");
@@ -362,6 +366,14 @@ export class FeltKitRuntime {
362
366
  this.logger.info(`Schema ${from} → v${applied.to.version} applied${what.length ? `: ${what.join(", ")}` : " (FeltDB now enforces it)"}`);
363
367
  }
364
368
  }
369
+ /** Indexes with a "desc" direction, declared to an embedded FeltDB (a FeltDB server has the contract's). */
370
+ async #orderedIndexes(app) {
371
+ if (this.environment.storage.kind === "remote")
372
+ return;
373
+ const declared = await ensureOrderedIndexes(this.instance.handle("feltkit.runtime"), app.collections.values());
374
+ if (declared.length)
375
+ this.logger.info(`Ordered indexes declared: ${declared.join(", ")}`);
376
+ }
365
377
  async reload(project) {
366
378
  this.#assertReady();
367
379
  if (project.app.name !== this.#project.app.name) {
@@ -371,6 +383,7 @@ export class FeltKitRuntime {
371
383
  const previous = this.#appport;
372
384
  this.#install(project);
373
385
  await this.#ensureSchema(project.app, "reload");
386
+ await this.#orderedIndexes(project.app);
374
387
  this.#agent?.define();
375
388
  await previous.close().catch(() => undefined);
376
389
  for (const listener of this.#reloadListeners)
@@ -518,6 +531,8 @@ export class FeltKitRuntime {
518
531
  env: this.#env,
519
532
  localUrl: () => this.localAuthority.url(),
520
533
  grants: this.localAuthority.grantsFor(principal, requestId),
534
+ agents: this.localAuthority.agentsFor(principal, requestId),
535
+ agentFor: (requested) => this.localAuthority.agentDecision(principal, requested),
521
536
  record: async ({ capability, executor, onBehalfOf, decision, durationMs }) => {
522
537
  await this.invocations.noteDecision(requestId, { capability, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, executor: decision.executorProof });
523
538
  this.activity.record({
@@ -611,7 +626,9 @@ export class FeltKitRuntime {
611
626
  if (!parsed.ok) {
612
627
  throw new FeltKitError("INVALID_ARGUMENT", `Invalid input for ${capability}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } });
613
628
  }
614
- return this.integrations.invoke(capability, parsed.value, { principal, via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), ...(options.onBehalfOf !== undefined ? { onBehalfOf: options.onBehalfOf } : {}) });
629
+ const requestId = `req_${randomUUID()}`;
630
+ await this.#authorizeIntegration(capability, found.op, parsed.value, principal, "function", requestId);
631
+ return this.integrations.invoke(capability, parsed.value, { principal, via: "function", requestId, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), ...(options.onBehalfOf !== undefined ? { onBehalfOf: options.onBehalfOf } : {}) });
615
632
  },
616
633
  };
617
634
  }
@@ -632,6 +649,7 @@ export class FeltKitRuntime {
632
649
  const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
633
650
  this.#dispatched.add(context.requestId);
634
651
  try {
652
+ await this.#authorizeIntegration(op.capability, op, input, principal, String(context.transport ?? "appport"), context.requestId);
635
653
  return await this.integrations.invoke(op.capability, input, {
636
654
  principal,
637
655
  requestId: context.requestId,
@@ -1406,12 +1424,16 @@ export class FeltKitRuntime {
1406
1424
  ...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
1407
1425
  };
1408
1426
  if (!decision.allowed) {
1427
+ // Durable evidence for a signed-in caller's refusal (an anonymous caller refused before sign-in is in the activity log only).
1428
+ if (principal)
1429
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, ...(principal.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}), outcome: "denied", layer: "role", reason: decision.reason ?? `requires ${decision.required}`, argKeys: argKeys(rawArgs) ?? [] });
1409
1430
  return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
1410
1431
  }
1411
1432
  // The approval requirement, at the execution boundary every interface goes through (/api,
1412
1433
  // AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
1413
1434
  const approvalRefusal = this.#approvalRefusal(name, fn, principal);
1414
1435
  if (approvalRefusal) {
1436
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null, outcome: "denied", layer: "approval", reason: approvalRefusal, argKeys: argKeys(rawArgs) ?? [] });
1415
1437
  return failure(new FeltKitError("FORBIDDEN", approvalRefusal, { details: { approval: "required" }, hint: "Ask a person to run it, or propose it and wait for their approval." }), { authority: { ...authorityRecord, allowed: false, reason: "approval required" }, argKeys: argKeys(rawArgs) });
1416
1438
  }
1417
1439
  const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
@@ -1751,17 +1773,178 @@ export class FeltKitRuntime {
1751
1773
  return failure(error, { authority: authorityRecord, argKeys: Object.keys(args) });
1752
1774
  }
1753
1775
  }
1776
+ /** Managed policies and decision evidence (runtime/policies.ts), in the application's FeltDB instance. */
1777
+ get policyStore() {
1778
+ this.#policyStore ??= new PolicyStore({
1779
+ db: () => this.instance.handle("feltkit.policies"),
1780
+ code: () => this.#project?.policies ?? [],
1781
+ validate: (rule) => {
1782
+ for (const fn of rule.functions) {
1783
+ // A function, or (managed policies only, by capability name) an integration operation.
1784
+ if (!this.#project?.functions.has(fn) && !(rule.source === "managed" && this.integrations.operationFor(fn))) {
1785
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names ${fn}, which this application does not define.`);
1786
+ }
1787
+ }
1788
+ for (const via of (rule.when ?? []).flatMap(viaCollections)) {
1789
+ if (typeof via !== "string" || !this.app.collections.has(via))
1790
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} reads owner.via from ${typeof via === "string" ? via : via.name}, which this application does not declare.`);
1791
+ }
1792
+ if (rule.resource && !this.app.collections.has(rule.resource.collection)) {
1793
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names collection ${rule.resource.collection}, which this application does not declare.`);
1794
+ }
1795
+ },
1796
+ });
1797
+ return this.#policyStore;
1798
+ }
1799
+ /**
1800
+ * Evaluate the policies for a call without running it (no handler, no writes, no evidence): what a
1801
+ * policy permits, for whom, and why. Reads the real records the policy would read. A delegation
1802
+ * condition asks AuthBoundry, as the call would.
1803
+ */
1804
+ async simulatePolicy(input) {
1805
+ if (!this.#project?.functions.has(input.function) && !this.integrations.operationFor(input.function))
1806
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `No function or integration operation named "${input.function}".`);
1807
+ const requestId = input.requestId ?? `sim_${randomUUID()}`;
1808
+ const db = this.#readerFor(input.principal);
1809
+ return evaluatePolicies(await this.policyStore.current(), this.#policyRequest(input.function, input.principal, input.args ?? {}, db, requestId));
1810
+ }
1811
+ /** A read-only view of the application's data for a decision made outside a function's own transaction. */
1812
+ #readerFor(principal) {
1813
+ const reader = new Reader(this.instance.handle("app"), this.#resolver);
1814
+ return hasTenantCollections(this.app.collections.values()) ? scopeToTenant(reader, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(reader);
1815
+ }
1816
+ /**
1817
+ * An integration operation's authorization beyond its role `access`, on every path that reaches
1818
+ * it (its AppPort/MCP capability, `ctx.integrations.invoke`, verification probes): the managed
1819
+ * policies that name its capability, then `feltkit({ authorize })` with `kind: "integration"`.
1820
+ * Refusals are durable evidence, as for functions.
1821
+ */
1822
+ async #authorizeIntegration(capability, op, input, principal, via, requestId) {
1823
+ const hook = this.app.options.authorize;
1824
+ const set = await this.policyStore.current();
1825
+ const governed = set.rules.some((rule) => rule.functions.includes(capability));
1826
+ if (!hook && !governed)
1827
+ return;
1828
+ const db = this.#readerFor(principal);
1829
+ const evidence = (outcome, layer, reason, policy) => ({
1830
+ function: capability,
1831
+ via,
1832
+ requestId,
1833
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1834
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1835
+ outcome,
1836
+ layer,
1837
+ reason,
1838
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1839
+ argKeys: Object.keys(input).sort(),
1840
+ });
1841
+ let policy;
1842
+ if (governed) {
1843
+ policy = await evaluatePolicies(set, this.#policyRequest(capability, principal, input, db, requestId));
1844
+ if (!policy.allowed) {
1845
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1846
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1847
+ }
1848
+ if (policy.durable)
1849
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1850
+ }
1851
+ if (!hook)
1852
+ return;
1853
+ try {
1854
+ await evaluateAuthorize(hook, {
1855
+ function: capability,
1856
+ kind: "integration",
1857
+ access: op.access,
1858
+ capability: { name: capability, version: 1 },
1859
+ principal,
1860
+ args: input,
1861
+ transport: via,
1862
+ requestId,
1863
+ db,
1864
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1865
+ });
1866
+ }
1867
+ catch (error) {
1868
+ if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND"))
1869
+ await this.#recordDecision(evidence("denied", "authorize", error.message));
1870
+ throw error;
1871
+ }
1872
+ }
1873
+ #policyRequest(name, principal, args, db, requestId) {
1874
+ return {
1875
+ function: name,
1876
+ principal,
1877
+ args,
1878
+ db,
1879
+ collection: (collection) => this.app.collections.get(collection),
1880
+ delegate: async ({ capability, onBehalfOf }) => {
1881
+ // A bare id in a record or argument names a person (AuthBoundry's "user:<id>").
1882
+ const person = onBehalfOf.includes(":") ? onBehalfOf : `user:${onBehalfOf}`;
1883
+ const decision = await this.#applicationAuthority(principal, requestId).decide({ capability, onBehalfOf: person });
1884
+ return { allowed: decision.allowed, decisionId: decision.decisionId, delegationId: decision.delegationId, ...(decision.reason ? { reason: decision.reason } : {}) };
1885
+ },
1886
+ };
1887
+ }
1888
+ /**
1889
+ * Durable decision evidence. A refusal is recorded before the caller sees it; if the record cannot
1890
+ * be written the refusal still stands (it is logged). An allow that requires durable evidence is
1891
+ * refused when its record cannot be written: the effect never runs without its evidence.
1892
+ */
1893
+ async #recordDecision(entry) {
1894
+ try {
1895
+ await this.policyStore.record(entry);
1896
+ }
1897
+ catch (error) {
1898
+ if (entry.outcome === "allowed")
1899
+ throw new FeltKitError("UNAVAILABLE", `The decision for ${entry.function} could not be recorded, so it does not run: ${error.message}`);
1900
+ this.logger.error(`Decision evidence for a refusal of ${entry.function} could not be recorded: ${error.message}`);
1901
+ }
1902
+ }
1754
1903
  async #authorizeResource(name, fn, args, principal, options, requestId, db, record) {
1755
1904
  const hook = this.app.options.authorize;
1756
- if (!hook && !fn.owner)
1905
+ const set = await this.policyStore.current();
1906
+ const governed = set.rules.some((rule) => rule.functions.includes(name));
1907
+ if (!hook && !fn.owner && !governed)
1757
1908
  return;
1909
+ const evidence = (outcome, layer, reason, policy) => ({
1910
+ function: name,
1911
+ via: String(options.via),
1912
+ requestId,
1913
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1914
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1915
+ outcome,
1916
+ layer,
1917
+ reason,
1918
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1919
+ argKeys: Object.keys(args).sort(),
1920
+ });
1921
+ let layer = "owner";
1922
+ let recorded = false;
1758
1923
  try {
1759
- // The function's declared ownership first (fails closed), then the application's hook.
1924
+ // The function's declared ownership first (fails closed), then the policies, then the hook.
1760
1925
  const owned = await evaluateOwnership(fn, { function: name, principal, args, db });
1761
1926
  if (owned)
1762
1927
  record.resource = owned;
1928
+ let policy;
1929
+ if (governed) {
1930
+ layer = "policy";
1931
+ policy = await evaluatePolicies(set, this.#policyRequest(name, principal, args, db, requestId));
1932
+ record.policy = { version: policy.policyVersion, matched: [...policy.matched], ...(policy.unmet.length ? { unmet: [...policy.unmet] } : {}), ...(policy.delegations.length ? { delegations: [...policy.delegations] } : {}) };
1933
+ if (!policy.allowed) {
1934
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1935
+ recorded = true;
1936
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1937
+ }
1938
+ if (policy.governed)
1939
+ record.resource = { allowed: true, reason: policy.reason };
1940
+ if (policy.durable)
1941
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1942
+ }
1763
1943
  if (!hook)
1764
1944
  return;
1945
+ layer = "authorize";
1946
+ const run = options.agentRun?.trigger;
1947
+ const approved = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
1765
1948
  const decision = await evaluateAuthorize(hook, {
1766
1949
  function: name,
1767
1950
  definition: fn,
@@ -1773,6 +1956,9 @@ export class FeltKitRuntime {
1773
1956
  transport: options.via,
1774
1957
  requestId,
1775
1958
  db,
1959
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1960
+ ...(run ? { agentRun: { agent: run.agent, triggeredBy: run.by.principalId } } : {}),
1961
+ ...(approved ? { approval: { taskId: approved.taskId, actionId: approved.actionId, approvedBy: approved.approvedBy } } : {}),
1776
1962
  });
1777
1963
  if (decision)
1778
1964
  record.resource = decision;
@@ -1782,6 +1968,8 @@ export class FeltKitRuntime {
1782
1968
  if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND")) {
1783
1969
  record.allowed = false;
1784
1970
  record.resource = { allowed: false, reason: error.message };
1971
+ if (!recorded)
1972
+ await this.#recordDecision(evidence("denied", layer, error.message));
1785
1973
  }
1786
1974
  throw error;
1787
1975
  }