{"_id":"@cubiczan/agent-governance","name":"@cubiczan/agent-governance","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@cubiczan/agent-governance","version":"0.1.0","description":"Governance and audit layer for AI agents that move capital: canonical risk policy engine, CHP decision gate with HITL, and a signed append-only audit ledger.","license":"UNLICENSED","author":{"name":"Shyam Desigan","email":"sam@cubiczan.com","url":"Cubiczan"},"type":"module","main":"./dist/index.js","module":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"}},"publishConfig":{"access":"public"},"scripts":{"build":"tsc -p tsconfig.json","test":"tsx --test test/*.test.ts","prepack":"npm run build"},"engines":{"node":">=18.17"},"keywords":["ai-agents","governance","risk-policy","audit-ledger","hitl","compliance"],"devDependencies":{"@types/node":"^22.10.0","tsx":"^4.19.0","typescript":"^5.6.0"},"gitHead":"edfb48f611653648206022e299acee24d2093c15","_id":"@cubiczan/agent-governance@0.1.0","_nodeVersion":"26.0.0","_npmVersion":"12.0.2","dist":{"integrity":"sha512-AseXIu6SdWCyUQoIizacFuoTtE0PZoL8YEny2s3ATT4KaQbvzNcbt3wlsm40nOMZ+uM4IPyFQ2jV4yvR++mkiQ==","shasum":"b62c1010ecd0a6777c76480a80806695b98f3660","tarball":"https://registry.npmjs.org/@cubiczan/agent-governance/-/agent-governance-0.1.0.tgz","fileCount":19,"unpackedSize":103438,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIB1HilQcG7QKkU7lFKvuSc6zKqL/cdZlybsOPSlzdtrjAiEA0u8IT9OEvJJT7Ldedk5r2SIK/dhjOxeknuMEPsfQsLQ="}]},"_npmUser":{"name":"cubiczan","email":"icohangar@gmail.com"},"directories":{},"maintainers":[{"name":"cubiczan","email":"icohangar@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/agent-governance_0.1.0_1788432937062_0.6144618166548645"},"_hasShrinkwrap":false}},"time":{"created":"2026-09-03T10:55:36.872Z","0.1.0":"2026-09-03T10:55:37.178Z","modified":"2026-09-03T10:55:37.841Z"},"maintainers":[{"name":"cubiczan","email":"icohangar@gmail.com"}],"description":"Governance and audit layer for AI agents that move capital: canonical risk policy engine, CHP decision gate with HITL, and a signed append-only audit ledger.","keywords":["ai-agents","governance","risk-policy","audit-ledger","hitl","compliance"],"author":{"name":"Shyam Desigan","email":"sam@cubiczan.com","url":"Cubiczan"},"license":"UNLICENSED","readme":"# @cubiczan/agent-governance\n\n**Governance and audit layer for AI agents that move capital.**\n\nEvery capital-moving action an agent proposes is driven through a policy\ngate (`EXPLORING → PROVISIONAL → LOCKED / HITL_REQUIRED / BLOCKED`), checked\nagainst hard risk limits and adversarial sanity rules, and recorded in a\ntamper-evident, HMAC-signed, append-only audit ledger — so you can prove to\nan auditor, a counterparty, or yourself exactly what the agent did and why.\n\n- **Zero runtime dependencies.** Node built-ins only.\n- **Fail-closed by design.** Unknown actions, missing policies, breached\n  caps, low-confidence signals, and unauditable decisions never execute.\n- **Restart- and multi-process-safe.** Daily caps persist across restarts;\n  ledger appends are lockfile-serialized across processes.\n\nThis is a commercial, proprietary package. See [LICENSE.md](./LICENSE.md).\nContact sam@cubiczan.com for licensing.\n\n## Quickstart\n\n```ts\nimport { ChpGate, AuditLedger, createPolicy } from \"@cubiczan/agent-governance\";\n\nconst ledger = new AuditLedger({\n  path: \"var/audit.jsonl\",\n  key: process.env.AUDIT_LEDGER_KEY, // HMAC-SHA256 signing key\n});\n\nconst gate = new ChpGate({\n  policy: createPolicy({\n    version: \"1.0\",\n    maxNotionalUsd: 5000,\n    dailyNotionalCapUsd: 20000,\n    hitlThresholdUsd: 1000,\n    allowedActions: [\"buy\", \"sell\"],\n    perAssetLimits: { ETH: 5000, SOL: 3000 },\n    minConfidence: 0.5,\n    allowedVenues: [\"hyperliquid\", \"polymarket\"],\n    maxLeverage: 5,\n  }),\n  ledger,                          // every decision is signed into the ledger\n  statePath: \"var/chp-daily.json\", // daily cap survives restarts\n  hooks: {\n    onBlocked: (d) => alertDashboard(d),\n    onHitl: (d) => pageHuman(d),\n  },\n});\n\nconst decision = gate.evaluate({\n  action: \"buy\",\n  asset: \"ETH\",\n  notionalUsd: 750,\n  venue: \"hyperliquid\",\n  confidence: 0.82,\n  rationale: \"momentum breakout\",\n});\n\nif (decision.allowed) {\n  await execute(order);\n} else if (decision.requiresHuman) {\n  // later, after a human signs off:\n  gate.approveHuman(decision.provenance.decisionId, \"sam@cubiczan.com\");\n}\n\n// Anyone with the key can independently verify the whole ledger:\nconsole.log(ledger.verify()); // { ok: true, count: n }\n```\n\nOr load the policy from a flat YAML file (zero-dependency parser):\n\n```ts\nconst gate = new ChpGate({ policyPath: \"config/policy.yaml\", ledger });\ngate.watchPolicy(5000); // hot-reload with validation; invalid edits are rejected\n```\n\n```yaml\nversion: \"1.0\"\nmax_notional_usd: 5000.0\ndaily_notional_cap_usd: 20000.0\nhitl_threshold_usd: 1000.0\nallowed_actions:\n  - buy\n  - sell\nper_asset_limits:\n  ETH: 5000.0\n  SOL: 3000.0\nmin_confidence: 0.5\nallowed_venues:\n  - hyperliquid\nmax_leverage: 5.0\nprice_band:\n  min: 0.02\n  max: 0.98\n```\n\n## API\n\n### Policy (`Policy`)\n\n| Export | Description |\n| --- | --- |\n| `createPolicy(partial)` | Build a policy from a plain object; unspecified fields take the conservative default. Throws `PolicyValidationError` with per-field messages. |\n| `validatePolicy(policy)` | Returns a list of human-readable errors (empty = valid). |\n| `loadPolicy(path?, { strict?, warn? })` | Load from flat YAML. Non-strict (default): missing/invalid file warns and falls back to the conservative default. Strict: throws. |\n| `defaultPolicy()` / `defaultPolicyPath()` | Conservative built-in policy / `config/policy.yaml` under cwd. |\n\nSchema: `maxNotionalUsd`, `dailyNotionalCapUsd`, `hitlThresholdUsd`,\n`allowedActions`, `perAssetLimits`, `minConfidence`, plus optional\n`allowedAssets`, `blockedAssets`, `allowedVenues`, `maxLeverage`,\n`priceBand { min?, max? }`.\n\n### Gate (`ChpGate`)\n\n| Member | Description |\n| --- | --- |\n| `new ChpGate({ policy?, policyPath?, ledger?, actor?, statePath?, allowZeroNotional?, hooks?, clock? })` | Construct with a validated policy object or a YAML path. |\n| `evaluate(action)` | Run policy + adversarial checks. Returns `ChpDecision` (`allowed`, `requiresHuman`, `state`, `reason`, `provenance`). |\n| `approveHuman(decisionId, approver)` | Promote a pending HITL decision to LOCKED (hard caps re-checked at approval time). |\n| `getPendingHitl()` | Pending HITL actions keyed by decisionId. |\n| `getDecisions()` | In-memory append-only provenance records. |\n| `getDailyNotionalUsd()` | Notional locked in the current rolling day. |\n| `reloadPolicy()` | Strict re-load + validate from `policyPath`; keeps the old policy on failure. |\n| `watchPolicy(intervalMs?, onReload?)` / `unwatchPolicy()` | Polling hot-reload (watcher is unref'ed). |\n| `on(\"blocked\" \\| \"hitl\" \\| \"locked\", fn)` | Typed event hooks; returns an unsubscribe function. |\n\nChecks run per action: allowed-action, allowed/blocked-asset, allowed-venue,\nper-asset cap, max notional, projected daily cap, sane-notional,\nmin-confidence, max-leverage, price band. Every check is recorded as a\npass/fail claim in the decision's provenance.\n\n### Ledger (`AuditLedger`)\n\n| Export | Description |\n| --- | --- |\n| `new AuditLedger({ path, key?, lock?, lockTimeoutMs?, lockRetryMs?, lockStaleMs? })` | Signed append-only JSONL ledger. Key defaults to `$AUDIT_LEDGER_KEY`, then a documented dev-only default. |\n| `append(record)` | Append one record chained to the previous signature; returns the new signature. |\n| `verify()` / `verifyLedger(path, key?)` | Re-derive every signature in-chain; reports the first tampered line index. |\n| `canonicalJson(value)` | Stable sorted-key JSON used as the signing payload. |\n\n## Cross-language golden-vector compatibility\n\nThe signing scheme (canonical JSON, payload field set, HMAC-SHA256,\n`prev_sig` chaining) is byte-identical to the author's TypeScript, Python,\nand Rust audit-ledger implementations, pinned by a shared golden vector\nasserted in this package's test suite:\n\n```\nkey=\"k\", ts=\"2026-01-01T00:00:00Z\", event=\"e\", actor=\"a\", inputs={x:1}, sources=[\"s\"]\nsig = d379966f5be33822aa1091efa18034e67e679fbadb168bb73c3f42ef712a46fc\n```\n\nLedgers written by any of those implementations verify under this package\n(with the same key), and vice versa.\n\n## Multi-process ledger safety — limits\n\nAppends are serialized via an advisory `<path>.lock` file (O_CREAT|O_EXCL,\nbounded retry, mtime-based stale-lock reclamation) and written with\nO_APPEND. This is safe for cooperating writers on a local POSIX filesystem.\nIt is **not** safe on NFS or other filesystems without coherent metadata,\nand it does not protect against non-cooperating writers that bypass the\nlock. For multi-host deployments, front the ledger with a single writer.\n\n## License\n\nProprietary. Copyright (c) 2026 Shyam Desigan (Cubiczan). All rights\nreserved. Use requires a commercial license — sam@cubiczan.com.\n","readmeFilename":"README.md","_rev":"1-0975693c617a0754518314d88b9fd361"}