Skip to content

feat(identity): policy-bundle endpoint so contract travels with ChittyID#197

Open
chitcommit wants to merge 1 commit into
mainfrom
feat/identity-policy-bundle
Open

feat(identity): policy-bundle endpoint so contract travels with ChittyID#197
chitcommit wants to merge 1 commit into
mainfrom
feat/identity-policy-bundle

Conversation

@chitcommit
Copy link
Copy Markdown
Contributor

@chitcommit chitcommit commented May 22, 2026

Summary

Closes the cross-channel enforcement gap for the System-Wide Sensitive Intent Contract. Local hooks (~/.claude/hooks/) only fire on this VM — Desktop, Mobile, web, ChatGPT have no local hook layer.

New endpoint binds policy to the entity, not the channel:

  • `GET /api/v1/identity/:chittyId/policy-bundle` → returns vendored canon bundle (contract, policy, conformance, integration map, drift framework) + sha256 + ETag
  • `GET /api/v1/identity/:chittyId/policy-bundle/check` → cheap ETag-only check for clients caching the bundle

Public read (no auth) — bundle is non-secret governance and must be reachable by any channel on session start. ChittyID is validated against the canonical P/L/T/E/A regex.

Implementation

  • `policy-bundle/v1/`: vendored canon source files + compiled `bundle.json` (sha256 over file contents)
  • `scripts/build-policy-bundle.mjs`: regenerates `bundle.json` from canon sources (`npm run policy-bundle:build`)
  • `src/api/routes/identity.js`: Hono route, ChittyID-validated
  • `src/api/middleware/auth.js`: path-specific public bypass alongside existing `/api/v1/context/sync` bypass
  • `tests/api/identity-routes.test.js`: 6 tests hitting the real route + real bundle (no mocks)

Test plan

  • All 6 new tests pass
  • Lint clean (0 errors)
  • Deploy staging, curl `/api/v1/identity/03-1-USA-5537-P-2602-0-38/policy-bundle` and confirm 200 + ETag
  • curl with `If-None-Match` and confirm 304
  • curl with malformed ChittyID, confirm 400 INVALID_CHITTYID

Follow-ups (deliberately not in scope)

  1. Entity-specific policy overlays keyed by ChittyID
  2. Desktop/Mobile/web client wiring to fetch on session start (channel-registration response)
  3. Gateway-level enforcement middleware (mcp.chitty.cc, agent.chitty.cc/mcp) for thin clients that can't run client-side checks
  4. Stop/PostToolUse hooks that scan assistant output for forbidden phrases — the prior gap that triggered this work

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Introduced system-wide sensitive intent policy bundle defining contracts, enforcement behaviors, and remediation procedures
    • Added API endpoints to retrieve policy bundles with ETag-based caching for efficient client synchronization
  • Chores

    • Added build tooling for policy bundle generation

Review Change Stack

Closes the cross-channel enforcement gap. Local hooks at ~/.claude/hooks/
only fire on the VM — Desktop, Mobile, web, ChatGPT have no local hook
layer, so the System-Wide Sensitive Intent Contract is structurally
invisible to them today.

New: GET /api/v1/identity/:chittyId/policy-bundle (and /check) returns
the vendored canon bundle (contract, policy, conformance, integration
map, drift framework) with ETag/304 support. Public read — bundle is
non-secret governance and must be reachable by any channel binding to
a ChittyID on session start.

- policy-bundle/v1/: vendored canon (.md, .json, .yaml) + compiled
  bundle.json with sha256 of file contents
- scripts/build-policy-bundle.mjs: regenerates bundle.json from canon
- src/api/routes/identity.js: ChittyID-validated route (P/L/T/E/A)
- src/api/middleware/auth.js: path-specific public bypass for the
  policy-bundle GET endpoints
- 6 real tests (no mocks): hit the Hono router with the real bundle

Follow-up (out of scope for this PR):
- entity-specific policy overlays keyed by ChittyID
- desktop/mobile/web client wiring to fetch on session start
- gateway-level enforcement middleware for thin clients

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings May 22, 2026 15:50
@cloudflare-workers-and-pages
Copy link
Copy Markdown
Contributor

cloudflare-workers-and-pages Bot commented May 22, 2026

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
❌ Deployment failed
View logs
chittyconnect f044774 May 22 2026, 03:51 PM

@@ -0,0 +1,35 @@
#!/usr/bin/env node
// Build policy-bundle/v1/bundle.json from vendored canon files.
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2026

📝 Walkthrough

Walkthrough

This PR introduces a complete policy bundle delivery system for managing sensitive-intent governance across product surfaces. It includes versioned contract documents, JSON policy configurations, conformance test specifications, integration maps defining enforcement points, and a build/delivery pipeline comprising a CLI bundle builder, npm wiring, API routes, public authentication handling, and comprehensive tests.

Changes

Policy Bundle Delivery System

Layer / File(s) Summary
Policy Specification & Contracts
policy-bundle/v1/system-wide-sensitive-intent-contract-v1.md, policy-bundle/v1/system-wide-sensitive-intent-policy-v1.json, policy-bundle/v1/system-wide-conformance-tests-v1.md, policy-bundle/v1/system-wide-drift-remediation-framework-v1.md, policy-bundle/v1/system-wide-integration-map-v1.yaml
Contract defines applicability, execution flow, error classes, and leak containment procedures. Policy JSON specifies routing, forbidden behaviors, fail-closed mappings, destination resolution, and escalation rules. Conformance tests enumerate scenarios (T1–T6) for broker routing, missing credentials, insufficient scope, unverified destinations, and leak containment. Integration map configures enforcement points across surfaces (claude_desktop, codex, chatgpt, ch1tty, chittymcp, chittyconnect_concierge) and global invariants. Drift remediation framework documents triggers, severity decision tree, retry/backoff policy, and automated correction actions.
Bundle Assembly & Build
scripts/build-policy-bundle.mjs, package.json, policy-bundle/v1/bundle.json
Build script reads policy artifacts from policy-bundle/v1/, constructs bundle JSON with version, scope, timestamp, embedded file contents, and computed SHA-256 hash of stable file serialization. Generated bundle.json packages all artifacts with metadata. npm policy-bundle:build script enables reproducible generation.
Policy Bundle API Routes
src/api/routes/identity.js
New identityRoutes Hono module validates ChittyID against regex, provides GET /:chittyId/policy-bundle (full bundle with ETag/If-None-Match 304 caching), and GET /:chittyId/policy-bundle/check (lightweight version + sha256 check). Both endpoints set ETag and Cache-Control headers.
Router Wiring & Authentication
src/api/router.js, src/api/middleware/auth.js, tests/api/identity-routes.test.js
Router imports and registers identity routes at /api/v1/identity. Auth middleware adds isPolicyBundlePath helper to detect policy-bundle GET requests and short-circuits authentication, setting public context before normal validation. Tests validate successful 200 responses with correct JSON shape and ETag, 304 caching behavior on If-None-Match match, invalid-ID rejection with 400, entity-type acceptance loop, and /check endpoint minimal response and cache behavior.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Router
  participant AuthMiddleware
  participant IdentityRoutes
  participant Cache
  
  Client->>Router: GET /api/v1/identity/:chittyId/policy-bundle
  Router->>AuthMiddleware: Check isPolicyBundlePath
  AuthMiddleware->>AuthMiddleware: Set public apiKey context
  AuthMiddleware->>IdentityRoutes: next()
  IdentityRoutes->>IdentityRoutes: Validate chittyId against regex
  IdentityRoutes->>Cache: Check If-None-Match vs ETag
  alt ETag matches
    IdentityRoutes->>Client: 304 Not Modified
  else No ETag match
    IdentityRoutes->>Client: 200 with bundle payload + ETag
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

security-approved, docs-approved, access-reviewed

Poem

🐰 A bundle of policy arrives on the wire,
Contracts and gates to lift us higher—
Sensitive intents now brokered with care,
ETag caching keeps bandwidth spare.
From chaos to conformance, drift's held tight,
Rabbit hops forward—the system's done right! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers purpose/scope, implementation details, and test plan but lacks explicit checkboxes for Security & Access and Docs sections from the template. Complete the template checklist by explicitly addressing Security & Access (secrets, access model, labels) and Docs (onboarding, scopes.yml) sections with checkmarks or justification.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately summarizes the main change: adding a policy-bundle endpoint that binds governance policies to ChittyIDs for cross-channel enforcement.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/identity-policy-bundle

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
policy-bundle/v1/system-wide-integration-map-v1.yaml (1)

3-6: ⚡ Quick win

Replace machine-specific absolute artifact paths with portable identifiers.

Lines 3-6 hardcode /home/ubuntu/..., which makes the integration map host-dependent and less channel-agnostic. Use bundle-relative names (or a neutral URI scheme) so clients across environments can consume it consistently.

Suggested diff
 contract:
-  policy_doc: /home/ubuntu/.ch1tty/canon/system-wide-sensitive-intent-contract-v1.md
-  policy_json: /home/ubuntu/.ch1tty/canon/system-wide-sensitive-intent-policy-v1.json
-  conformance: /home/ubuntu/.ch1tty/canon/system-wide-conformance-tests-v1.md
-  drift_remediation: /home/ubuntu/.ch1tty/canon/system-wide-drift-remediation-framework-v1.md
+  policy_doc: system-wide-sensitive-intent-contract-v1.md
+  policy_json: system-wide-sensitive-intent-policy-v1.json
+  conformance: system-wide-conformance-tests-v1.md
+  drift_remediation: system-wide-drift-remediation-framework-v1.md
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@policy-bundle/v1/system-wide-integration-map-v1.yaml` around lines 3 - 6, The
policy integration map currently uses machine-specific absolute paths for keys
policy_doc, policy_json, conformance, and drift_remediation; change these values
to portable bundle-relative identifiers or a neutral URI scheme (e.g.,
./canon/system-wide-sensitive-intent-contract-v1.md or
bundle://canon/system-wide-sensitive-intent-policy-v1.json) so the map is
host-agnostic and consumable across environments—update the four entries
(policy_doc, policy_json, conformance, drift_remediation) accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@policy-bundle/v1/system-wide-integration-map-v1.yaml`:
- Around line 3-6: The policy integration map currently uses machine-specific
absolute paths for keys policy_doc, policy_json, conformance, and
drift_remediation; change these values to portable bundle-relative identifiers
or a neutral URI scheme (e.g.,
./canon/system-wide-sensitive-intent-contract-v1.md or
bundle://canon/system-wide-sensitive-intent-policy-v1.json) so the map is
host-agnostic and consumable across environments—update the four entries
(policy_doc, policy_json, conformance, drift_remediation) accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f68aeaf3-7ce6-4e0e-a6c8-62d95cf9b581

📥 Commits

Reviewing files that changed from the base of the PR and between 973b4d9 and f044774.

📒 Files selected for processing (12)
  • package.json
  • policy-bundle/v1/bundle.json
  • policy-bundle/v1/system-wide-conformance-tests-v1.md
  • policy-bundle/v1/system-wide-drift-remediation-framework-v1.md
  • policy-bundle/v1/system-wide-integration-map-v1.yaml
  • policy-bundle/v1/system-wide-sensitive-intent-contract-v1.md
  • policy-bundle/v1/system-wide-sensitive-intent-policy-v1.json
  • scripts/build-policy-bundle.mjs
  • src/api/middleware/auth.js
  • src/api/router.js
  • src/api/routes/identity.js
  • tests/api/identity-routes.test.js

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a public, identity-bound “policy bundle” API so clients across channels can fetch a canonical System-Wide Sensitive Intent governance bundle (with ETag/sha) keyed by ChittyID.

Changes:

  • Adds GET /api/v1/identity/:chittyId/policy-bundle and /check routes with ChittyID validation and ETag-based caching.
  • Vendors the v1 governance bundle source files + committed bundle.json, plus a build script (npm run policy-bundle:build) to regenerate it.
  • Introduces an auth-middleware bypass for the new public endpoints and adds route-level tests.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/api/identity-routes.test.js Adds Vitest coverage for the identity policy-bundle routes (status, ETag/304, validation, check endpoint).
src/api/routes/identity.js Implements the new identity policy-bundle endpoints with regex validation and cache headers/ETag handling.
src/api/router.js Mounts the new identity routes under /api/v1/identity.
src/api/middleware/auth.js Adds a path-based public bypass for the new policy-bundle endpoints.
scripts/build-policy-bundle.mjs Adds a bundle builder that compiles vendored canon files into policy-bundle/v1/bundle.json and computes sha256.
policy-bundle/v1/system-wide-sensitive-intent-policy-v1.json Adds the v1 sensitive intent policy JSON.
policy-bundle/v1/system-wide-sensitive-intent-contract-v1.md Adds the v1 sensitive intent contract document.
policy-bundle/v1/system-wide-integration-map-v1.yaml Adds the v1 integration surface map.
policy-bundle/v1/system-wide-drift-remediation-framework-v1.md Adds the v1 drift remediation framework document.
policy-bundle/v1/system-wide-conformance-tests-v1.md Adds the v1 conformance test definitions.
policy-bundle/v1/bundle.json Adds the generated v1 bundle artifact including file contents and sha256.
package.json Adds policy-bundle:build script.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +45 to +49
version: bundle.version,
scope: bundle.scope,
sha256: bundle.sha256,
generated_at: bundle.generated_at,
bundle: bundle.files,
Comment on lines +51 to +55
if (isPolicyBundlePath(c)) {
c.set("apiKey", { type: "public", service: "policy-bundle", status: "active" });
await next();
return;
}
@@ -0,0 +1,35 @@
#!/usr/bin/env node
// Build policy-bundle/v1/bundle.json from vendored canon files.
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
Comment on lines +3 to +6
policy_doc: /home/ubuntu/.ch1tty/canon/system-wide-sensitive-intent-contract-v1.md
policy_json: /home/ubuntu/.ch1tty/canon/system-wide-sensitive-intent-policy-v1.json
conformance: /home/ubuntu/.ch1tty/canon/system-wide-conformance-tests-v1.md
drift_remediation: /home/ubuntu/.ch1tty/canon/system-wide-drift-remediation-framework-v1.md
Comment thread src/api/router.js
api.route("/api/v1/tenants/migration", migrationRoutes);
api.route("/api/v1/tenants", tenantRoutes);
api.route("/api/v1/sessions", sessionRoutes);
api.route("/api/v1/identity", identityRoutes);
Comment thread src/api/router.js
api.route("/api/v1/tenants/migration", migrationRoutes);
api.route("/api/v1/tenants", tenantRoutes);
api.route("/api/v1/sessions", sessionRoutes);
api.route("/api/v1/identity", identityRoutes);
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f044774a99

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const identityRoutes = new Hono();

// ChittyID format: VV-G-LLL-SSSS-T-YM-C-X where T ∈ {P,L,T,E,A}
const CHITTYID_RE = /^\d{2}-\d-[A-Z]{3}-\d{4}-[PLTEA]-\d{4}-\d-\d{1,3}$/;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Accept alphanumeric ChittyID segments

The new CHITTYID_RE rejects canonical IDs that contain letters in the SSSS or final X segments (it requires \d{4} and \d{1,3}), so /api/v1/identity/:chittyId/policy-bundle* returns 400 INVALID_CHITTYID for valid identities such as those produced by generateLocalChittyId() (src/intelligence/experience-anchor.js, which emits base36/alpha characters and is tested by tests/intelligence/experience-anchor.test.js). This makes the policy-bundle endpoint unusable for a non-trivial portion of real ChittyIDs.

Useful? React with 👍 / 👎.

*/

import { Hono } from "hono";
import bundle from "../../../policy-bundle/v1/bundle.json";
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Ship policy-bundle JSON with the runtime package

identityRoutes now has a hard runtime import of ../../../policy-bundle/v1/bundle.json, but package.json still uses a restrictive files allowlist that does not include policy-bundle/** (confirmed by npm pack --dry-run, which omits that directory). In npm-installed environments this causes module resolution failure when the router is loaded, so the service can fail to start before handling any request.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants