{"_id":"@aibos/docs-registry","_rev":"2-37c12da699848a93dd3148548743c9ad","name":"@aibos/docs-registry","dist-tags":{"latest":"0.1.1"},"versions":{"0.1.0":{"name":"@aibos/docs-registry","version":"0.1.0","keywords":["aibos","governance","documentation","registry","schema","zod"],"author":{"name":"AIBOS"},"license":"MIT","_id":"@aibos/docs-registry@0.1.0","maintainers":[{"name":"aibos88","email":"jackwee2020@gmail.com"}],"homepage":"https://github.com/pohlai88/NEXUS-KERNEL#readme","bugs":{"url":"https://github.com/pohlai88/NEXUS-KERNEL/issues"},"dist":{"shasum":"f211c30f0bdd36c93c7b7a2fce591f136c27d5eb","tarball":"https://registry.npmjs.org/@aibos/docs-registry/-/docs-registry-0.1.0.tgz","fileCount":86,"integrity":"sha512-wU4RjQLWjIezBtpCYqzNdHdyuOsiHrMuZ1yaX9wsGeWyEOnfVX5CD6goJf3maX4nbBPHeDFEo79aAmu99EIlvg==","signatures":[{"sig":"MEUCIAdm7j8tFV4enbgWwlrVpA48JyUk24BK6DyFA9dRgZFDAiEA/M6J5WQXgGIJrmYp1OfTgz5XMYlTVP2mxjwf54sFUj8=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":219942},"main":"./dist/index.js","type":"module","_from":"file:aibos-docs-registry-0.1.0.tgz","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.18"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./schema":{"types":"./dist/schema/index.d.ts","import":"./dist/schema/index.js"},"./templates":{"types":"./dist/templates/index.d.ts","import":"./dist/templates/index.js"},"./constitution":{"default":"./constitution/constitution.machine.json"}},"scripts":{"gen":"tsx src/scripts/gen-docs.ts","test":"vitest run","build":"pnpm gen:schema && tsc && pnpm postbuild","clean":"rm -rf dist","audit:all":"pnpm audit:constitution && pnpm gen:schema && pnpm audit:schema && pnpm audit:derived && pnpm gen && pnpm audit:index && pnpm audit:checksum && pnpm audit:orphans","postbuild":"node -e \"const fs=require('fs');fs.mkdirSync('dist/templates',{recursive:true});fs.copyFileSync('src/templates/header.md.hbs','dist/templates/header.md.hbs');console.log('✅ Copied header.md.hbs to dist/templates/')\"","typecheck":"tsc --noEmit","gen:schema":"tsx src/scripts/gen-schema.ts","audit:index":"tsx src/scripts/audit-index.ts","audit:schema":"tsx src/scripts/audit-schema.ts","audit:derived":"tsx src/scripts/audit-derived.ts","audit:orphans":"tsx src/scripts/audit-orphans.ts","audit:breaking":"tsx src/scripts/audit-breaking.ts","audit:checksum":"tsx src/scripts/audit-checksum.ts","audit:constitution":"tsx src/scripts/audit-constitution.ts"},"_npmUser":{"name":"aibos88","email":"jackwee2020@gmail.com"},"_resolved":"C:\\Users\\dlbja\\AppData\\Local\\Temp\\9c884083b7c393493eca461ddb98e5f6\\aibos-docs-registry-0.1.0.tgz","_integrity":"sha512-wU4RjQLWjIezBtpCYqzNdHdyuOsiHrMuZ1yaX9wsGeWyEOnfVX5CD6goJf3maX4nbBPHeDFEo79aAmu99EIlvg==","repository":{"url":"git+https://github.com/pohlai88/NEXUS-KERNEL.git","type":"git","directory":"packages/docs-registry"},"_npmVersion":"10.9.3","description":"Document governance SDK — schemas, generation, audits, and standard packs for AIBOS governance documents","directories":{},"_nodeVersion":"22.20.0","dependencies":{"zod":"^3.24.1","handlebars":"^4.7.8"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"ajv":"^8.17.1","tsx":"^4.21.0","glob":"^13.0.0","vitest":"^2.0.0","typescript":"^5.6.3","@types/node":"^20.19.27"},"_npmOperationalInternal":{"tmp":"tmp/docs-registry_0.1.0_1767247965768_0.14533178219977905","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@aibos/docs-registry","version":"0.1.1","description":"Document governance SDK — schemas, generation, audits, and standard packs for AIBOS governance documents","type":"module","main":"./dist/index.js","module":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"import":"./dist/index.js","types":"./dist/index.d.ts"},"./schema":{"import":"./dist/schema/index.js","types":"./dist/schema/index.d.ts"},"./templates":{"import":"./dist/templates/index.js","types":"./dist/templates/index.d.ts"}},"scripts":{"build":"tsc","typecheck":"tsc --noEmit","test":"vitest run","clean":"rm -rf dist","gen":"tsx src/scripts/gen-docs.ts","audit:index":"tsx src/scripts/audit-index.ts","audit:checksum":"tsx src/scripts/audit-checksum.ts","audit:orphans":"tsx src/scripts/audit-orphans.ts","audit:all":"pnpm gen && pnpm audit:index && pnpm audit:checksum && pnpm audit:orphans","mcp:server":"tsx src/mcp/server.ts","prepublishOnly":"pnpm build","prepack":"pnpm build"},"keywords":["aibos","governance","documentation","registry","schema","zod"],"author":{"name":"AIBOS"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/pohlai88/NEXUS-DOCS-REGISTRY.git"},"homepage":"https://github.com/pohlai88/NEXUS-DOCS-REGISTRY#readme","bugs":{"url":"https://github.com/pohlai88/NEXUS-DOCS-REGISTRY/issues"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"engines":{"node":">=18.0.0"},"sideEffects":false,"dependencies":{"@modelcontextprotocol/sdk":"^1.25.1","zod":"^3.24.1"},"devDependencies":{"@types/node":"^20.19.27","glob":"^13.0.0","handlebars":"^4.7.8","tsx":"^4.21.0","typescript":"^5.6.3"},"peerDependencies":{"handlebars":"^4.7.0"},"peerDependenciesMeta":{"handlebars":{"optional":true}},"_id":"@aibos/docs-registry@0.1.1","gitHead":"a208fba9629b43ad31eb36358c48c9291d24b686","_nodeVersion":"22.20.0","_npmVersion":"10.9.3","dist":{"integrity":"sha512-jEYV8PIhPr9X5Cz/qCzFRgxl2CdAowQRGXsE5t8jMuCDLR/nZpCTPMpbmUbQW/VUmrkuyBg3AglqzYyo/2SNXQ==","shasum":"e53c91271dc58ad5c2a271afccc90c406b85115d","tarball":"https://registry.npmjs.org/@aibos/docs-registry/-/docs-registry-0.1.1.tgz","fileCount":65,"unpackedSize":198718,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIGxIA1RAtmOAyQUD/ga+G0yTODby1oL/RAlg+wJLZ3zlAiBg6uIPjo+vmGy2GHi6HQmwQBhLLyzgzaf6xWIuKEM8zw=="}]},"_npmUser":{"name":"aibos88","email":"jackwee2020@gmail.com"},"directories":{},"maintainers":[{"name":"aibos88","email":"jackwee2020@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/docs-registry_0.1.1_1767276882259_0.08731207995720669"},"_hasShrinkwrap":false}},"time":{"created":"2026-01-01T06:12:45.688Z","modified":"2026-01-01T14:14:42.652Z","0.1.0":"2026-01-01T06:12:45.918Z","0.1.1":"2026-01-01T14:14:42.405Z"},"bugs":{"url":"https://github.com/pohlai88/NEXUS-DOCS-REGISTRY/issues"},"author":{"name":"AIBOS"},"license":"MIT","homepage":"https://github.com/pohlai88/NEXUS-DOCS-REGISTRY#readme","keywords":["aibos","governance","documentation","registry","schema","zod"],"repository":{"type":"git","url":"git+https://github.com/pohlai88/NEXUS-DOCS-REGISTRY.git"},"description":"Document governance SDK — schemas, generation, audits, and standard packs for AIBOS governance documents","maintainers":[{"name":"aibos88","email":"jackwee2020@gmail.com"}],"readme":"# @aibos/docs-registry\n\n> **Document Governance SDK**\n> Machine-enforceable schemas, generation, audits, and constitutional document governance for AIBOS-style systems.\n\n**TL;DR:** This package is for **governance and compliance**, not just documentation. Use it when you need machine-validated document structure, audits, checksums, and constitutional governance. If you just need to write docs, use regular Markdown tools instead.\n\n---\n\n## What This Is\n\n`@aibos/docs-registry` is an **NPM-pure governance SDK** for managing documents as **compiled artifacts**, not free-text files.\n\nIt enforces a **Human–Machine governance contract**:\n\n* **Humans own meaning** — intent, rationale, philosophy\n* **Machines own enforcement** — validation, consistency, memory\n* **Drift is expected — but never silent**\n\nThis library is designed for teams who treat documentation as **infrastructure**, not decoration.\n\n---\n\n## When Is This Package Helpful?\n\n### ✅ **Use This Package When:**\n\n1. **You need governance and compliance**\n   - Documents must be machine-validated\n   - You need to prove compliance (audits, regulations)\n   - Document lineage and authority chains matter\n   - Example: Enterprise systems, regulated industries, constitutional governance\n\n2. **You have structured document types**\n   - PRDs, ADRs, RFCs, SRS, TSD, SOP documents\n   - Documents follow a hierarchy (derive from each other)\n   - Documents need metadata (status, owners, versions)\n   - Example: Architecture documentation, product requirements, technical specs\n\n3. **You need drift detection**\n   - INDEX.md must stay in sync with filesystem\n   - Content integrity must be verified (checksums)\n   - Orphan documents must be detected\n   - Example: Large documentation sets, multi-repo documentation\n\n4. **You want machine-enforceable documentation**\n   - CI/CD must validate documents\n   - Automated audits before commits\n   - Schema validation for document metadata\n   - Example: Teams treating docs as infrastructure\n\n5. **You follow constitutional governance models**\n   - Documents derive from LAW documents\n   - RFCs propose changes to constitutional framework\n   - Clear authority chains required\n   - Example: AIBOS-style systems, constitutional document governance\n\n### ❌ **Don't Use This Package When:**\n\n1. **Simple documentation**\n   - Just need basic Markdown files\n   - No governance requirements\n   - No structured metadata needed\n   - **Use instead:** Regular Markdown, simple docs tools\n\n2. **Casual documentation**\n   - Personal projects\n   - Quick notes\n   - No compliance needs\n   - **Use instead:** Any simple documentation tool\n\n3. **You don't need validation**\n   - Documents are free-form\n   - No structure requirements\n   - No audit needs\n   - **Use instead:** Standard documentation tools (GitBook, Notion, etc.)\n\n4. **You don't need lineage**\n   - Documents don't derive from each other\n   - No authority chains\n   - No constitutional model\n   - **Use instead:** Simple documentation systems\n\n### 🤔 **Maybe Use This Package When:**\n\n- You're starting a new project and want structured documentation from day one\n- You have documentation that might need governance in the future\n- You want to experiment with constitutional document models\n- You need some structure but not full governance (you can use it partially)\n\n---\n\n## Real-World Use Cases\n\n### ✅ **Perfect Fit:**\n\n1. **Enterprise Architecture Documentation**\n   - ADRs, PRDs, SRS documents\n   - Need to track decisions and requirements\n   - Compliance and audit requirements\n\n2. **Regulated Industries**\n   - Financial services, healthcare, government\n   - Documents must be validated and auditable\n   - Clear ownership and versioning required\n\n3. **Constitutional Governance Systems**\n   - AIBOS-style systems\n   - Documents derive from constitutional LAW\n   - RFCs propose changes to framework\n\n4. **Large-Scale Documentation**\n   - Monorepos with many packages\n   - Cross-repo documentation\n   - Need INDEX synchronization\n\n### ❌ **Not a Good Fit:**\n\n1. **Personal Blogs**\n   - Just writing articles\n   - No governance needs\n   - **Better:** Jekyll, Hugo, simple Markdown\n\n2. **Simple README Files**\n   - Just project documentation\n   - No structured types\n   - **Better:** Regular Markdown\n\n3. **Quick Notes**\n   - Meeting notes, personal docs\n   - No validation needed\n   - **Better:** Notion, Obsidian, simple tools\n\n---\n\n## The Bottom Line\n\n**This package is helpful when:**\n- You need **governance** (not just documentation)\n- You need **machine-enforceable** document structure\n- You need **validation, audits, and compliance**\n- You follow **constitutional or hierarchical** document models\n\n**This package is NOT helpful when:**\n- You just need **simple documentation**\n- You don't need **validation or governance**\n- Your documents are **free-form and casual**\n\n**Think of it this way:**\n- **Regular docs tools** = Write and read documents\n- **This package** = Govern, validate, audit, and enforce document structure\n\nIf you're asking \"do I need this?\", you probably don't. But if you're asking \"how do I enforce document governance?\", this is the answer.\n\n---\n\n## Core Capabilities\n\n* **Zod schemas** for `doc.json` (machine-validated SSOT)\n* **Deterministic generation** of managed header blocks\n* **Checksum enforcement** for content integrity\n* **Filesystem → INDEX synchronization**\n* **Full audit pipeline** (schema, checksum, index, orphans)\n* **Standard document packs** for fast scaffolding\n\nNo runtime. No database. No services.\n**Everything is file-based, deterministic, and auditable.**\n\n---\n\n## Installation\n\n```bash\nnpm install @aibos/docs-registry\n# or\npnpm add @aibos/docs-registry\n```\n\nOptional (for template generation):\n\n```bash\nnpm install handlebars\n```\n\n---\n\n## Getting Started (5 Minutes)\n\n**Want to get started quickly?** Follow these steps:\n\n1. **Install the package** (see above)\n\n2. **Create your first document:**\n   ```bash\n   mkdir -p docs/PRD/PRD-001\n   ```\n\n3. **Create `docs/PRD/PRD-001/doc.json`:**\n   ```json\n   {\n     \"document_id\": \"PRD-001\",\n     \"document_type\": \"PRD\",\n     \"classification\": \"STANDARD\",\n     \"title\": \"My First Document\",\n     \"status\": \"DRAFT\",\n     \"authority\": \"DERIVED\",\n     \"scope\": \"KERNEL\",\n     \"derived_from\": [],\n     \"version\": \"0.1.0\",\n     \"owners\": [\"Your Name\"],\n     \"checksum_sha256\": null,\n     \"created_at\": \"2026-01-01\",\n     \"updated_at\": \"2026-01-01\"\n   }\n   ```\n\n4. **Create `docs/PRD/PRD-001/doc.md`:**\n   ```markdown\n   # PRD-001 — My First Document\n   \n   Your content here.\n   ```\n\n5. **Generate managed blocks:**\n   ```ts\n   import { generateDocs } from \"@aibos/docs-registry\";\n   await generateDocs({ docsDir: \"docs\" });\n   ```\n\n6. **Generate INDEX:**\n   ```ts\n   import { generateIndex } from \"@aibos/docs-registry\";\n   await generateIndex({ docsDir: \"docs\" });\n   ```\n\n7. **Run audit:**\n   ```ts\n   import { auditAll } from \"@aibos/docs-registry\";\n   const result = await auditAll({ docsDir: \"docs\" });\n   console.log(result.passed ? \"✅ All good!\" : \"❌ Issues found\");\n   ```\n\n**That's it!** You now have a governed document system.\n\n---\n\n## Conceptual Model (MITL)\n\nThis SDK implements a **Machine-In-The-Loop (MITL)** governance model:\n\n```\nHuman Intent (Philosophy)\n        ↓\nMachine Contracts (Schemas)\n        ↓\nDeterministic Generation\n        ↓\nAudit & Drift Detection\n```\n\nDocuments are not \"written\".\nThey are **compiled**.\n\n---\n\n## Constitutional Model\n\nThis SDK supports a **3-Tier Constitutional Model** (see `RFC-KERNEL-001`):\n\n### Important: Constitution vs LAW\n\n- **Constitution** = The overall 3-Tier Constitutional Model (the framework/system)\n- **LAW** = Individual constitutional law documents (e.g., `LAW-001`, `LAW-002`)\n- **Constitutional Laws** = The collection of all LAW documents that form the foundation\n\n**Think of it this way:**\n- The **Constitution** is the model/framework (like a country's constitution)\n- **LAW documents** are individual laws within that constitution (like articles/amendments)\n\n### Tier 1: Constitutional Laws (LAW Documents)\n- **Foundational philosophy** — Human truths that rarely change\n- **Example:** `LAW-001` — A foundational constitutional law\n- **Purpose:** Define culture, philosophy, and intent\n- **Note:** Multiple LAW documents can exist (LAW-001, LAW-002, etc.)\n\n### Tier 2: Enforcement Doctrines\n- **Required mechanisms** — Non-optional mechanics to enforce Tier 1\n- **Example:** Registry is the sole semantic authority\n- **Purpose:** Make constitutional laws real and enforceable\n\n### Tier 3: Enforcement Surface\n- **Execution reality** — Required capabilities and enforcement gates\n- **Example:** Semantic registry validation, override creation\n- **Purpose:** Provide concrete mechanisms for governance\n\n### RFC's Role in Constitutional Evolution\n\n**RFC (Request for Comments)** is the mechanism for proposing changes to the Constitution or new LAW documents:\n\n- **RFCs derive from LAW** — All RFCs must reference existing LAW documents (e.g., `LAW-001`)\n- **RFCs propose changes** — They suggest new constitutional structures, new LAW documents, or modifications\n- **RFCs can become LAW** — When approved, RFCs can become new LAW documents\n- **Example:** `RFC-KERNEL-001` proposes the 3-Tier Constitutional Model itself (derived from `LAW-001`)\n\n**Constitutional Flow:**\n\n```\nLAW-001 (A foundational constitutional law)\n    ↓\nRFC-KERNEL-001 (Proposes 3-Tier Model) ← Derived from LAW-001\n    ↓\n[If approved] → May become LAW-002 or part of constitutional framework\n    ↓\nOther documents derive from LAW documents\n```\n\n**Why This Matters:**\n\n- **Constitutional stability** — LAW documents rarely change, preserving foundational truths\n- **Controlled evolution** — RFCs provide a formal process for proposing new LAW documents or constitutional changes\n- **Clear lineage** — Every document traces back to LAW documents (the constitutional foundation)\n- **Machine-enforceable** — This SDK enforces the constitutional model via schemas\n\n---\n\n## Document Structure\n\nEach document lives in its own folder:\n\n```\ndocs/<TYPE>/<DOC-ID>/\n  doc.json   ← Machine-validated metadata (SSOT)\n  doc.md     ← Human content + managed block\n```\n\n### doc.json (SSOT)\n\n```json\n{\n  \"document_id\": \"PRD-EXAMPLE-001\",\n  \"document_type\": \"PRD\",\n  \"classification\": \"STANDARD\",\n  \"title\": \"Example Product Requirements\",\n  \"status\": \"DRAFT\",\n  \"authority\": \"DERIVED\",\n  \"scope\": \"KERNEL\",\n  \"derived_from\": [\"LAW-001\"],\n  \"version\": \"0.1.0\",\n  \"owners\": [\"Your Name\"],\n  \"checksum_sha256\": null,\n  \"created_at\": \"2026-01-01\",\n  \"updated_at\": \"2026-01-01\"\n}\n```\n\nThis file is the **single source of truth**.\n`doc.md` is derived.\n\n---\n\n## Managed Blocks (Generated)\n\nThe SDK injects a **managed header block** into `doc.md`:\n\n```markdown\n<!-- BEGIN: AIBOS_MANAGED -->\n\n| Field           | Value           |\n| --------------- | --------------- |\n| **Document ID** | PRD-EXAMPLE-001 |\n| **Status**      | DRAFT           |\n| **Version**     | 0.1.0           |\n\n<!-- END: AIBOS_MANAGED -->\n```\n\nRules:\n\n* Content **inside** the block is machine-owned\n* Content **outside** the block is human-owned\n* Manual edits inside the block are **overwritten**\n\n---\n\n## Quick Start\n\n### Step 1: Install the Package\n\n```bash\nnpm install @aibos/docs-registry\n# or\npnpm add @aibos/docs-registry\n```\n\n### Step 2: Set Up Your Document Structure\n\nCreate a `docs` folder with your document structure:\n\n```\ndocs/\n├── PRD/\n│   └── PRD-001/\n│       ├── doc.json    ← Create this first\n│       └── doc.md      ← Create this second\n└── ADR/\n    └── ADR-001/\n        ├── doc.json\n        └── doc.md\n```\n\n### Step 3: Create Your First Document\n\n**Create `docs/PRD/PRD-001/doc.json`:**\n\n```json\n{\n  \"document_id\": \"PRD-001\",\n  \"document_type\": \"PRD\",\n  \"classification\": \"STANDARD\",\n  \"title\": \"My First Product Requirements\",\n  \"status\": \"DRAFT\",\n  \"authority\": \"DERIVED\",\n  \"scope\": \"KERNEL\",\n  \"derived_from\": [],\n  \"version\": \"0.1.0\",\n  \"owners\": [\"Your Name\"],\n  \"checksum_sha256\": null,\n  \"created_at\": \"2026-01-01\",\n  \"updated_at\": \"2026-01-01\"\n}\n```\n\n**Create `docs/PRD/PRD-001/doc.md`:**\n\n```markdown\n# PRD-001 — My First Product Requirements\n\nYour content goes here. The managed block will be automatically generated.\n```\n\n### Step 4: Generate Managed Blocks\n\n```ts\nimport { generateDocs } from \"@aibos/docs-registry\";\n\n// This will:\n// 1. Validate all doc.json files\n// 2. Generate managed header blocks in doc.md files\n// 3. Calculate checksums\nawait generateDocs({ docsDir: \"docs\" });\n```\n\n**After generation, your `doc.md` will have:**\n\n```markdown\n<!-- BEGIN: AIBOS_MANAGED -->\n| Field | Value |\n|---|---|\n| **Document ID** | PRD-001 |\n| **Status** | DRAFT |\n| **Version** | 0.1.0 |\n<!-- END: AIBOS_MANAGED -->\n\n# PRD-001 — My First Product Requirements\n\nYour content goes here.\n```\n\n### Step 5: Generate INDEX\n\n```ts\nimport { generateIndex } from \"@aibos/docs-registry\";\n\n// Creates docs/INDEX.md with all documents\nawait generateIndex({ docsDir: \"docs\" });\n```\n\n### Step 6: Run Audits\n\n```ts\nimport { auditAll } from \"@aibos/docs-registry\";\n\nconst result = await auditAll({ docsDir: \"docs\" });\n\nif (!result.passed) {\n  console.error(\"❌ Audit failed:\");\n  result.violations.forEach(v => {\n    console.error(`  - ${v.docId}: ${v.message}`);\n  });\n  process.exit(1);\n}\n\nconsole.log(\"✅ All checks passed\");\n```\n\n---\n\n## Common Use Cases\n\n### Use Case 1: Validate a Single Document\n\n```ts\nimport { DocJsonSchema } from \"@aibos/docs-registry/schema\";\nimport fs from \"node:fs\";\n\nconst raw = JSON.parse(fs.readFileSync(\"docs/PRD/PRD-001/doc.json\", \"utf8\"));\nconst result = DocJsonSchema.safeParse(raw);\n\nif (!result.success) {\n  console.error(\"Validation errors:\");\n  result.error.issues.forEach(issue => {\n    console.error(`  - ${issue.path.join(\".\")}: ${issue.message}`);\n  });\n  process.exit(1);\n}\n\nconsole.log(\"✅ Document is valid:\", result.data.document_id);\n```\n\n### Use Case 2: Create a Script to Generate All Docs\n\n**Create `scripts/generate-docs.ts`:**\n\n```ts\nimport { generateDocs, generateIndex } from \"@aibos/docs-registry\";\n\nasync function main() {\n  const docsDir = \"docs\";\n  \n  console.log(\"📄 Generating documents...\");\n  await generateDocs({ docsDir });\n  \n  console.log(\"📑 Generating INDEX...\");\n  await generateIndex({ docsDir });\n  \n  console.log(\"✅ Done!\");\n}\n\nmain().catch(console.error);\n```\n\n**Add to `package.json`:**\n\n```json\n{\n  \"scripts\": {\n    \"docs:generate\": \"tsx scripts/generate-docs.ts\"\n  }\n}\n```\n\n**Run it:**\n\n```bash\nnpm run docs:generate\n```\n\n### Use Case 3: CI/CD Integration\n\n**Create `.github/workflows/docs-audit.yml`:**\n\n```yaml\nname: Document Audit\n\non: [push, pull_request]\n\njobs:\n  audit:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - uses: pnpm/action-setup@v2\n      - uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n      - run: pnpm install\n      - run: pnpm docs:generate\n      - run: pnpm docs:audit\n```\n\n**Add audit script to `package.json`:**\n\n```json\n{\n  \"scripts\": {\n    \"docs:audit\": \"tsx -e \\\"import('@aibos/docs-registry').then(m => m.auditAll({ docsDir: 'docs' }).then(r => { if (!r.passed) { console.error('Audit failed'); process.exit(1); } }))\\\"\"\n  }\n}\n```\n\n### Use Case 4: Create Documents Programmatically\n\n```ts\nimport { DocJsonSchema, type DocJson } from \"@aibos/docs-registry/schema\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nasync function createDocument(\n  docId: string,\n  docType: string,\n  title: string,\n  content: string\n) {\n  const docDir = path.join(\"docs\", docType, docId);\n  fs.mkdirSync(docDir, { recursive: true });\n\n  // Create doc.json\n  const docJson: DocJson = {\n    document_id: docId,\n    document_type: docType,\n    classification: \"STANDARD\",\n    title,\n    status: \"DRAFT\",\n    authority: \"DERIVED\",\n    scope: \"KERNEL\",\n    derived_from: [],\n    version: \"0.1.0\",\n    owners: [\"System\"],\n    checksum_sha256: null,\n    created_at: new Date().toISOString().split(\"T\")[0],\n    updated_at: new Date().toISOString().split(\"T\")[0],\n  };\n\n  // Validate\n  const result = DocJsonSchema.safeParse(docJson);\n  if (!result.success) {\n    throw new Error(`Invalid document: ${result.error.message}`);\n  }\n\n  // Write files\n  fs.writeFileSync(\n    path.join(docDir, \"doc.json\"),\n    JSON.stringify(docJson, null, 2)\n  );\n  fs.writeFileSync(path.join(docDir, \"doc.md\"), content);\n\n  // Generate managed blocks\n  const { generateDocs } = await import(\"@aibos/docs-registry\");\n  await generateDocs({ docsDir: \"docs\" });\n\n  console.log(`✅ Created document: ${docId}`);\n}\n\n// Usage\nawait createDocument(\n  \"PRD-002\",\n  \"PRD\",\n  \"New Feature Requirements\",\n  \"# PRD-002 — New Feature Requirements\\n\\nFeature description...\"\n);\n```\n\n### Use Case 5: Check Document Status\n\n```ts\nimport { discoverDocs } from \"@aibos/docs-registry\";\n\nconst docs = await discoverDocs(\"docs\");\n\nconsole.log(\"Document Status:\");\ndocs.forEach(doc => {\n  console.log(`  ${doc.docId}: ${doc.docJson.status} (v${doc.docJson.version})`);\n});\n```\n\n---\n\n## Complete Example: Full Workflow\n\nHere's a complete example showing the full workflow:\n\n```ts\nimport {\n  generateDocs,\n  generateIndex,\n  auditAll,\n  discoverDocs,\n} from \"@aibos/docs-registry\";\n\nasync function main() {\n  const docsDir = \"docs\";\n\n  // 1. Discover all documents\n  console.log(\"📋 Discovering documents...\");\n  const docs = await discoverDocs(docsDir);\n  console.log(`   Found ${docs.length} documents`);\n\n  // 2. Generate managed blocks and checksums\n  console.log(\"📄 Generating managed blocks...\");\n  const genResult = await generateDocs({ docsDir });\n  console.log(`   Processed: ${genResult.processed} documents`);\n  console.log(`   Updated: ${genResult.updated.length} documents`);\n\n  // 3. Generate INDEX\n  console.log(\"📑 Generating INDEX...\");\n  await generateIndex({ docsDir });\n  console.log(\"   ✅ INDEX.md created\");\n\n  // 4. Run full audit\n  console.log(\"🔍 Running audit...\");\n  const auditResult = await auditAll({ docsDir });\n\n  if (auditResult.passed) {\n    console.log(\"   ✅ All checks passed\");\n  } else {\n    console.error(\"   ❌ Audit failed:\");\n    auditResult.violations.forEach(v => {\n      console.error(`      - ${v.docId}: ${v.message}`);\n    });\n    process.exit(1);\n  }\n\n  console.log(\"\\n✅ All operations completed successfully!\");\n}\n\nmain().catch(console.error);\n```\n\n---\n\n## Audit Guarantees\n\n| Check      | Guarantee                            |\n| ---------- | ------------------------------------ |\n| Schema     | All `doc.json` pass Zod validation   |\n| Checksum   | Content hash matches stored checksum |\n| INDEX → FS | Every INDEX entry exists             |\n| FS → INDEX | No undocumented files                |\n| Orphans    | No stray documents                   |\n| Drift      | All violations are explicit          |\n\n**Nothing passes silently.**\n\n---\n\n## Document Types\n\n| Type | Level | Purpose                     | Authority Chain                              |\n| ---- | ----- | --------------------------- | -------------------------------------------- |\n| LAW  | 1     | Constitutional law documents | Original (constitutional foundation)         |\n| RFC  | —     | Proposals (pre-decision)     | Derived from LAW (proposes new LAW or changes) |\n| PRD  | 2     | Product intent & boundaries  | Derived from LAW/RFC                         |\n| SRS  | 3     | System requirements         | Derived from PRD                             |\n| ADR  | 4     | Architecture decisions      | Derived from SRS                             |\n| TSD  | 5     | Technical specification     | Derived from ADR                              |\n| SOP  | 6     | Operating procedures        | Derived from TSD                              |\n\n**Note:** The **Constitution** is the overall 3-Tier Constitutional Model framework. **LAW** documents are individual constitutional laws within that framework.\n\n### Document Hierarchy & Authority\n\nDocuments follow a **constitutional hierarchy**:\n\n```\nConstitution (3-Tier Model)\n  ↓\nLAW Documents (e.g., LAW-001, LAW-002) ← Constitutional foundation\n  ↓\nRFC (Proposals) ← Proposes new LAW documents or constitutional changes\n  ↓\nPRD (Product Requirements)\n  ↓\nSRS (System Requirements)\n  ↓\nADR (Architecture Decisions)\n  ↓\nTSD (Technical Specifications)\n  ↓\nSOP (Operating Procedures)\n```\n\n**Key Relationships:**\n\n- **Constitution** = The overall 3-Tier Constitutional Model (the framework)\n- **LAW** = Individual constitutional law documents (e.g., `LAW-001`, `LAW-002`)\n  - LAW documents form the constitutional foundation\n  - They rarely change, preserving foundational truths\n- **RFC** = Proposals that may become new LAW documents or propose constitutional changes\n  - Example: `RFC-KERNEL-001` proposes the 3-Tier Constitutional Model itself\n  - RFCs derive from existing LAW documents (e.g., `LAW-001`)\n- **All other types** derive from LAW documents (directly or via RFC)\n\n**Example Flow:**\n\n1. **LAW-001** exists as a foundational constitutional law\n2. **RFC-KERNEL-001** proposes the 3-Tier Constitutional Model (derived from `LAW-001`)\n3. If approved, RFC may become a new LAW document (e.g., `LAW-002`) or part of the constitutional framework\n4. **PRD-DOCSREG-001** derives from `LAW-001` and `RFC-DOCSREG-001`\n5. **SRS-DOCSREG-001** derives from `PRD-DOCSREG-001`\n6. And so on down the hierarchy\n\n**Why RFC Matters:**\n\n- RFCs are **proposals** before they become LAW documents or other document types\n- They allow **constitutional evolution** without breaking existing LAW documents\n- They provide a **formal process** for proposing new LAW documents or structural changes\n- They maintain **lineage** back to LAW documents (the constitutional foundation)\n\n---\n\n## API Reference\n\n### Main Exports\n\n**From `@aibos/docs-registry`:**\n\n```ts\nimport {\n  // Generation\n  generateDocs,        // Generate managed blocks and checksums\n  generateIndex,       // Generate INDEX.md\n  \n  // Auditing\n  auditAll,            // Run all audits\n  auditIndex,          // Audit INDEX sync\n  auditChecksum,       // Audit checksums\n  auditOrphans,        // Find orphan documents\n  \n  // Discovery\n  discoverDocs,        // Scan and discover documents\n  \n  // Utilities\n  computeChecksum,     // Calculate content checksum\n  normalizeContent,   // Normalize content for checksum\n} from \"@aibos/docs-registry\";\n```\n\n**From `@aibos/docs-registry/schema`:**\n\n```ts\nimport {\n  // Schemas\n  DocJsonSchema,       // Validate doc.json\n  \n  // Types\n  DocumentType,        // \"PRD\" | \"ADR\" | \"SRS\" | etc.\n  DocumentStatus,      // \"DRAFT\" | \"APPROVED\" | etc.\n  AuthorityLevel,      // \"DERIVED\" | \"ORIGINAL\" | etc.\n  \n  // TypeScript Types\n  type DocJson,        // TypeScript type for doc.json\n} from \"@aibos/docs-registry/schema\";\n```\n\n### Configuration\n\n```ts\ninterface DocsRegistryConfig {\n  docsDir: string;              // Required: Path to docs directory\n  templatesDir?: string;        // Optional: Custom templates directory\n  checksumAlgorithm?: \"sha256\"; // Optional: Checksum algorithm (default: sha256)\n}\n```\n\n### Function Signatures\n\n#### `generateDocs(config: DocsRegistryConfig): Promise<GenerateResult>`\n\nGenerates managed blocks and calculates checksums for all documents.\n\n**Returns:**\n```ts\n{\n  processed: number;      // Total documents processed\n  updated: string[];      // Document IDs that were updated\n  errors: Array<{         // Errors encountered\n    docId: string;\n    error: string;\n  }>;\n}\n```\n\n#### `generateIndex(config: DocsRegistryConfig): Promise<void>`\n\nGenerates `INDEX.md` from discovered documents.\n\n#### `auditAll(config: DocsRegistryConfig): Promise<AuditResult>`\n\nRuns all audit checks (schema, checksum, index, orphans).\n\n**Returns:**\n```ts\n{\n  passed: boolean;\n  violations: Array<{\n    docId: string;\n    check: string;        // \"schema\" | \"checksum\" | \"index\" | \"orphan\"\n    message: string;\n  }>;\n}\n```\n\n#### `discoverDocs(docsDir: string): Promise<DiscoveredDoc[]>`\n\nScans filesystem and discovers all documents.\n\n**Returns:**\n```ts\nArray<{\n  docId: string;\n  docJson: DocJson;\n  docJsonPath: string;\n  docMdPath: string;\n}>\n```\n\n---\n\n## Governance Rules (Non-Negotiable)\n\n### ✅ DO\n\n* Treat `doc.json` as SSOT\n* Generate, never hand-edit managed blocks\n* Run audits before commit\n* **Use RFCs for structural change** — Propose constitutional changes via RFC\n* **Derive from LAW** — All documents must trace back to LAW documents (the constitutional foundation)\n* **Maintain lineage** — Always specify `derived_from` in `doc.json`\n\n### ❌ DON'T\n\n* Edit generated sections\n* Skip audits\n* Rely on tribal memory\n* Treat docs as free-text\n* **Create documents without constitutional lineage** — Always derive from LAW or RFC\n* **Change LAW documents directly** — Use RFC to propose new LAW documents or constitutional changes\n\n---\n\n## Troubleshooting\n\n### Common Issues\n\n#### Issue: \"Document validation failed\"\n\n**Solution:** Check your `doc.json` structure. Use the schema:\n\n```ts\nimport { DocJsonSchema } from \"@aibos/docs-registry/schema\";\n\nconst result = DocJsonSchema.safeParse(yourDocJson);\nif (!result.success) {\n  console.error(result.error.issues);\n}\n```\n\n#### Issue: \"Checksum mismatch\"\n\n**Solution:** Regenerate the document:\n\n```ts\nawait generateDocs({ docsDir: \"docs\" });\n```\n\nThis will recalculate checksums based on current content.\n\n#### Issue: \"INDEX out of sync\"\n\n**Solution:** Regenerate the INDEX:\n\n```ts\nawait generateIndex({ docsDir: \"docs\" });\n```\n\n#### Issue: \"Orphan documents found\"\n\n**Solution:** Either:\n1. Add the document to INDEX by regenerating it\n2. Remove the orphan document if it's not needed\n\n#### Issue: \"Module not found\" errors\n\n**Solution:** Make sure you're using the correct import paths:\n\n```ts\n// ✅ Correct\nimport { generateDocs } from \"@aibos/docs-registry\";\nimport { DocJsonSchema } from \"@aibos/docs-registry/schema\";\n\n// ❌ Wrong\nimport { generateDocs } from \"@aibos/docs-registry/core\";\n```\n\n### Need Help?\n\n- Check the [examples in the `docs/` folder](./docs/) in this package\n- Review the [API Reference](#api-reference) below\n- Open an [issue on GitHub](https://github.com/pohlai88/NEXUS-DOCS-REGISTRY/issues)\n\n---\n\n## Design Philosophy\n\nThis SDK is intentionally strict.\n\nIt exists to eliminate:\n\n* Silent drift\n* Broken lineage\n* Inconsistent documents\n* \"Out-of-date but nobody noticed\" failures\n\nIf you want flexibility, use Markdown.\nIf you want **governance**, use this.\n\n---\n\n## License\n\nMIT\n\n---\n\n### Final Recommendation\n\n* ✅ **This README is npm-ready**\n* ✅ **No workspace / pnpm leakage**\n* ✅ **Single authoritative narrative**\n* ✅ **Matches your Kernel-first doctrine**\n\nIf you want, next I can:\n\n* Produce a **README diff** against your original\n* Split **“Constitution”** into a separate advanced doc\n* Create a **minimal README** + **full docs site version**\n\nJust say the word.\n","readmeFilename":"README.md"}