SaaS Product · Kiro-Generated · TypeScript

Gov-Process SaaS
Governance-as-a-Service Platform

Kiro took a working TypeScript governance library — 136 passing tests, 6 core components — and generated a complete multi-tenant SaaS productization: Fastify API server, PostgreSQL + Redis multi-tenant data isolation, Git-webhook-triggered policy hot-reload with zero downtime, blue-green index swapping, encrypted credential store, and a hybrid client SDK with automatic agent/library fallback. The same governance intelligence, now monetizable.

13
Tasks Completed
15
API Endpoints
136
Tests Passing
0
Downtime Updates
3
SDK Modes
0
TS Errors

Library → Agent → Multi-Tenant SaaS

The governance engine started as a TypeScript library imported directly into projects. Kiro drove two successive productization jumps — each adding a new deployment tier without breaking the tier below.

Stage 1 — Library

Embedded TypeScript

GovernanceIndexer, ComplianceValidator, ArtifactGenerator, ContextManager. Imported directly into each project. Reads local ./governance/ markdown files. 136 tests. 0 infra.

Stage 2 — Agent Service

Standalone API + Git Sync

Fastify server exposing the library over REST. GitSyncManager polls/pulls governance repos on webhook push. WebhookHandler verifies GitHub/GitLab HMAC signatures. PolicyUpdateOrchestrator hot-reloads the index.

Stage 3 — SaaS

Multi-Tenant Platform

TenantManager adds full database + cache + filesystem isolation per tenant. API key auth. Encrypted credential storage. Audit trail. Blue-green indexing. Rollback. Client SDK with hybrid fallback.

Kiro's spec for this transformation was precise: take a working library with 100% test coverage and produce a production-grade SaaS service without breaking the library API. The design called for 13 sequential tasks — each shipping a testable milestone — with checkpoints at Tasks 5, 8, and 12 that verified zero TypeScript errors, zero lint errors, and all tests passing before the next task began. The final deliverable at Task 13 was the Client SDK: a three-mode abstraction (agent, library, auto) that lets any consumer choose their deployment tier at configuration time, with automatic fallback to library mode if the agent is unreachable. Zero breaking changes to existing library consumers.

Spec-driven tasks Checkpoint gates Zero breaking changes TypeScript strict mode Property-based tests fast-check

Service Layers

Client Layer
@gov-process/agent-client SDK auto / agent / library modes Automatic fallback Retry + exponential backoff CI/CD pipeline integration
API Gateway
Fastify server API key auth Rate limiting CORS + security headers Structured request logging Swagger / OpenAPI docs
Webhook Layer
GitHub webhook (HMAC-SHA256) GitLab webhook (token) Replay attack prevention (5-min window) Branch filtering 10 webhooks/min per tenant
Policy Orchestration
PolicyUpdateOrchestrator Blue-green index swap Zero-downtime hot reload Rollback to any of last 5 indexes Distributed lock (no concurrent updates) Pre-apply validation
Core Engine
GovernanceIndexer ComplianceValidator ArtifactGenerator ContextManager ProjectClassifier Unchanged from library
Multi-Tenancy
TenantManager DB isolation per tenant Redis namespace per tenant Filesystem isolation Encrypted credentials 5-min cache TTL
Persistence
PostgreSQL (tenant + audit data) Redis (cache + distributed locks + rate limiting) Gitea (local dev mock Git server) Connection pooling + transactions

What Kiro Built Across 13 Tasks

Tasks 1–2

Project Infrastructure + DB/Cache

TypeScript strict mode project. Jest + fast-check PBT. ESLint + Prettier. PostgreSQL schema with migrations. Redis with tenant namespace helpers. Docker Compose for all local infra.

✓ CompleteTypeScript
Task 3

Core Agent Service

Fastify server with middleware stack: API key auth, request logging, error handling, rate limiting, CORS, security headers. Health check endpoint. Service info route. Full error boundary.

✓ CompleteFastify
Task 4

Git Sync Manager

Clone + pull governance repos. Change detection (added/modified/deleted). Branch/tag management. Encrypted credential storage. SSH key + PAT support. Retry with exponential backoff.

✓ Completesimple-git
Task 6

Webhook Handler

GitHub HMAC-SHA256 verification. GitLab token verification. 5-minute replay attack prevention window. Per-tenant rate limiting (10/min). Branch-specific change tracking for targeted re-indexing.

✓ CompleteHMAC
Task 7

Policy Update Orchestrator

Zero-downtime blue-green index swap: new index built in background, validated, then atomically swapped into live. Keeps last 5 successful indexes. Rollback to any commit. Distributed lock prevents concurrent updates for the same tenant.

✓ CompleteBlue-green
Task 9

Tenant Manager

Full tenant lifecycle: create, read, update, deactivate, reactivate. Tenant isolation enforcement across DB, cache, and filesystem. Configuration validation. Usage statistics. Encrypted credential storage. 5-minute TTL cache.

✓ CompleteMulti-tenant
Task 10

Compliance Validation API

Multi-tenant validation endpoint. Code artifact submission with language + filepath context. Development stage support. Strict mode, warning toggles, evidence collection options. Violation severity levels + remediation guidance per runbook reference.

✓ Complete
Task 11

Artifact Generation API

Three endpoints: Model Card (with confidence scoring), DPIA (with missing field identification), Risk Assessment (with actionable suggestions). Markdown output. Tenant validation. All artifacts reference the specific governance runbook sections that drove them.

✓ CompleteConfidence scores
Task 13

Governance Agent Client SDK

npm package @gov-process/agent-client. Three modes: agent (API only), library (embedded, offline), auto (hybrid with fallback). Lazy loading of library components. Retry + exponential backoff. Mode switching at runtime. Axios HTTP client.

✓ CompleteHybrid SDK

Three Deployment Modes — One API

The @gov-process/agent-client SDK abstracts the deployment tier from the consumer. A team can start in library mode (offline, zero infra), graduate to agent mode (shared service), and switch via a single config change — no code changes in calling code.

Mode: Library

Offline / Embedded

Uses the local TypeScript library with no network calls. Reads from ./governance/ markdown files. Works without any running service. Ideal for offline development and air-gapped environments.

Use when: no agent deployed yet
Mode: Agent

API Only

Only uses the remote agent API. Throws if the agent is unavailable. Always gets the latest policy version from the central server. Correct for CI/CD pipelines that must validate against the canonical governance index.

Use when: CI/CD, strict policy enforcement
SDK Quick Start — Auto Mode+
import { GovernanceAgentClient } from '@gov-process/agent-client'; const client = new GovernanceAgentClient({ mode: 'auto', agentUrl: 'https://gov-agent.example.com', apiKey: process.env.GOV_API_KEY, fallbackPath: './governance', timeout: 5000, retries: 3, }); // Validate code artifacts const result = await client.validate( [{ filePath: 'src/model.py', content: '...', language: 'python' }], { projectType: 'ml-model', developmentStage: 'development', frameworks: ['scikit-learn'], dataTypes: ['personal'] } ); console.log('Passed:', result.passed); console.log('Violations:', result.violations); // Generate compliance artifact const modelCard = await client.generateModelCard({ modelName: 'Customer Churn Predictor', modelType: 'classification', trainingData: 'historical_transactions', intendedUse: 'Predict customer churn risk', }); console.log('Confidence:', modelCard.confidence);

15 Endpoints — 4 Public, 11 Authenticated

GET/public
GET/api/v1/healthpublic
POST/webhooks/github/:tenantIdpublic + HMAC
POST/webhooks/gitlab/:tenantIdpublic + token
POST/api/v1/tenantsauth required
GET/api/v1/tenantsauth required
GET/api/v1/tenants/:tenantIdauth required
PATCH/api/v1/tenants/:tenantIdauth required
POST/api/v1/tenants/:tenantId/deactivateauth required
POST/api/v1/tenants/:tenantId/reactivateauth required
GET/api/v1/tenants/:tenantId/statsauth required
POST/api/v1/validateauth required
GET/api/v1/validate/statsauth required
POST/api/v1/generate/model-cardauth required
POST/api/v1/generate/dpiaauth required
POST/api/v1/generate/risk-assessmentauth required

6 Components, 136 Tests — Zero Changes

The SaaS productization wrapped these components but never modified them. The test count is the guarantee that the wrapping didn't break anything.

ComponentResponsibilityTestsNotable
MarkdownParser Parses governance runbooks — extracts sections, procedures, checklists, frontmatter 15 unit + 11 PBT Hierarchical section structure
RequirementExtractor Identifies EARS patterns (ubiquitous, event-driven, state-driven), infers applicability rules, builds requirement relationship graphs 29 unit SHALL/MUST detection
GovernanceIndexer Scans directory for runbooks, builds inverted keyword index, caches parsed results 13 unit Fast keyword search
ProjectClassifier Classifies into 6 project types (enterprise-ai, high-risk-ai, regulatory-compliance, poc-pilot, customer-facing-ai, generative-ai), custom rules 17 unit Priority-ordered rule evaluation
ContextManager Tracks 6 development stages with validated transitions, maintains compliance status, orchestrates governance gates with stage-specific artifacts 28 unit Gate status tracking
ComplianceValidator Extensible rule engine, built-in rules for privacy/audit/error handling/docs, violation severity + remediation guidance 23 unit (AST analysis pending) Custom rule registration

Key Engineering Choices

Why blue-green index swapping for policy updates?+

A governance service has an unusual constraint: policy updates must not interrupt in-flight validation requests. If a team's CI/CD pipeline is mid-validation when a policy push triggers a re-index, the validation must complete against a consistent index — not a partially-rebuilt one. Blue-green indexing solves this: the new index is built completely in a background slot, validated for correctness, then atomically swapped as the live index. Any requests that started against the old index complete against it; new requests immediately see the updated policy. The last 5 successful indexes are retained, making rollback to any specific commit a single atomic operation.

How does multi-tenant isolation work without schema-per-tenant?+

Schema-per-tenant (one PostgreSQL schema per customer) is operationally expensive at scale — 100 tenants means 100 schema migration runs. Instead, the design uses row-level isolation: every table has a tenant_id column and every query is forced through the TenantManager which injects the tenant filter. Redis uses per-tenant key namespacing ({tenantId}:governance: prefix) for cache and distributed locks. The filesystem isolation gives each tenant a separate directory for cloned governance repositories — their policies never touch another tenant's index. This approach scales to thousands of tenants with a single database schema migration.

Why a hybrid client SDK rather than requiring the agent?+

A SaaS agent that CI/CD pipelines depend on is a hard dependency — if the agent goes down, builds break. The hybrid SDK eliminates this: auto mode tries the agent first for the latest centrally-managed policies, but falls back to the embedded library if the agent is unreachable. The library uses the governance files checked into the consuming project's repo — slightly stale relative to the central server, but unblocking. This also gives teams a zero-infrastructure path to adopt the governance engine (library mode) and a migration path to the full SaaS offering (agent mode) with no code changes required at the adoption boundary. The SDK tracks fallback count so operators can see if library mode is being invoked unexpectedly.

Why EARS patterns for requirement extraction?+

EARS (Easy Approach to Requirements Syntax) is a structured natural language pattern for requirements that makes them machine-parseable without a formal specification language. The patterns — ubiquitous (The system shall…), event-driven (When X, the system shall…), state-driven (While Y, the system shall…) — appear naturally in governance runbooks written by compliance teams who have no knowledge of formal methods. The RequirementExtractor maps these patterns to structured objects with applicability rules, allowing the GovernanceIndexer to answer "which requirements apply to a Python ML model in the development stage?" without the compliance author having to tag anything explicitly.

Why Fastify over Express for the API server?+

Fastify has native TypeScript support, a built-in JSON schema validation layer (via Ajv), and ships with OpenAPI/Swagger plugin support without additional middleware. For a governance API where every request body shape needs to be validated and documented, Fastify's route-level schema declaration produces both runtime validation and Swagger documentation from a single source of truth. Fastify is also ~2× faster than Express in benchmarks — relevant for a validation service that may be called synchronously in developer workflows. The plugin architecture (authentication, rate limiting, CORS) integrates cleanly without the middleware ordering fragility common in Express applications.

What's left — what would the next sprint ship?+
  • AST-based code analysis in ComplianceValidator — static analysis of Python/TypeScript/Java source files against governance rules (e.g., verify audit logging is present in all API handlers)
  • Property-based tests for the agent layer — the library has fast-check PBT; the agent endpoints need similar coverage for edge cases in webhook replay prevention and concurrent policy updates
  • Billing + usage metering — TenantManager tracks statistics but there's no metered billing integration (Stripe, Azure Marketplace billing)
  • IDE extension integration — the SDK is ready but Kiro/VS Code extension entry points need to be wired to the SDK's auto mode so developers get inline governance feedback while writing code
  • Helm chart / Kubernetes deployment — Docker Compose covers local dev; a production Helm chart with horizontal pod autoscaling for the validation workload hasn't been written yet
Source Platform ↗ Azure Deployment ↗ AWS Deployment ↗ All Projects ↗