diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..83fb659 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,17 @@ +## Summary + +Describe the problem, resulting behavior, and task scope. + +## Compatibility and authority + +Describe public API, collection audience, approval/evidence, and private-data +impacts. Explain any new host prerequisites or artifact/release consequences. + +## Validation + +- [ ] `pnpm run format:check` +- [ ] `pnpm run check` +- [ ] `pnpm test` +- [ ] `pnpm run release:check` +- [ ] Current-head Node 22/24, review, and security gates +- [ ] No private host internals or real customer data diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8431906 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + validate: + name: Node.js ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [22, 24] + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.34.5 + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: ${{ matrix.node-version }} + cache: pnpm + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Check formatting + run: pnpm run format:check + - name: Check types + run: pnpm run check + - name: Run tests + run: pnpm test + - name: Check package artifacts + run: pnpm run release:check diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..16d1699 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,34 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: "27 8 * * 1" + +permissions: + contents: read + security-events: write + +concurrency: + group: codeql-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + analyze: + name: Analyze JavaScript and TypeScript + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Initialize CodeQL + uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + with: + languages: javascript-typescript + - name: Build + uses: github/codeql-action/autobuild@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + - name: Analyze + uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 diff --git a/.gitignore b/.gitignore index 1301e01..541587e 100644 --- a/.gitignore +++ b/.gitignore @@ -127,6 +127,7 @@ dist # pnpm .pnpm-store +.release/ # yarn v3 .pnp.* diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..0e23e3f --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +dist/ +coverage/ +artifacts/ +pnpm-lock.yaml diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..926c5dc --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,52 @@ +# Working in this repository + +Knowledge Base is a standalone MIT Pegma component. Optimize for a fresh agent +context: small typed contracts, explicit composition, and meaningful public-API +tests. The approved scope is the [Support Desk enhancement plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md). + +## Boundaries + +- Contracts and core own collection policy, immutable article revisions, + validation/evidence bindings, approval, publication, and retirement. +- KB-01 is pure domain work. Storage, authorized services, retrieval, API/MCP, + and host interfaces are later tasks; do not create their packages early. +- Never implement a database, authorization role model, identity/session/token + system, audit log, request limiter, or durable scheduler here. Compose the + corresponding Pegma package in the owning later task. +- Reuse Spine's identity/time types. Pin exact released Pegma versions. A host + cannot consume an unpublished package through a branch, copied source, or a + local path as a production release substitute. +- Collections own all access policy. Articles inherit it without ACL overrides. + Portal visibility and approved bot-answer audiences are independent; private + is the default. Public access requires an explicit reviewed policy change. +- Approval binds exact content, revision, audience/policy, applicability, + validation policy, and evidence. Edits and changed authority invalidate it. + A `passed` string or claimed runner identity does not authenticate evidence. +- Core transitions are not an authorization boundary. The later application + must authenticate/authorize the actor, attestations, and current resources. +- Base packages require no Support Desk, GitHub, model, framework, HTTP, or + provider SDK. Evidence is data; never execute code or fetch submitted URLs. +- Constrain content and links; host renderers must disable executable content + and raw HTML. Staff evidence/provenance never enters customer or bot DTOs. +- Use fictional fixtures only. Commercial host internals, credentials, customer + content, and operational configuration stay in their owning private systems. +- Never write literal control bytes into source. Use escaped forms and verify + bytes after tool-assisted edits. + +## Workflow + +Work on a `claude/*` branch and open a PR. Required checks are +`pnpm run format:check`, `pnpm run check`, `pnpm test`, and +`pnpm run release:check`, on Node 22 and 24. Run the applicable review/security +checks for the current head. Do not bypass pending, skipped, or failing gates. + +Each published package needs its own README and MIT LICENSE, a build-on-prepack +script, and compiled-test exclusion. Merging source does not publish packages. +See [release operations](docs/RELEASING.md); first publication and external +trusted-publisher configuration are separate maintainer operations. + +## Reading order + +Read this file, the root README, then the owning package README. The public +enhancement plan defines KB-01 through KB-05. Give a worker one task and an +explicit file ownership boundary; do not revert another worker's edits. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e973b7 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# Knowledge Base + +A standalone MIT Pegma component for product documentation and support knowledge. +Hosts own their users, storage, authorization policy, interfaces, and deployment. +Knowledge Base owns collection policy, immutable article revisions, validation, +and exact publication approval. It requires no GitHub connection or AI provider. + +> Development status: KB-01 implements contracts and pure domain transitions. +> The packages are unpublished. Authorized persistence, retrieval, API/MCP, +> and customer/staff interfaces are later tasks. This repository is not yet an +> operational knowledge-base service or a production dependency. + +| Package | Scope | +| ----------------------------------------------------------------- | ------------------------------------------------------ | +| [`@pegma/knowledge-base-contracts`](packages/contracts/README.md) | Collection, article, evidence, and approval vocabulary | +| [`@pegma/knowledge-base-core`](packages/core/README.md) | Pure validation and lifecycle transitions | + +Collections default to private and independently specify portal and bot-answer +audiences. Articles inherit collection policy. Staff approval binds the exact +revision, content, collection policy, applicability, validation requirements, +and evidence. A revised guide requires fresh review; prior publication never +authorizes edited content. + +Core transitions accept explicit inputs and return new values. They do not +authenticate a runner or staff member, enforce host roles, fetch evidence URLs, +or execute guide steps. Later application services must enforce current +Authorization Core permissions and authenticated attestation boundaries. +Local agents will test guides against authorized staging and submit evidence +through the later API/MCP adapter. + +Develop on Node 22 or 24 with pnpm 10.34.5: + +```sh +pnpm install --frozen-lockfile +pnpm run format:check +pnpm run check +pnpm test +pnpm run release:check +``` + +The npm and pnpm workspace declarations deliberately name the same two source +packages: pnpm links them for development, while npm supplies artifact packing. +The release check installs both tarballs in a consumer outside either workspace +to verify dependency resolution without source links. + +The [approved enhancement plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md) +defines KB-01 through KB-05 and the later Support Desk/host integrations. +Its [P-00 handoff](https://github.com/pegma-dev/support-desk/pull/33) records +source/registry baselines, synthetic acceptance cases, and open activation +prerequisites. These two launch hosts use separate stores and policies; the +packages do not introduce a shared tenant control plane. + +Read [AGENTS.md](AGENTS.md) before changing code and +[release operations](docs/RELEASING.md) before preparing artifacts. Merging +source does not publish a package. Each new npm name needs the maintainer's +first publication and trusted-publisher setup before hosts can consume it. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..413ccb7 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,95 @@ +# Release operations + +## KB-01 status + +`@pegma/knowledge-base-contracts` and `@pegma/knowledge-base-core` are prepared +at synchronized version `0.1.0`. Both package names are unpublished. KB-01 +establishes packaging checks and the release handoff; it does not publish, +create tags/releases, configure credentials, or enable a publish workflow. + +Hosts must wait for an exact public registry release. Git branches, copied +source, local paths, and unpublished production tarballs are not substitutes. +The temporary tarball consumer below is a packaging test only. + +## Artifact checks + +Run the repository gate on Node 22 and 24 with the pinned pnpm version: + +```sh +pnpm install --frozen-lockfile +pnpm run format:check +pnpm run check +pnpm test +pnpm run release:check +``` + +`release:check` packs contracts and then core using npm. Each package's +`prepack` builds its own output, so a package cannot silently ship a stale +distribution. The checker verifies: + +- synchronized stable versions, exact internal/Spine pins, ESM/public metadata, + and the two declared runtime/type entry points; +- a package-local README and MIT LICENSE, a build-on-prepack script, and + exclusion of `src/**/*.test.ts` from compilation; +- npm's artifact inventory containing only package metadata, README, LICENSE, + and JavaScript/declaration output and maps under `dist`, with compiled tests + excluded and both entry-point files present; +- the actual tarball bytes against npm's reported SHA-1 and SHA-512 integrity; +- an isolated consumer installation of both tarballs and successful ESM + imports of both public packages. + +The consumer disables install scripts, audit, and funding requests and obtains +released external dependencies from the public npm registry. It has no workspace +links. The checker locates `npm-cli.js` and invokes it with Node directly on +Windows and Unix; it does not interpolate commands through a shell. Temporary +files are removed only after checking their resolved directory is the generated +child of the system temporary root. No user npm configuration is inspected or +printed. + +To keep the same verified tarballs for maintainer inspection: + +```sh +pnpm run release:pack +``` + +This runs the same checks, then writes a new `.release/knowledge-base-*` +directory containing the two tarballs and `manifest.json` with their inventory +and integrity values. Existing artifact directories are preserved. These files +are local preparation artifacts, not proof of a released version or provenance. +The checker does not verify a source tag, main ancestry, registry publication, +or trusted-publisher configuration. Those are release prerequisites below. + +## Maintainer prerequisites before first publication + +These operations remain pending and must be recorded when completed: +Recheck npm's current [trusted-publishing guidance](https://docs.npmjs.com/trusted-publishers/) +when implementing the release workflow; this checklist records the Pegma +release procedure, not proof that external publisher settings exist. + +- [ ] Confirm package-name ownership and organization publishing permissions. +- [ ] Complete KB-05's application/adapter and dual-store release criteria for + any additional packages being advertised; do not publish empty packages. +- [ ] Merge reviewed release source and exact version/pin changes to protected + `origin/main`; require every current-head review, test, build, security, + and artifact check to pass. +- [ ] Configure protection for immutable `v*` tags and approved release signers. +- [ ] Prepare and verify the exact artifacts from a protected signed annotated + `vX.Y.Z` tag whose commit is already on `origin/main`. +- [ ] The maintainer performs the new package names' one-time manual 2FA + publication of those exact verified tarballs. Choose and document the + bootstrap/first advertised release procedure before this operation. +- [ ] Configure npm trusted publishers for this repository, the reviewed future + publish workflow, and its protected publishing environment. +- [ ] Establish the future workflow: unprivileged signature/main/gate/pack + preparation, followed by a minimal environment-approved OIDC publish job + receiving only the exact prepared artifacts. +- [ ] Verify registry versions, tarball integrity, provenance, and a clean + public consumer installation before marking the packages available. + +The first-publication procedure is a maintainer operation, not a command hidden +in CI. Do not add an npm token or token-based fallback to this repository. +Merging a PR does not publish. Later releases must use the protected signed +annotated tag and trusted-publisher path, preserve published version immutability, +and recover partial publication by verifying identical existing artifacts rather +than overwriting a version. Define that workflow in the release task before +enabling publication. diff --git a/package.json b/package.json new file mode 100644 index 0000000..16ae4c1 --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "name": "knowledge-base", + "version": "0.0.0", + "private": true, + "description": "Composable product documentation and support knowledge for Pegma hosts.", + "license": "MIT", + "type": "module", + "engines": { + "node": ">=22" + }, + "workspaces": [ + "packages/*" + ], + "scripts": { + "build": "tsc -b", + "check": "tsc -b --pretty false && tsc -p tsconfig.test.json --pretty false", + "clean": "tsc -b --clean", + "format": "prettier --write .", + "format:check": "prettier --check .", + "test": "pnpm run build && vitest run", + "release:check": "node scripts/release-packages.mjs check", + "release:pack": "node scripts/release-packages.mjs pack" + }, + "devDependencies": { + "@types/node": "26.6.6", + "prettier": "3.9.10", + "typescript": "7.0.2", + "vitest": "5.0.5" + }, + "packageManager": "pnpm@10.34.5" +} diff --git a/packages/contracts/LICENSE b/packages/contracts/LICENSE new file mode 100644 index 0000000..833a7d0 --- /dev/null +++ b/packages/contracts/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pegma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/contracts/README.md b/packages/contracts/README.md new file mode 100644 index 0000000..ad7a5f7 --- /dev/null +++ b/packages/contracts/README.md @@ -0,0 +1,36 @@ +# @pegma/knowledge-base-contracts + +Provider-free collection, immutable article revision, validation evidence, and +exact approval contracts for a composable knowledge base. This package owns +permission names; the host's Authorization Core composition owns their meaning +and enforcement. Identity and time types come from `@pegma/spine`. + +Collections independently enable portal and bot use for an explicit audience. +Every article inherits its collection policy; there are no article-level access +overrides. An enabled permission audience names a permission the host resolves. +Anonymous use is representable for future opt-in publication, with an exact +public collection approval; both initial hosts keep it disabled. + +Content edits create a new immutable `ArticleRevision`. `Article` is a bounded +transition aggregate containing the current draft and at most one published +snapshot; it is not a revision archive. Application services must retain +bounded revision history separately and authorize access to it. An existing +publication can remain while an update awaits review. Retirement removes the +published snapshot from the transition result. + +`ApprovalBinding` names the exact content hash, collection audience policy, +applicability, validation policy, and evidence versions/hashes that a reviewer +approved. Evidence includes steps, a staging build, a runner, timestamps, +protected artifact references, and an attestation receipt. A `passed` result +alone is insufficient. Hashes use lowercase hexadecimal SHA-256. + +These types do not authenticate identity or prove a submitted attestation. The +later application/host boundary must authenticate the runner and reviewer, +verify the attestation against its trusted verifier, apply current permission +and resource checks, and control private evidence access. Authoring callers +cannot grant themselves publication authority by supplying these fields. + +The package does not own persistence, an access model, HTTP/MCP transports, +safe HTML rendering, arbitrary URL fetching, code execution, GitHub, or model +integration. Evidence and approval records are private staff material; later +customer/bot projections must return approved article content only. diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..8549f29 --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/knowledge-base-contracts", + "version": "0.1.0", + "description": "Provider-neutral knowledge collections, revisions, validation, and approval contracts.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/knowledge-base.git", + "directory": "packages/contracts" + }, + "dependencies": { + "@pegma/spine": "0.1.2" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run --silent build" + } +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..d6ee940 --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,196 @@ +import type { IsoTimestamp, PrincipalId } from "@pegma/spine"; + +export type { Clock, IsoTimestamp, Logger, PrincipalId } from "@pegma/spine"; + +export type CollectionId = string; +export type ArticleId = string; +export type EvidenceId = string; +export type ValidationPolicyId = string; + +/** These are permission names, never role names or an authorization engine. */ +export const knowledgePermissions = { + collectionRead: "knowledge.collection.read", + collectionManage: "knowledge.collection.manage", + publicCollectionApprove: "knowledge.collection.approve-public", + articleRead: "knowledge.article.read", + draftWrite: "knowledge.article.draft.write", + evidenceSubmit: "knowledge.article.evidence.submit", + reviewSubmit: "knowledge.article.review.submit", + review: "knowledge.article.review", + publish: "knowledge.article.publish", + retire: "knowledge.article.retire", + validationManage: "knowledge.validation.manage", +} as const; + +export type KnowledgePermission = + (typeof knowledgePermissions)[keyof typeof knowledgePermissions]; + +export const articleKinds = [ + "explanation", + "walkthrough", + "troubleshooting", + "developer-reference", +] as const; +export type ArticleKind = (typeof articleKinds)[number]; + +/** The host resolves named permissions and authenticates every protected use. */ +export type KnowledgeAudience = + | { readonly kind: "permission"; readonly permission: string } + | { readonly kind: "anonymous" }; + +export type CollectionUse = + | { readonly enabled: false } + | { readonly enabled: true; readonly audience: KnowledgeAudience }; + +export interface CollectionPolicy { + readonly version: number; + readonly portal: CollectionUse; + readonly bot: CollectionUse; +} + +export interface PublicCollectionApproval { + readonly collectionId: CollectionId; + readonly policyVersion: number; + readonly policyHash: string; + readonly reviewerId: PrincipalId; + readonly reviewedAt: IsoTimestamp; +} + +export interface Collection { + readonly id: CollectionId; + readonly revision: number; + readonly name: string; + readonly policy: CollectionPolicy; + readonly publicApproval?: PublicCollectionApproval; + readonly createdBy: PrincipalId; + readonly createdAt: IsoTimestamp; + readonly updatedBy: PrincipalId; + readonly updatedAt: IsoTimestamp; +} + +export interface Applicability { + readonly productId: string; + readonly productVersion: string; + readonly buildId?: string; + readonly locale?: string; +} + +export interface ArticleContent { + readonly format: "markdown" | "plain_text"; + readonly text: string; +} + +export interface ValidationPolicyReference { + readonly id: ValidationPolicyId; + readonly version: number; +} + +/** Content is immutable. Editing creates a new numbered revision. */ +export interface ArticleRevision { + readonly articleId: ArticleId; + readonly number: number; + readonly collectionId: CollectionId; + readonly kind: ArticleKind; + readonly title: string; + readonly summary: string; + readonly content: ArticleContent; + readonly tags: readonly string[]; + readonly applicability: Applicability; + readonly validationPolicy: ValidationPolicyReference; + /** Lowercase hexadecimal SHA-256, computed by core, not supplied as proof. */ + readonly contentHash: string; + readonly createdBy: PrincipalId; + readonly createdAt: IsoTimestamp; +} + +export interface ValidationRequirement { + readonly id: string; + readonly kind: ArticleKind; + readonly testKind: string; + readonly maxAgeMilliseconds: number; + /** Identity authentication and attestation verification belong to KB-02/host. */ + readonly trustedRunnerIds: readonly PrincipalId[]; +} + +export interface ValidationPolicy { + readonly id: ValidationPolicyId; + readonly version: number; + readonly requirements: readonly ValidationRequirement[]; +} + +/** Opaque protected artifact identity; core never fetches URLs or executes it. */ +export interface EvidenceArtifactReference { + readonly id: string; + readonly hash: string; +} + +/** Private verification material, excluded from later customer/bot DTOs. */ +export interface VerificationEvidence { + readonly id: EvidenceId; + readonly version: number; + readonly articleId: ArticleId; + readonly articleRevision: number; + readonly contentHash: string; + readonly validationPolicy: ValidationPolicyReference; + readonly checkId: string; + readonly testKind: string; + readonly applicability: Applicability; + readonly stagingBuildId: string; + readonly steps: readonly string[]; + readonly result: "passed" | "failed" | "inconclusive"; + readonly executedAt: IsoTimestamp; + readonly runnerId: PrincipalId; + readonly artifacts: readonly EvidenceArtifactReference[]; + /** A trusted boundary must authenticate the runner and verify this receipt. */ + readonly attestation: { + readonly id: string; + readonly verifiedBy: PrincipalId; + readonly verifiedAt: IsoTimestamp; + }; + /** Lowercase hexadecimal SHA-256 over the evidence fields excluding hash. */ + readonly hash: string; +} + +export interface EvidenceBinding { + readonly id: EvidenceId; + readonly version: number; + readonly hash: string; +} + +/** Exact review snapshot. Changes to any binding require a fresh review. */ +export interface ApprovalBinding { + readonly articleId: ArticleId; + readonly articleRevision: number; + readonly contentHash: string; + readonly collectionId: CollectionId; + readonly collectionPolicyVersion: number; + readonly collectionPolicyHash: string; + readonly applicability: Applicability; + readonly validationPolicy: ValidationPolicyReference; + readonly validationPolicyHash: string; + readonly evidence: readonly EvidenceBinding[]; +} + +export interface ArticleApproval { + readonly binding: ApprovalBinding; + readonly reviewerId: PrincipalId; + readonly reviewedAt: IsoTimestamp; +} + +export interface PublishedArticle { + readonly revision: ArticleRevision; + readonly approval: ArticleApproval; +} + +/** + * Bounded transition input/output: one current revision and one publication. + * Durable immutable revision history is owned by later application services. + */ +export interface Article { + readonly id: ArticleId; + readonly state: "draft" | "in-review" | "published" | "retired"; + readonly current: ArticleRevision; + readonly evidence: readonly VerificationEvidence[]; + readonly review?: ApprovalBinding; + readonly published?: PublishedArticle; +} diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..5a82ed0 --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/core/LICENSE b/packages/core/LICENSE new file mode 100644 index 0000000..833a7d0 --- /dev/null +++ b/packages/core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pegma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/core/README.md b/packages/core/README.md new file mode 100644 index 0000000..a6f3b5b --- /dev/null +++ b/packages/core/README.md @@ -0,0 +1,119 @@ +# @pegma/knowledge-base-core + +Pure collection, draft, verification, review, publication, and retirement +transitions. This initial 0.1.0 source is unpublished. It requires no Support +Desk, GitHub, model, framework, database, or provider SDK. + +Core owns domain invariants. The later application service authenticates +callers, resolves Authorization Core permissions, loads current authoritative +records, verifies external evidence receipts, and commits state with Audit +through Storage Core. Calling a pure function does not grant a permission. + +## Entry points + +- **createCollection** always starts with portal and bot use disabled. +- **previewCollectionPolicy** binds proposed independent portal/bot audiences to + the current collection revision. **applyCollectionPolicy** rejects stale or + changed previews. Anonymous use additionally requires explicit approval of + that exact collection, policy version, and policy hash. + Its review time must fall between the source collection's latest update and + application of the approved change; review and application can occur at + different times. + The preview hash is a deterministic snapshot binding, not a signature, + capability, or proof that the preview function was called. The application + loads the trusted current collection and authenticates the actor and approval. +- **createArticle** and **reviseArticle** compute SHA-256 over the complete numbered + revision using canonical JSON and Web Crypto. A supplied hash is never + accepted as content proof. Revision outputs and their nested values are + frozen, and asynchronous operations snapshot their inputs before hashing. +- **recordEvidence** checks exact article revision/hash, applicability, + validation policy, expected staging build, required check, runner, trusted + verification receipt, execution/verification time, steps, and artifacts. + Replacing evidence increments its version and invalidates pending review. +- **submitForReview** requires exactly one current verified passing result for + every check required by that article kind. Every kind requires a content + check; walkthroughs additionally require a workflow check. Policies can + require further check kinds. +- **publishArticle** recomputes the approval binding against current facts and + compares both the submitted review and the reviewer's exact requested + binding. Changed content, audience, validation policy, evidence, or expired + checks defeat stale approval. +- **rejectReview** returns a submitted review to draft. The application records + the authorized rejection reason in its command/audit transaction. +- **retireArticle** removes the publication and pending review. Republishing a + retired article requires creating a new draft revision and review. + Retirement retains the current private revision and evidence in the bounded + staff aggregate; it is not deletion or anonymization. + +An article has no access override. Its numbered revision names one collection. +Moving a draft to another collection requires a new reviewed publication. An +existing approved publication remains bound to its previous collection while +that draft is being prepared. + +## Bounded state and publication checks + +The aggregate retains one current revision, at most one published revision, +and a bounded set of current evidence. It does not store a revision archive. +Editing clears current evidence and pending review while preserving the old +published snapshot. A published snapshot contains exact evidence references; +later application storage must retain or revoke the corresponding evidence +versions and private provenance according to policy. + +**isPublicationBoundToCurrentPolicies** checks the published snapshot against +the supplied authoritative collection and validation policy, including hashes +to detect same-version mutation. It is only a policy-binding predicate. It does +not authorize a read, authenticate external evidence, establish retained +evidence availability/revocation, or implement customer retrieval. Never expose +an aggregate or its private approval/evidence fields directly to customers or +the model. Never expose or log raw aggregates. Authorized DTO construction, +evidence access, retention, and deletion belong to KB-02 and the host. + +All times, identities, and policies are explicit inputs. A **ReviewContext** +must come from the trusted application: it supplies current collection and +validation policy, the expected staging build, authenticated receipt verifier +allowlist, and current time. Core validates claimed bindings and configured +runner/verifier membership; it cannot authenticate a claimed identity. A +review or evidence operation cannot predate the supplied collection's latest +update. Older evidence can remain valid when the operation uses current time +and the evidence still satisfies its exact binding and freshness requirements. +A caller inventing an attestation object has not produced verification proof. +The later API/MCP boundary must verify receipts and authorize evidence +submission before calling these transitions. + +A draft targeting a future build waits for matching verification or is revised; +evidence for a different staging build fails closed. + +## Source format and schema ceilings + +Content is Markdown or plain text, never MDX. The Markdown subset supports +ordinary text, headings, lists, code, and inline links to HTTPS URLs, root-relative +paths, or fragments. Raw HTML/JSX, embedded images, autolinks, reference links, +credentialed URLs, protocol-relative URLs, and other schemes are rejected. +Escape literal markup as entities, including markup shown inside code examples. +Core never fetches links/artifacts or executes code. Hosts must use a safe +renderer with raw HTML and executable extensions disabled; plain text must be +rendered as text. + +**knowledgeLimits** exposes hard schema ceilings: 32 KiB of UTF-8 content, +200-character titles, 1,000-character summaries, 16 tags, 32 policy requirements, +32 current evidence records, 16 steps per record, and eight artifact references +per record. Other strings and identity lists also have explicit bounds. +These are validation ceilings, not measured production throughput, retention, +rate limits, or model budgets. KB-02 must separately bound durable partitions, +retained history, and transaction work. + +Domain failures are **KnowledgeBaseError** with code and field. Core does +not implement HTTP mappings, replay receipts, concurrent storage updates, +authorization roles, audit persistence, or network retry behavior. + +## Validation + +From the repository root: + + pnpm run check + pnpm exec vitest run packages/core/src/index.test.ts + +Tests exercise exported entry points for immutable edits, private/bot-only and +public policies, stale approval and evidence replacement, wrong build/runner, +expired checks, retirement, malformed content, and byte bounds. They establish +pure domain behavior, not authenticated authoring or real-host acceptance. diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..cacf64c --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/knowledge-base-core", + "version": "0.1.0", + "description": "Pure knowledge article, validation, and publication transitions.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/knowledge-base.git", + "directory": "packages/core" + }, + "dependencies": { + "@pegma/knowledge-base-contracts": "0.1.0" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run --silent build" + } +} diff --git a/packages/core/src/articles.ts b/packages/core/src/articles.ts new file mode 100644 index 0000000..7cae953 --- /dev/null +++ b/packages/core/src/articles.ts @@ -0,0 +1,645 @@ +import type { + Applicability, + ApprovalBinding, + Article, + ArticleContent, + ArticleKind, + ArticleRevision, + Collection, + IsoTimestamp, + PrincipalId, + ValidationPolicy, + VerificationEvidence, +} from "@pegma/knowledge-base-contracts"; +import { verifyCollection } from "./collections.js"; +import { + boundedArray, + canonical, + count, + digest, + hash, + immutable, + invalid, + keys, + KnowledgeBaseError, + knowledgeLimits, + text, + timestamp, + unique, + validateApplicability, + validatePolicy, + validateRevisionFields, + verifyRevision, +} from "./validation.js"; + +export interface ArticleDraft { + readonly kind: ArticleKind; + readonly title: string; + readonly summary: string; + readonly content: ArticleContent; + readonly tags: readonly string[]; + readonly applicability: Applicability; +} + +export interface DraftContext { + readonly collection: Collection; + readonly validationPolicy: ValidationPolicy; + readonly actorId: PrincipalId; + readonly at: IsoTimestamp; +} + +/** + * Authoritative facts from the host/application, never raw HTTP evidence fields. + * Core checks bindings; it cannot authenticate a runner, verifier, or permission. + */ +export interface ReviewContext { + readonly collection: Collection; + readonly validationPolicy: ValidationPolicy; + readonly expectedStagingBuildId: string; + readonly trustedAttesterIds: readonly PrincipalId[]; + readonly at: IsoTimestamp; +} + +export type EvidenceSubmission = Omit< + VerificationEvidence, + "version" | "hash" | "attestation" +>; + +function validateBindingApplicability( + binding: ApprovalBinding, + field: "review" | "binding", +): void { + const fields = [ + "articleId", + "articleRevision", + "contentHash", + "collectionId", + "collectionPolicyVersion", + "collectionPolicyHash", + "applicability", + "validationPolicy", + "validationPolicyHash", + "evidence", + ] as const; + keys(binding, fields, field); + if (fields.some((key) => !Object.hasOwn(binding, key))) { + invalid(field, "Approval binding is missing required snapshot fields"); + } + validateApplicability(binding.applicability); +} + +function expectedRevision(article: Article, expected: number): void { + keys( + article, + ["id", "state", "current", "evidence", "review", "published"], + "article", + ); + if (!["draft", "in-review", "published", "retired"].includes(article.state)) { + invalid("state", "Unknown article state"); + } + count(expected, "expectedRevision"); + if ( + article.current.articleId !== article.id || + article.current.number !== expected + ) { + throw new KnowledgeBaseError( + "conflict", + "expectedRevision", + "Article revision has changed", + ); + } +} + +function withoutReview(article: Article): Omit { + const { review: _review, ...rest } = article; + return rest; +} + +function usable(article: Article): void { + if (article.state === "retired") { + throw new KnowledgeBaseError( + "transition", + "state", + "Retired articles need a new draft", + ); + } +} + +async function createRevision( + id: string, + number: number, + draft: ArticleDraft, + context: DraftContext, +): Promise { + await verifyCollection(context.collection); + validatePolicy(context.validationPolicy); + const fields: Omit = { + articleId: id, + number, + collectionId: context.collection.id, + kind: draft.kind, + title: draft.title, + summary: draft.summary, + content: draft.content, + tags: draft.tags, + applicability: draft.applicability, + validationPolicy: { + id: context.validationPolicy.id, + version: context.validationPolicy.version, + }, + createdBy: context.actorId, + createdAt: context.at, + }; + validateRevisionFields(fields); + if ( + timestamp(fields.createdAt, "createdAt") < + timestamp(context.collection.createdAt, "collection.createdAt") + ) { + invalid("createdAt", "Article cannot predate its collection"); + } + return { ...fields, contentHash: await digest(fields) }; +} + +export async function createArticle(input: { + readonly id: string; + readonly draft: ArticleDraft; + readonly context: DraftContext; +}): Promise
{ + const request = structuredClone(input); + const current = await createRevision( + request.id, + 1, + request.draft, + request.context, + ); + return immutable({ id: request.id, state: "draft", current, evidence: [] }); +} + +/** A collection move is a new draft, never an immediate audience override. */ +export async function reviseArticle( + article: Article, + input: { + readonly expectedRevision: number; + readonly draft: ArticleDraft; + readonly context: DraftContext; + }, +): Promise
{ + const source = structuredClone(article); + const request = structuredClone(input); + expectedRevision(source, request.expectedRevision); + await verifyRevision(source.current); + if ( + timestamp(request.context.at, "at") < + timestamp(source.current.createdAt, "createdAt") + ) { + invalid("at", "Revision time moved backwards"); + } + const current = await createRevision( + source.id, + source.current.number + 1, + request.draft, + request.context, + ); + return immutable({ + ...withoutReview(source), + state: "draft", + current, + evidence: [], + }); +} + +function validateReviewContext(context: ReviewContext): number { + validatePolicy(context.validationPolicy); + text(context.expectedStagingBuildId, "expectedStagingBuildId"); + boundedArray( + context.trustedAttesterIds, + "trustedAttesterIds", + knowledgeLimits.trustedIdentities, + ); + if (context.trustedAttesterIds.length === 0) + invalid("trustedAttesterIds", "Trusted attesters must be explicit"); + for (const principal of context.trustedAttesterIds) + text(principal, "trustedAttesterId"); + unique(context.trustedAttesterIds, "trustedAttesterIds"); + return timestamp(context.at, "at"); +} + +function evidenceFailure(field: string, message: string): never { + throw new KnowledgeBaseError("evidence", field, message); +} + +async function verifyEvidence( + evidence: VerificationEvidence, + revision: ArticleRevision, + context: ReviewContext, +): Promise { + keys( + evidence, + [ + "id", + "version", + "articleId", + "articleRevision", + "contentHash", + "validationPolicy", + "checkId", + "testKind", + "applicability", + "stagingBuildId", + "steps", + "result", + "executedAt", + "runnerId", + "artifacts", + "attestation", + "hash", + ], + "evidence", + ); + validateApplicability(evidence.applicability); + const now = validateReviewContext(context); + text(evidence.id, "evidence.id"); + count(evidence.version, "evidence.version"); + hash(evidence.hash, "evidence.hash"); + const { hash: evidenceHash, ...fields } = evidence; + if ((await digest(fields)) !== evidenceHash) + evidenceFailure("evidence.hash", "Evidence changed after hashing"); + if ( + evidence.articleId !== revision.articleId || + evidence.articleRevision !== revision.number || + evidence.contentHash !== revision.contentHash || + canonical(evidence.validationPolicy) !== + canonical(revision.validationPolicy) || + canonical(evidence.applicability) !== canonical(revision.applicability) || + evidence.stagingBuildId !== context.expectedStagingBuildId || + (revision.applicability.buildId !== undefined && + evidence.stagingBuildId !== revision.applicability.buildId) + ) + evidenceFailure( + "evidence.binding", + "Evidence does not bind the exact draft, policy, product, and staging build", + ); + text(evidence.checkId, "evidence.checkId"); + text(evidence.testKind, "evidence.testKind", 64); + text(evidence.stagingBuildId, "evidence.stagingBuildId"); + const requirement = context.validationPolicy.requirements.find( + (item) => + item.id === evidence.checkId && + item.kind === revision.kind && + item.testKind === evidence.testKind, + ); + if (requirement === undefined) + evidenceFailure( + "evidence.checkId", + "Evidence does not match a required check", + ); + text(evidence.runnerId, "evidence.runnerId"); + if (!requirement.trustedRunnerIds.includes(evidence.runnerId)) { + evidenceFailure( + "evidence.runnerId", + "Runner is not trusted for this check", + ); + } + if (evidence.attestation === undefined || evidence.attestation === null) { + evidenceFailure( + "evidence.attestation", + "A trusted verification receipt is required", + ); + } + keys( + evidence.attestation, + ["id", "verifiedBy", "verifiedAt"], + "evidence.attestation", + ); + text(evidence.attestation.id, "evidence.attestation.id"); + text(evidence.attestation.verifiedBy, "evidence.attestation.verifiedBy"); + if (!context.trustedAttesterIds.includes(evidence.attestation.verifiedBy)) { + evidenceFailure( + "evidence.attestation", + "Evidence requires a trusted verification receipt", + ); + } + const executed = timestamp(evidence.executedAt, "evidence.executedAt"); + const verified = timestamp( + evidence.attestation.verifiedAt, + "evidence.attestation.verifiedAt", + ); + if ( + executed < timestamp(revision.createdAt, "revision.createdAt") || + verified < executed || + verified > now || + executed > now || + now - executed > requirement.maxAgeMilliseconds + ) + evidenceFailure( + "evidence.executedAt", + "Evidence is stale, future-dated, or predates the draft", + ); + if (!["passed", "failed", "inconclusive"].includes(evidence.result)) { + invalid("evidence.result", "Unknown evidence result"); + } + boundedArray(evidence.steps, "evidence.steps", knowledgeLimits.steps); + if (evidence.steps.length === 0) + invalid("evidence.steps", "Evidence must describe its checks"); + for (const step of evidence.steps) + text(step, "evidence.step", knowledgeLimits.stepCharacters); + boundedArray( + evidence.artifacts, + "evidence.artifacts", + knowledgeLimits.artifacts, + ); + for (const artifact of evidence.artifacts) { + keys(artifact, ["id", "hash"], "artifact"); + text(artifact.id, "artifact.id"); + hash(artifact.hash, "artifact.hash"); + } + unique( + evidence.artifacts.map((artifact) => artifact.id), + "evidence.artifacts", + ); +} + +async function verifyContextBinding( + revision: ArticleRevision, + context: ReviewContext, +): Promise { + const at = validateReviewContext(context); + await verifyRevision(revision); + await verifyCollection(context.collection); + if (at < timestamp(context.collection.updatedAt, "collection.updatedAt")) { + invalid( + "at", + "Operation time cannot predate the current collection policy", + ); + } + if ( + revision.collectionId !== context.collection.id || + revision.validationPolicy.id !== context.validationPolicy.id || + revision.validationPolicy.version !== context.validationPolicy.version + ) { + throw new KnowledgeBaseError( + "conflict", + "policy", + "Review requires the current collection and validation policy", + ); + } +} + +/** Replacing evidence invalidates a pending review; history is stored by KB-02. */ +export async function recordEvidence( + article: Article, + input: { + readonly evidence: EvidenceSubmission; + readonly attestation: VerificationEvidence["attestation"]; + readonly context: ReviewContext; + }, +): Promise
{ + const source = structuredClone(article); + const request = structuredClone(input); + keys( + request.evidence, + [ + "id", + "articleId", + "articleRevision", + "contentHash", + "validationPolicy", + "checkId", + "testKind", + "applicability", + "stagingBuildId", + "steps", + "result", + "executedAt", + "runnerId", + "artifacts", + ], + "evidence", + ); + validateApplicability(request.evidence.applicability); + usable(source); + expectedRevision(source, request.evidence.articleRevision); + await verifyContextBinding(source.current, request.context); + boundedArray(source.evidence, "evidence", knowledgeLimits.evidence); + const previous = source.evidence.find( + (item) => item.id === request.evidence.id, + ); + const fields = { + ...request.evidence, + version: previous === undefined ? 1 : previous.version + 1, + attestation: request.attestation, + }; + count(fields.version, "evidence.version"); + const evidence: VerificationEvidence = { + ...fields, + hash: await digest(fields), + }; + await verifyEvidence(evidence, source.current, request.context); + const records = [ + ...source.evidence.filter((item) => item.id !== evidence.id), + evidence, + ]; + boundedArray(records, "evidence", knowledgeLimits.evidence); + return immutable({ + ...withoutReview(source), + state: "draft", + evidence: records, + }); +} + +async function approvalBinding( + article: Article, + context: ReviewContext, +): Promise { + await verifyContextBinding(article.current, context); + boundedArray(article.evidence, "evidence", knowledgeLimits.evidence); + unique( + article.evidence.map((item) => item.id), + "evidence", + ); + for (const evidence of article.evidence) + await verifyEvidence(evidence, article.current, context); + const requirements = context.validationPolicy.requirements.filter( + (item) => item.kind === article.current.kind, + ); + for (const requirement of requirements) { + const checks = article.evidence.filter( + (item) => item.checkId === requirement.id, + ); + if (checks.length !== 1 || checks[0]!.result !== "passed") { + evidenceFailure( + "evidence.checkId", + "Every required check needs exactly one verified passing result", + ); + } + } + return { + articleId: article.id, + articleRevision: article.current.number, + contentHash: article.current.contentHash, + collectionId: context.collection.id, + collectionPolicyVersion: context.collection.policy.version, + collectionPolicyHash: await digest(context.collection.policy), + applicability: article.current.applicability, + validationPolicy: article.current.validationPolicy, + validationPolicyHash: await digest(context.validationPolicy), + evidence: article.evidence + .map((item) => ({ id: item.id, version: item.version, hash: item.hash })) + .sort((left, right) => + left.id === right.id ? 0 : left.id < right.id ? -1 : 1, + ), + }; +} + +export async function submitForReview( + article: Article, + input: { readonly expectedRevision: number; readonly context: ReviewContext }, +): Promise
{ + const source = structuredClone(article); + const request = structuredClone(input); + usable(source); + expectedRevision(source, request.expectedRevision); + if (source.state !== "draft") { + throw new KnowledgeBaseError( + "transition", + "state", + "Only a draft can enter review", + ); + } + const review = await approvalBinding(source, request.context); + return immutable({ ...source, state: "in-review", review }); +} + +/** Permission checks and authenticated reviewer identity belong to KB-02. */ +export async function publishArticle( + article: Article, + input: { + readonly expectedRevision: number; + readonly binding: ApprovalBinding; + readonly reviewerId: PrincipalId; + readonly context: ReviewContext; + }, +): Promise
{ + const source = structuredClone(article); + const request = structuredClone(input); + expectedRevision(source, request.expectedRevision); + text(request.reviewerId, "reviewerId"); + if (source.state !== "in-review") { + throw new KnowledgeBaseError( + "transition", + "state", + "Publication requires a submitted review", + ); + } + if (source.review === undefined) { + invalid("review", "Submitted review snapshot is missing"); + } + validateBindingApplicability(source.review, "review"); + validateBindingApplicability(request.binding, "binding"); + const binding = await approvalBinding(source, request.context); + if ( + canonical(binding) !== canonical(source.review) || + canonical(binding) !== canonical(request.binding) + ) { + throw new KnowledgeBaseError( + "conflict", + "approval", + "Approval no longer matches the exact review snapshot", + ); + } + return immutable({ + ...withoutReview(source), + state: "published", + published: { + revision: source.current, + approval: { + binding, + reviewerId: request.reviewerId, + reviewedAt: request.context.at, + }, + }, + }); +} + +export function rejectReview(article: Article, expected: number): Article { + expectedRevision(article, expected); + if (article.state !== "in-review") { + throw new KnowledgeBaseError( + "transition", + "state", + "Only a submitted review can be rejected", + ); + } + return immutable({ + ...withoutReview(structuredClone(article)), + state: "draft", + }); +} + +export function retireArticle(article: Article, expected: number): Article { + expectedRevision(article, expected); + const { published: _published, ...rest } = withoutReview( + structuredClone(article), + ); + return immutable({ ...rest, state: "retired" }); +} + +/** + * Policy-binding predicate only. It does not authorize a read, prove retained + * evidence availability/revocation, or replace later retrieval's current checks. + */ +export async function isPublicationBoundToCurrentPolicies( + article: Article, + collection: Collection, + policy: ValidationPolicy, +): Promise { + const source = structuredClone(article); + const currentCollection = structuredClone(collection); + const currentPolicy = structuredClone(policy); + if (source.state === "retired" || source.published === undefined) + return false; + await verifyCollection(currentCollection); + validatePolicy(currentPolicy); + const published = source.published; + keys(published, ["revision", "approval"], "published"); + if ( + !Object.hasOwn(published, "revision") || + !Object.hasOwn(published, "approval") + ) { + invalid( + "published", + "Published snapshot must include revision and approval", + ); + } + keys( + published.approval, + ["binding", "reviewerId", "reviewedAt"], + "published.approval", + ); + if (!Object.hasOwn(published.approval, "binding")) { + invalid( + "published.approval", + "Published approval must include its binding", + ); + } + const binding = published.approval.binding; + validateBindingApplicability(binding, "binding"); + await verifyRevision(published.revision); + return ( + published.revision.articleId === source.id && + binding.articleId === source.id && + binding.articleRevision === published.revision.number && + binding.contentHash === published.revision.contentHash && + binding.collectionId === published.revision.collectionId && + currentCollection.id === published.revision.collectionId && + binding.collectionPolicyVersion === currentCollection.policy.version && + binding.collectionPolicyHash === (await digest(currentCollection.policy)) && + canonical(binding.applicability) === + canonical(published.revision.applicability) && + canonical(binding.validationPolicy) === + canonical(published.revision.validationPolicy) && + binding.validationPolicy.id === currentPolicy.id && + binding.validationPolicy.version === currentPolicy.version && + binding.validationPolicyHash === (await digest(currentPolicy)) + ); +} diff --git a/packages/core/src/collections.ts b/packages/core/src/collections.ts new file mode 100644 index 0000000..12d7a2c --- /dev/null +++ b/packages/core/src/collections.ts @@ -0,0 +1,244 @@ +import type { + Collection, + CollectionPolicy, + CollectionUse, + IsoTimestamp, + PrincipalId, + PublicCollectionApproval, +} from "@pegma/knowledge-base-contracts"; +import { + count, + digest, + immutable, + invalid, + keys, + KnowledgeBaseError, + text, + timestamp, +} from "./validation.js"; + +export interface CollectionPolicyPreview { + readonly collectionId: string; + readonly expectedRevision: number; + readonly policy: CollectionPolicy; + /** Deterministic snapshot digest, not a signature, capability, or preview receipt. */ + readonly policyHash: string; +} + +function validateUse(use: CollectionUse, field: string): void { + keys(use, ["enabled", "audience"], field); + if (use.enabled === false) { + if (Object.keys(use).some((key) => key !== "enabled")) { + invalid(field, "Disabled use cannot carry a hidden audience"); + } + return; + } + if (use.enabled !== true || use.audience === undefined) { + invalid(field, "Enabled use must name its audience"); + } + if (use.audience.kind === "permission") { + keys(use.audience, ["kind", "permission"], field + ".audience"); + text(use.audience.permission, field + ".permission"); + } else if (use.audience.kind !== "anonymous") { + invalid(field, "Unknown collection audience"); + } else { + keys(use.audience, ["kind"], field + ".audience"); + } +} + +export function validateCollectionPolicy(policy: CollectionPolicy): void { + keys(policy, ["version", "portal", "bot"], "collectionPolicy"); + count(policy.version, "collectionPolicy.version"); + validateUse(policy.portal, "collectionPolicy.portal"); + validateUse(policy.bot, "collectionPolicy.bot"); +} + +function isPublic(policy: CollectionPolicy): boolean { + return [policy.portal, policy.bot].some( + (use) => use.enabled && use.audience.kind === "anonymous", + ); +} + +export async function verifyCollection(collection: Collection): Promise { + keys( + collection, + [ + "id", + "revision", + "name", + "policy", + "publicApproval", + "createdBy", + "createdAt", + "updatedBy", + "updatedAt", + ], + "collection", + ); + text(collection.id, "collection.id"); + text(collection.name, "collection.name"); + count(collection.revision, "collection.revision"); + text(collection.createdBy, "collection.createdBy"); + text(collection.updatedBy, "collection.updatedBy"); + const createdAt = timestamp(collection.createdAt, "collection.createdAt"); + const updatedAt = timestamp(collection.updatedAt, "collection.updatedAt"); + if (updatedAt < createdAt) + invalid("collection.updatedAt", "Collection time moved backwards"); + validateCollectionPolicy(collection.policy); + if (!isPublic(collection.policy)) { + if (collection.publicApproval !== undefined) { + invalid( + "publicApproval", + "Private collection policies cannot retain public approval", + ); + } + return; + } + const approval = collection.publicApproval; + if ( + approval === undefined || + approval.collectionId !== collection.id || + approval.policyVersion !== collection.policy.version || + approval.policyHash !== (await digest(collection.policy)) + ) { + throw new KnowledgeBaseError( + "conflict", + "publicApproval", + "Anonymous collection use requires exact policy approval", + ); + } + keys( + approval, + ["collectionId", "policyVersion", "policyHash", "reviewerId", "reviewedAt"], + "publicApproval", + ); + text(approval.reviewerId, "publicApproval.reviewerId"); + const reviewedAt = timestamp( + approval.reviewedAt, + "publicApproval.reviewedAt", + ); + if (reviewedAt < createdAt || reviewedAt > updatedAt) { + invalid( + "publicApproval.reviewedAt", + "Public approval time is outside the policy change", + ); + } +} + +/** Creation is always private; enabling any audience is an explicit update. */ +export function createCollection(input: { + readonly id: string; + readonly name: string; + readonly actorId: PrincipalId; + readonly at: IsoTimestamp; +}): Collection { + text(input.id, "collection.id"); + text(input.name, "collection.name"); + text(input.actorId, "actorId"); + timestamp(input.at, "at"); + return immutable({ + id: input.id, + revision: 1, + name: input.name, + policy: { version: 1, portal: { enabled: false }, bot: { enabled: false } }, + createdBy: input.actorId, + createdAt: input.at, + updatedBy: input.actorId, + updatedAt: input.at, + }); +} + +/** + * Compute an exact proposed snapshot. Its digest detects changed fields; it + * cannot prove this function was called or authenticate an actor or approval. + */ +export async function previewCollectionPolicy( + collection: Collection, + uses: { readonly portal: CollectionUse; readonly bot: CollectionUse }, +): Promise { + const source = structuredClone(collection); + const proposed = structuredClone(uses); + await verifyCollection(source); + const policy = { + version: source.policy.version + 1, + portal: proposed.portal, + bot: proposed.bot, + }; + validateCollectionPolicy(policy); + return immutable({ + collectionId: source.id, + expectedRevision: source.revision, + policy, + policyHash: await digest(policy), + }); +} + +/** + * The application must load the trusted current collection and authenticate + * and authorize both the actor and any public-policy reviewer/approval. + */ +export async function applyCollectionPolicy( + collection: Collection, + input: { + readonly preview: CollectionPolicyPreview; + readonly actorId: PrincipalId; + readonly at: IsoTimestamp; + readonly publicApproval?: PublicCollectionApproval; + }, +): Promise { + const source = structuredClone(collection); + const change = structuredClone(input); + await verifyCollection(source); + text(change.actorId, "actorId"); + const at = timestamp(change.at, "at"); + if (at < timestamp(source.updatedAt, "collection.updatedAt")) { + invalid("at", "Policy change time moved backwards"); + } + if ( + change.preview.collectionId !== source.id || + change.preview.expectedRevision !== source.revision || + change.preview.policy.version !== source.policy.version + 1 || + change.preview.policyHash !== (await digest(change.preview.policy)) + ) { + throw new KnowledgeBaseError( + "conflict", + "preview", + "Collection policy preview is stale or changed", + ); + } + validateCollectionPolicy(change.preview.policy); + if ( + isPublic(change.preview.policy) && + change.publicApproval !== undefined && + timestamp(change.publicApproval.reviewedAt, "publicApproval.reviewedAt") < + timestamp(source.updatedAt, "collection.updatedAt") + ) { + invalid( + "publicApproval.reviewedAt", + "Public approval cannot predate the source collection policy", + ); + } + count(source.revision + 1, "collection.revision"); + const next: Collection = { + ...source, + revision: source.revision + 1, + policy: change.preview.policy, + updatedBy: change.actorId, + updatedAt: change.at, + ...(isPublic(change.preview.policy) && change.publicApproval !== undefined + ? { publicApproval: change.publicApproval } + : {}), + }; + const { publicApproval: _oldApproval, ...withoutApproval } = next; + const result = isPublic(next.policy) ? next : withoutApproval; + // Avoid accidentally inheriting an approval from an older public policy. + if (isPublic(next.policy) && change.publicApproval === undefined) { + throw new KnowledgeBaseError( + "conflict", + "publicApproval", + "An explicit public-policy approval is required", + ); + } + await verifyCollection(result); + return immutable(result); +} diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts new file mode 100644 index 0000000..a6b3ed0 --- /dev/null +++ b/packages/core/src/index.test.ts @@ -0,0 +1,1098 @@ +import { + articleKinds, + type Article, + type Collection, + type PublicCollectionApproval, + type ValidationPolicy, + type VerificationEvidence, +} from "@pegma/knowledge-base-contracts"; +import { describe, expect, it } from "vitest"; + +import { + applyCollectionPolicy, + createArticle, + createCollection, + isPublicationBoundToCurrentPolicies, + knowledgeLimits, + previewCollectionPolicy, + publishArticle, + recordEvidence, + rejectReview, + retireArticle, + reviseArticle, + submitForReview, + type ArticleDraft, + type DraftContext, + type EvidenceSubmission, + type ReviewContext, +} from "./index.js"; + +const at = (offset = 0) => + new Date(Date.parse("2026-11-06T20:00:00.000Z") + offset).toISOString(); +const policy: ValidationPolicy = { + id: "policy/documentation", + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + "-content", + kind, + testKind: "content", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ["runner/staging"], + })), + { + id: "walkthrough-workflow", + kind: "walkthrough", + testKind: "workflow", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ["runner/staging"], + }, + ], +}; +const draft: ArticleDraft = { + kind: "explanation", + title: "Export your workspace", + summary: "Download a workspace export.", + content: { format: "markdown", text: "Choose [Export](/workspace/export)." }, + tags: ["export"], + applicability: { + productId: "fictional-workshop", + productVersion: "1.0", + buildId: "staging-42", + locale: "en-US", + }, +}; + +function collection(id = "collection/portal"): Collection { + return createCollection({ + id, + name: "Workshop guides", + actorId: "staff/admin", + at: at(), + }); +} + +function authorContext(currentCollection = collection()): DraftContext { + return { + collection: currentCollection, + validationPolicy: policy, + actorId: "agent/author", + at: at(), + }; +} + +function reviewContext( + currentCollection = collection(), + offset = 3_000, +): ReviewContext { + return { + collection: currentCollection, + validationPolicy: policy, + expectedStagingBuildId: "staging-42", + trustedAttesterIds: ["staff/verifier"], + at: at(offset), + }; +} + +async function article( + kind: ArticleDraft["kind"] = "explanation", + currentCollection = collection(), +) { + return createArticle({ + id: "article/export", + draft: { ...draft, kind }, + context: authorContext(currentCollection), + }); +} + +function submission( + current: Article, + checkId = current.current.kind + "-content", +): EvidenceSubmission { + const requirement = policy.requirements.find((item) => item.id === checkId)!; + return { + id: "evidence/" + checkId, + articleId: current.id, + articleRevision: current.current.number, + contentHash: current.current.contentHash, + validationPolicy: current.current.validationPolicy, + checkId, + testKind: requirement.testKind, + applicability: current.current.applicability, + stagingBuildId: "staging-42", + steps: ["Read the exact draft and check the stated product behavior."], + result: "passed", + executedAt: at(1_000), + runnerId: "runner/staging", + artifacts: [{ id: "artifact/synthetic-test", hash: "a".repeat(64) }], + }; +} + +const attestation: VerificationEvidence["attestation"] = { + id: "receipt/verified", + verifiedBy: "staff/verifier", + verifiedAt: at(2_000), +}; + +async function checks( + current: Article, + context = reviewContext(), +): Promise
{ + let next = current; + for (const requirement of policy.requirements.filter( + (item) => item.kind === current.current.kind, + )) { + next = await recordEvidence(next, { + evidence: submission(next, requirement.id), + attestation, + context, + }); + } + return next; +} + +async function reviewed( + current?: Article, + context = reviewContext(), +): Promise
{ + const source = current ?? (await article()); + return submitForReview(await checks(source, context), { + expectedRevision: source.current.number, + context, + }); +} + +async function published( + current?: Article, + context = reviewContext(), +): Promise
{ + const source = current ?? (await reviewed()); + return publishArticle(source, { + expectedRevision: source.current.number, + binding: source.review!, + reviewerId: "staff/reviewer", + context, + }); +} + +describe("collection audience changes", () => { + it("creates private collections with independent portal and bot uses", async () => { + const initial = collection(); + expect(initial.policy).toEqual({ + version: 1, + portal: { enabled: false }, + bot: { enabled: false }, + }); + const preview = await previewCollectionPolicy(initial, { + portal: { enabled: false }, + bot: { + enabled: true, + audience: { kind: "permission", permission: "workshop.customer" }, + }, + }); + const updated = await applyCollectionPolicy(initial, { + preview, + actorId: "staff/admin", + at: at(1_000), + }); + expect(updated.policy.portal.enabled).toBe(false); + expect(updated.policy.bot).toEqual({ + enabled: true, + audience: { kind: "permission", permission: "workshop.customer" }, + }); + expect(initial.policy.version).toBe(1); + expect(updated.policy.version).toBe(2); + expect(updated).not.toHaveProperty("publicApproval"); + }); + + it("requires explicit public approval of the exact preview and defeats replay", async () => { + const initial = collection(); + const preview = await previewCollectionPolicy(initial, { + portal: { enabled: true, audience: { kind: "anonymous" } }, + bot: { enabled: false }, + }); + await expect( + applyCollectionPolicy(initial, { + preview, + actorId: "staff/admin", + at: at(1_000), + }), + ).rejects.toMatchObject({ field: "publicApproval" }); + const approval: PublicCollectionApproval = { + collectionId: initial.id, + policyVersion: preview.policy.version, + policyHash: preview.policyHash, + reviewerId: "staff/reviewer", + reviewedAt: at(1_000), + }; + await expect( + applyCollectionPolicy(initial, { + preview, + actorId: "staff/admin", + at: at(1_000), + publicApproval: { ...approval, policyHash: "b".repeat(64) }, + }), + ).rejects.toMatchObject({ field: "publicApproval" }); + const publicCollection = await applyCollectionPolicy(initial, { + preview, + actorId: "staff/admin", + at: at(1_000), + publicApproval: approval, + }); + expect(publicCollection.publicApproval).toEqual(approval); + await expect( + applyCollectionPolicy(publicCollection, { + preview, + actorId: "staff/admin", + at: at(2_000), + publicApproval: approval, + }), + ).rejects.toMatchObject({ field: "preview" }); + const privatePreview = await previewCollectionPolicy(publicCollection, { + portal: { enabled: false }, + bot: { enabled: false }, + }); + const privateAgain = await applyCollectionPolicy(publicCollection, { + preview: privatePreview, + actorId: "staff/admin", + at: at(2_000), + }); + expect(privateAgain).not.toHaveProperty("publicApproval"); + }); + + it("rejects a mutated preview even when its policy version is unchanged", async () => { + const initial = collection(); + const preview = await previewCollectionPolicy(initial, { + portal: { enabled: false }, + bot: { enabled: false }, + }); + await expect( + applyCollectionPolicy(initial, { + preview: { + ...preview, + policy: { + ...preview.policy, + bot: { enabled: true, audience: { kind: "anonymous" } }, + }, + }, + actorId: "staff/admin", + at: at(1_000), + }), + ).rejects.toMatchObject({ field: "preview" }); + }); + + it("rejects public approval predating the source policy but allows review before application", async () => { + const initial = collection(); + const privatePreview = await previewCollectionPolicy(initial, { + portal: { + enabled: true, + audience: { kind: "permission", permission: "workshop.customer" }, + }, + bot: { enabled: false }, + }); + const updated = await applyCollectionPolicy(initial, { + preview: privatePreview, + actorId: "staff/admin", + at: at(10_000), + }); + const publicPreview = await previewCollectionPolicy(updated, { + portal: { enabled: true, audience: { kind: "anonymous" } }, + bot: { enabled: false }, + }); + const approval: PublicCollectionApproval = { + collectionId: updated.id, + policyVersion: publicPreview.policy.version, + policyHash: publicPreview.policyHash, + reviewerId: "staff/reviewer", + reviewedAt: at(5_000), + }; + await expect( + applyCollectionPolicy(updated, { + preview: publicPreview, + actorId: "staff/admin", + at: at(20_000), + publicApproval: approval, + }), + ).rejects.toMatchObject({ field: "publicApproval.reviewedAt" }); + const approved = await applyCollectionPolicy(updated, { + preview: publicPreview, + actorId: "staff/admin", + at: at(20_000), + publicApproval: { ...approval, reviewedAt: at(15_000) }, + }); + await expect( + applyCollectionPolicy(updated, { + preview: publicPreview, + actorId: "staff/admin", + at: at(20_000), + publicApproval: { ...approval, reviewedAt: at(25_000) }, + }), + ).rejects.toMatchObject({ field: "publicApproval.reviewedAt" }); + expect(approved.publicApproval?.reviewedAt).toBe(at(15_000)); + expect(approved.updatedAt).toBe(at(20_000)); + expect(approved.policy.portal).toEqual({ + enabled: true, + audience: { kind: "anonymous" }, + }); + }); +}); + +describe("immutable drafts and publication", () => { + it("rejects malformed stored review parents with a named domain failure", async () => { + const inReview = await reviewed(); + for (const malformed of [null, undefined, {}, [], "invalid"]) { + const unsafe = { ...inReview, review: malformed } as unknown as Article; + await expect( + publishArticle(unsafe, { + expectedRevision: 1, + binding: inReview.review!, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ name: "KnowledgeBaseError", field: "review" }); + } + }); + + it("rejects malformed supplied binding parents with a named domain failure", async () => { + const inReview = await reviewed(); + for (const malformed of [null, undefined, {}, [], "invalid"]) { + await expect( + publishArticle(inReview, { + expectedRevision: 1, + binding: malformed as unknown as NonNullable, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ name: "KnowledgeBaseError", field: "binding" }); + } + }); + + it("rejects malformed published binding parents with a named domain failure", async () => { + const approved = await published(); + for (const malformed of [null, undefined, {}, [], "invalid"]) { + const unsafe = { + ...approved, + published: { + ...approved.published!, + approval: { ...approved.published!.approval, binding: malformed }, + }, + } as unknown as Article; + await expect( + isPublicationBoundToCurrentPolicies(unsafe, collection(), policy), + ).rejects.toMatchObject({ name: "KnowledgeBaseError", field: "binding" }); + } + }); + + it("guards malformed published revision parents before verifying them", async () => { + const approved = await published(); + for (const malformed of [null, undefined, {}, [], "invalid"]) { + const unsafe = { + ...approved, + published: { ...approved.published!, revision: malformed }, + } as unknown as Article; + await expect( + isPublicationBoundToCurrentPolicies(unsafe, collection(), policy), + ).rejects.toMatchObject({ name: "KnowledgeBaseError" }); + } + }); + + it("guards published approval parents before reading a binding", async () => { + const approved = await published(); + await expect( + isPublicationBoundToCurrentPolicies( + { ...approved, published: null } as unknown as Article, + collection(), + policy, + ), + ).rejects.toMatchObject({ name: "KnowledgeBaseError", field: "published" }); + for (const malformed of [null, undefined, {}, [], "invalid"]) { + const unsafe = { + ...approved, + published: { ...approved.published!, approval: malformed }, + } as unknown as Article; + await expect( + isPublicationBoundToCurrentPolicies(unsafe, collection(), policy), + ).rejects.toMatchObject({ + name: "KnowledgeBaseError", + field: "published.approval", + }); + } + }); + + it.each(["buildId", "locale"] as const)( + "rejects supplied approval applicability.%s before comparison", + async (field) => { + const inReview = await reviewed(); + await expect( + publishArticle(inReview, { + expectedRevision: 1, + binding: { + ...inReview.review!, + applicability: { + ...inReview.review!.applicability, + [field]: undefined, + } as ArticleDraft["applicability"], + }, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it.each(["buildId", "locale"] as const)( + "rejects stored review applicability.%s before comparison", + async (field) => { + const inReview = await reviewed(); + const malformed = { + ...inReview, + review: { + ...inReview.review!, + applicability: { + ...inReview.review!.applicability, + [field]: undefined, + } as ArticleDraft["applicability"], + }, + }; + await expect( + publishArticle(malformed, { + expectedRevision: 1, + binding: inReview.review!, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it.each(["buildId", "locale"] as const)( + "rejects published binding applicability.%s before policy comparison", + async (field) => { + const approved = await published(); + const malformed = { + ...approved, + published: { + ...approved.published!, + approval: { + ...approved.published!.approval, + binding: { + ...approved.published!.approval.binding, + applicability: { + ...approved.published!.approval.binding.applicability, + [field]: undefined, + } as ArticleDraft["applicability"], + }, + }, + }, + }; + await expect( + isPublicationBoundToCurrentPolicies(malformed, collection(), policy), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it("computes hashes, snapshots caller input, and freezes nested revisions", async () => { + const input = structuredClone(draft); + const pending = createArticle({ + id: "article/export", + draft: input, + context: authorContext(), + }); + (input.content as { text: string }).text = + "Caller changed this during hashing."; + const created = await pending; + expect(created.current.content.text).toBe(draft.content.text); + expect(created.current.contentHash).toMatch(/^[a-f0-9]{64}$/u); + expect(Object.isFrozen(created.current.content)).toBe(true); + expect(created).not.toHaveProperty("published"); + expect(created.current).not.toHaveProperty("audience"); + }); + + it("publishes only an exact verified review snapshot", async () => { + const created = await article(); + await expect( + submitForReview(created, { + expectedRevision: 1, + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "evidence" }); + const inReview = await reviewed(created); + await expect( + publishArticle(inReview, { + expectedRevision: 1, + binding: { ...inReview.review!, contentHash: "b".repeat(64) }, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "approval" }); + const ready = await published(inReview); + expect(ready.state).toBe("published"); + expect(ready.published?.approval.binding).toEqual(inReview.review); + expect(ready.published?.revision.contentHash).toBe( + created.current.contentHash, + ); + expect(ready).not.toHaveProperty("review"); + }); + + it("edits preserve the old publication but invalidate pending review and evidence", async () => { + const first = await published(); + const changed = await reviseArticle(first, { + expectedRevision: 1, + draft: { ...draft, title: "Export a snapshot" }, + context: { ...authorContext(), at: at(4_000) }, + }); + expect(changed.current.number).toBe(2); + expect(changed.current.contentHash).not.toBe(first.current.contentHash); + expect(changed.evidence).toEqual([]); + expect(changed).not.toHaveProperty("review"); + expect(changed.published).toEqual(first.published); + expect(first.current.title).toBe(draft.title); + await expect( + publishArticle(changed, { + expectedRevision: 2, + binding: first.published!.approval.binding, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "transition" }); + await expect( + reviseArticle(changed, { + expectedRevision: 1, + draft, + context: authorContext(), + }), + ).rejects.toMatchObject({ code: "conflict" }); + }); + + it("moves only a draft's collection while retaining the old approved collection binding", async () => { + const initial = await published(); + const other = collection("collection/bot-only"); + const moved = await reviseArticle(initial, { + expectedRevision: 1, + draft, + context: { ...authorContext(other), at: at(4_000) }, + }); + expect(moved.current.collectionId).toBe(other.id); + expect(moved.published?.revision.collectionId).toBe("collection/portal"); + expect( + await isPublicationBoundToCurrentPolicies(moved, collection(), policy), + ).toBe(true); + expect( + await isPublicationBoundToCurrentPolicies(moved, other, policy), + ).toBe(false); + }); + + it("changed audience or validation requirements defeat stale approval, including same-version mutation", async () => { + const current = await reviewed(); + const originalCollection = collection(); + const preview = await previewCollectionPolicy(originalCollection, { + portal: { + enabled: true, + audience: { kind: "permission", permission: "staff.read" }, + }, + bot: { enabled: false }, + }); + const changedCollection = await applyCollectionPolicy(originalCollection, { + preview, + actorId: "staff/admin", + at: at(1_000), + }); + await expect( + publishArticle(current, { + expectedRevision: 1, + binding: current.review!, + reviewerId: "staff/reviewer", + context: reviewContext(changedCollection), + }), + ).rejects.toMatchObject({ field: "approval" }); + const sameVersion = { + ...originalCollection, + policy: { + ...originalCollection.policy, + bot: { + enabled: true as const, + audience: { kind: "permission" as const, permission: "staff.read" }, + }, + }, + }; + await expect( + publishArticle(current, { + expectedRevision: 1, + binding: current.review!, + reviewerId: "staff/reviewer", + context: reviewContext(sameVersion), + }), + ).rejects.toMatchObject({ field: "approval" }); + const changedPolicy = { + ...policy, + requirements: policy.requirements.map((item) => ({ + ...item, + maxAgeMilliseconds: item.maxAgeMilliseconds + 1, + })), + }; + await expect( + publishArticle(current, { + expectedRevision: 1, + binding: current.review!, + reviewerId: "staff/reviewer", + context: { ...reviewContext(), validationPolicy: changedPolicy }, + }), + ).rejects.toMatchObject({ field: "approval" }); + }); + + it("rejects tampered content with a claimed old hash", async () => { + const current = structuredClone(await reviewed()); + const tampered = { + ...current, + current: { + ...current.current, + content: { format: "markdown" as const, text: "Changed after review." }, + }, + }; + await expect( + publishArticle(tampered, { + expectedRevision: 1, + binding: current.review!, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "contentHash" }); + }); + + it("requires operation time to follow the current collection policy while retaining older valid evidence", async () => { + const originalCollection = collection(); + const verified = await checks(await article()); + const originalEvidence = verified.evidence; + const preview = await previewCollectionPolicy(originalCollection, { + portal: { + enabled: true, + audience: { kind: "permission", permission: "workshop.customer" }, + }, + bot: { enabled: false }, + }); + const updatedCollection = await applyCollectionPolicy(originalCollection, { + preview, + actorId: "staff/admin", + at: at(10_000), + }); + const staleContext = reviewContext(updatedCollection, 3_000); + await expect( + submitForReview(verified, { + expectedRevision: 1, + context: staleContext, + }), + ).rejects.toMatchObject({ field: "at" }); + await expect( + recordEvidence(verified, { + evidence: submission(verified), + attestation, + context: staleContext, + }), + ).rejects.toMatchObject({ field: "at" }); + + const inReview = await submitForReview(verified, { + expectedRevision: 1, + context: reviewContext(updatedCollection, 11_000), + }); + expect(inReview.evidence).toEqual(originalEvidence); + await expect( + publishArticle(inReview, { + expectedRevision: 1, + binding: inReview.review!, + reviewerId: "staff/reviewer", + context: staleContext, + }), + ).rejects.toMatchObject({ field: "at" }); + const approved = await published( + inReview, + reviewContext(updatedCollection, 12_000), + ); + expect(approved.published?.approval.reviewedAt).toBe(at(12_000)); + expect(approved.published?.approval.binding.collectionPolicyVersion).toBe( + updatedCollection.policy.version, + ); + expect(approved.evidence).toEqual(originalEvidence); + expect(approved.evidence[0]?.executedAt).toBe(at(1_000)); + }); + + it("rejection and retirement clear authority; a retired article requires a new draft", async () => { + const inReview = await reviewed(); + expect(rejectReview(inReview, 1)).toMatchObject({ state: "draft" }); + expect(rejectReview(inReview, 1)).not.toHaveProperty("review"); + const retired = retireArticle(await published(inReview), 1); + expect(retired.state).toBe("retired"); + expect(retired).not.toHaveProperty("published"); + expect(retired.evidence).toEqual(inReview.evidence); + expect( + await isPublicationBoundToCurrentPolicies(retired, collection(), policy), + ).toBe(false); + await expect( + submitForReview(retired, { + expectedRevision: 1, + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "transition" }); + const restoredDraft = await reviseArticle(retired, { + expectedRevision: 1, + draft, + context: { ...authorContext(), at: at(4_000) }, + }); + expect(restoredDraft).toMatchObject({ + state: "draft", + current: { number: 2 }, + }); + expect(restoredDraft).not.toHaveProperty("published"); + }); +}); + +describe("bound evidence and article-appropriate checks", () => { + it.each(["buildId", "locale"] as const)( + "rejects submitted evidence applicability.%s before hashing", + async (field) => { + const current = await article(); + const evidence = submission(current); + await expect( + recordEvidence(current, { + evidence: { + ...evidence, + applicability: { + ...evidence.applicability, + [field]: undefined, + } as EvidenceSubmission["applicability"], + }, + attestation, + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it.each(["buildId", "locale"] as const)( + "rejects stored evidence applicability.%s before review hashing", + async (field) => { + const verified = await checks(await article()); + const malformed = { + ...verified, + evidence: verified.evidence.map((evidence) => ({ + ...evidence, + applicability: { + ...evidence.applicability, + [field]: undefined, + } as VerificationEvidence["applicability"], + })), + }; + await expect( + submitForReview(malformed, { + expectedRevision: 1, + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it("walkthroughs need workflow evidence in addition to a content check", async () => { + const current = await article("walkthrough"); + const contentOnly = await recordEvidence(current, { + evidence: submission(current), + attestation, + context: reviewContext(), + }); + await expect( + submitForReview(contentOnly, { + expectedRevision: 1, + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "evidence" }); + const complete = await recordEvidence(contentOnly, { + evidence: submission(current, "walkthrough-workflow"), + attestation, + context: reviewContext(), + }); + expect( + ( + await submitForReview(complete, { + expectedRevision: 1, + context: reviewContext(), + }) + ).state, + ).toBe("in-review"); + }); + + it.each([ + { field: "contentHash", value: "b".repeat(64) }, + { field: "stagingBuildId", value: "staging-wrong" }, + { field: "runnerId", value: "untrusted/runner" }, + { field: "executedAt", value: at(-1_000) }, + { field: "executedAt", value: at(10_000) }, + ])("rejects wrong evidence $field=$value", async ({ field, value }) => { + const current = await article(); + await expect( + recordEvidence(current, { + evidence: { ...submission(current), [field]: value }, + attestation, + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "evidence" }); + }); + + it("requires a trusted authenticated-receipt fact, not just a passed result", async () => { + const current = await article(); + await expect( + recordEvidence(current, { + evidence: submission(current), + attestation: { ...attestation, verifiedBy: "agent/self-reported" }, + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "evidence.attestation" }); + }); + + it("does not review failed checks and rechecks freshness at publication", async () => { + const current = await article(); + const failed = await recordEvidence(current, { + evidence: { ...submission(current), result: "failed" }, + attestation, + context: reviewContext(), + }); + await expect( + submitForReview(failed, { + expectedRevision: 1, + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "evidence" }); + const inReview = await reviewed(current); + await expect( + publishArticle(inReview, { + expectedRevision: 1, + binding: inReview.review!, + reviewerId: "staff/reviewer", + context: reviewContext(collection(), 70_000), + }), + ).rejects.toMatchObject({ field: "evidence.executedAt" }); + }); + + it("replacing evidence increments its version and invalidates submitted review", async () => { + const current = await reviewed(); + const replacement = await recordEvidence(current, { + evidence: { + ...submission(current), + steps: ["Rechecked the exact draft."], + }, + attestation: { ...attestation, id: "receipt/rechecked" }, + context: reviewContext(), + }); + expect(replacement.state).toBe("draft"); + expect(replacement).not.toHaveProperty("review"); + expect(replacement.evidence[0]?.version).toBe(2); + expect(replacement.evidence[0]?.hash).not.toBe(current.evidence[0]?.hash); + await expect( + publishArticle(replacement, { + expectedRevision: 1, + binding: current.review!, + reviewerId: "staff/reviewer", + context: reviewContext(), + }), + ).rejects.toMatchObject({ code: "transition" }); + }); +}); + +describe("malformed and bounded source content", () => { + it.each(["buildId", "locale"] as const)( + "rejects explicit undefined at applicability.%s", + async (field) => { + await expect( + createArticle({ + id: "article/undefined-applicability", + draft: { + ...draft, + applicability: { + ...draft.applicability, + [field]: undefined, + } as ArticleDraft["applicability"], + }, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "applicability." + field }); + }, + ); + + it("accepts applicability with optional build and locale omitted", async () => { + const created = await createArticle({ + id: "article/omitted-applicability", + draft: { + ...draft, + applicability: { + productId: draft.applicability.productId, + productVersion: draft.applicability.productVersion, + }, + }, + context: authorContext(), + }); + expect(created.current.applicability).toEqual({ + productId: draft.applicability.productId, + productVersion: draft.applicability.productVersion, + }); + expect(created.current.contentHash).toMatch(/^[a-f0-9]{64}$/u); + const verified = await checks(created); + expect(verified.evidence[0]?.applicability).toEqual( + created.current.applicability, + ); + const inReview = await submitForReview(verified, { + expectedRevision: 1, + context: reviewContext(), + }); + expect(inReview.state).toBe("in-review"); + const approved = await published(inReview); + expect( + await isPublicationBoundToCurrentPolicies(approved, collection(), policy), + ).toBe(true); + }); + + it("rejects extra nested payloads instead of retaining unbounded unsupported fields", async () => { + await expect( + createArticle({ + id: "article/bad", + draft: { + ...draft, + content: { + ...draft.content, + hidden: "unsupported", + } as ArticleDraft["content"], + }, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "content" }); + await expect( + createArticle({ + id: "article/bad", + draft: { + ...draft, + applicability: { + ...draft.applicability, + acl: ["anonymous"], + } as ArticleDraft["applicability"], + }, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "applicability" }); + const current = await article(); + await expect( + recordEvidence(current, { + evidence: { + ...submission(current), + hidden: "unsupported", + } as EvidenceSubmission, + attestation, + context: reviewContext(), + }), + ).rejects.toMatchObject({ field: "evidence" }); + }); + + it("never carries an article-level audience override through a transition", async () => { + const current = { + ...(await article()), + audience: { kind: "anonymous" }, + } as Article; + await expect( + reviseArticle(current, { + expectedRevision: 1, + draft, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "article" }); + }); + + it.each([ + '', + '', + "[unsafe](javascript:alert(1))", + "[unsafe](data:text/html,bad)", + "[unsafe](//other.invalid/path)", + "[unsafe](https://user:secret@other.invalid/path)", + "[unsafe](https:\\\\other.invalid)", + "[reference][unsafe]\n[unsafe]: javascript:alert(1)", + "![unreviewed image](https://other.invalid/image.png)", + "Bad\u0000content", + ])("rejects unsupported content %s", async (body) => { + await expect( + createArticle({ + id: "article/bad", + draft: { ...draft, content: { format: "markdown", text: body } }, + context: authorContext(), + }), + ).rejects.toMatchObject({ code: "invalid" }); + }); + + it("rejects byte overflow and executable content formats", async () => { + await expect( + createArticle({ + id: "article/bad", + draft: { + ...draft, + content: { + format: "markdown", + text: "🙂".repeat(knowledgeLimits.contentBytes / 4 + 1), + }, + }, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "content.text" }); + await expect( + createArticle({ + id: "article/bad", + draft: { + ...draft, + content: { format: "mdx" as "markdown", text: "{execute()}" }, + }, + context: authorContext(), + }), + ).rejects.toMatchObject({ field: "content.format" }); + }); + + it("accepts inert plain text and supported secure links without fetching them", async () => { + const content = await createArticle({ + id: "article/secure", + draft: { + ...draft, + content: { + format: "markdown", + text: "[Guide](https://docs.invalid/guide?x=1&y=2)\n\n[Section](#export)\n\nUse <literal markup>.", + }, + }, + context: authorContext(), + }); + expect(content.current.content.text).toContain("https://docs.invalid"); + expect( + ( + await createArticle({ + id: "article/plain", + draft: { + ...draft, + content: { + format: "plain_text", + text: "[This is plain text](javascript:inert)", + }, + }, + context: authorContext(), + }) + ).current.content.format, + ).toBe("plain_text"); + }); + + it("rejects a validation policy that removes walkthrough workflow checks", async () => { + await expect( + createArticle({ + id: "article/bad", + draft, + context: { + ...authorContext(), + validationPolicy: { + ...policy, + requirements: policy.requirements.filter( + (item) => item.testKind !== "workflow", + ), + }, + }, + }), + ).rejects.toMatchObject({ field: "validationPolicy.requirements" }); + }); +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..7b91d9d --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,21 @@ +export { + applyCollectionPolicy, + createCollection, + previewCollectionPolicy, + type CollectionPolicyPreview, +} from "./collections.js"; +export { + createArticle, + isPublicationBoundToCurrentPolicies, + publishArticle, + recordEvidence, + rejectReview, + retireArticle, + reviseArticle, + submitForReview, + type ArticleDraft, + type DraftContext, + type EvidenceSubmission, + type ReviewContext, +} from "./articles.js"; +export { KnowledgeBaseError, knowledgeLimits } from "./validation.js"; diff --git a/packages/core/src/validation.ts b/packages/core/src/validation.ts new file mode 100644 index 0000000..c5e3074 --- /dev/null +++ b/packages/core/src/validation.ts @@ -0,0 +1,369 @@ +import { + articleKinds, + type Applicability, + type ArticleContent, + type ArticleRevision, + type IsoTimestamp, + type ValidationPolicy, +} from "@pegma/knowledge-base-contracts"; + +export class KnowledgeBaseError extends Error { + override readonly name = "KnowledgeBaseError"; + + constructor( + readonly code: "invalid" | "conflict" | "evidence" | "transition", + readonly field: string, + message: string, + ) { + super(message); + } +} + +/** Schema ceilings, not host throughput, retention, or model budgets. */ +export const knowledgeLimits = { + identifierCharacters: 200, + titleCharacters: 200, + summaryCharacters: 1_000, + contentBytes: 32_768, + tags: 16, + tagCharacters: 64, + requirements: 32, + trustedIdentities: 32, + evidence: 32, + steps: 16, + stepCharacters: 1_000, + artifacts: 8, +} as const; + +export function invalid(field: string, message: string): never { + throw new KnowledgeBaseError("invalid", field, message); +} + +export function keys( + value: object, + allowed: readonly string[], + field: string, +): void { + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).some((key) => !allowed.includes(key)) + ) { + invalid(field, field + " contains unsupported fields"); + } +} + +export function text( + value: string, + field: string, + maximum: number = knowledgeLimits.identifierCharacters, +): void { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > maximum || + value.trim() !== value || + /[\u0000-\u001f\u007f]/u.test(value) + ) { + invalid( + field, + field + " must be bounded, nonempty text without control characters", + ); + } +} + +export function count(value: number, field: string, minimum = 1): void { + if (!Number.isSafeInteger(value) || value < minimum) { + invalid(field, field + " must be a safe integer of at least " + minimum); + } +} + +export function timestamp(value: IsoTimestamp, field: string): number { + const milliseconds = Date.parse(value); + if ( + typeof value !== "string" || + !Number.isFinite(milliseconds) || + new Date(milliseconds).toISOString() !== value + ) { + invalid(field, field + " must be a canonical ISO timestamp"); + } + return milliseconds; +} + +export function hash(value: string, field: string): void { + if (typeof value !== "string" || !/^[a-f0-9]{64}$/u.test(value)) { + invalid(field, field + " must be a lowercase SHA-256 digest"); + } +} + +export function boundedArray( + values: readonly T[], + field: string, + maximum: number, +): void { + if (!Array.isArray(values) || values.length > maximum) { + invalid(field, field + " exceeds its array bound"); + } +} + +export function unique(values: readonly string[], field: string): void { + if (new Set(values).size !== values.length) { + invalid(field, field + " must not contain duplicate values"); + } +} + +export function validateApplicability(value: Applicability): void { + keys( + value, + ["productId", "productVersion", "buildId", "locale"], + "applicability", + ); + for (const field of ["buildId", "locale"] as const) { + if (Object.hasOwn(value, field) && value[field] === undefined) { + invalid( + "applicability." + field, + "Omit an absent optional field instead of setting undefined", + ); + } + } + text(value.productId, "applicability.productId"); + text(value.productVersion, "applicability.productVersion"); + if (value.buildId !== undefined) text(value.buildId, "applicability.buildId"); + if (value.locale !== undefined) { + if (!/^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/u.test(value.locale)) { + invalid("applicability.locale", "Locale must be a bounded language tag"); + } + text(value.locale, "applicability.locale", 64); + } +} + +function safeLink(target: string): boolean { + if ( + target.length > 2_048 || + /[\s\\<>"'\x60\u0000-\u001f\u007f]/u.test(target) || + target.startsWith("//") + ) + return false; + if (target.startsWith("#")) return target.length > 1; + if (!target.startsWith("/") && !target.startsWith("https://")) return false; + try { + const url = new URL(target, "https://knowledge.invalid"); + return ( + url.protocol === "https:" && url.username === "" && url.password === "" + ); + } catch { + return false; + } +} + +/** + * A deliberately restricted source subset. This is not an HTML sanitizer. + * Hosts still use a Markdown renderer with HTML and executable extensions off. + */ +export function validateContent(value: ArticleContent): void { + keys(value, ["format", "text"], "content"); + if (value.format !== "markdown" && value.format !== "plain_text") { + invalid("content.format", "Only Markdown and plain text are supported"); + } + if ( + typeof value.text !== "string" || + value.text.trim().length === 0 || + new TextEncoder().encode(value.text).byteLength > + knowledgeLimits.contentBytes || + /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(value.text) + ) { + invalid( + "content.text", + "Content must be nonempty bounded text without control bytes", + ); + } + if (/<\s*(?:[a-zA-Z][\w:-]*\b|[!/?])/u.test(value.text)) { + invalid( + "content.text", + "Raw HTML and JSX are unsupported; escape literal markup", + ); + } + if (value.format === "plain_text") return; + // No embedded images, reference definitions, autolinks, or arbitrary MDX. + if ( + /!\[/u.test(value.text) || + /^\s{0,3}\[[^\]]+\]:/mu.test(value.text) || + /<[^>\n]+>/u.test(value.text) + ) { + invalid( + "content.text", + "Use supported inline links and non-executable Markdown", + ); + } + // Inline code and fenced code remain plain Markdown; never execute either. + const links = value.text.matchAll(/\]\(([^)]*)\)/gu); + for (const link of links) { + if (!safeLink(link[1]!)) + invalid("content.link", "Unsupported or unsafe Markdown link"); + } + // Reference-style links are excluded rather than ambiguously interpreted. + if (/\]\s*\[/u.test(value.text)) { + invalid("content.link", "Reference-style Markdown links are unsupported"); + } +} + +export function validatePolicy(policy: ValidationPolicy): void { + keys(policy, ["id", "version", "requirements"], "validationPolicy"); + text(policy.id, "validationPolicy.id"); + count(policy.version, "validationPolicy.version"); + boundedArray( + policy.requirements, + "validationPolicy.requirements", + knowledgeLimits.requirements, + ); + const ids: string[] = []; + for (const requirement of policy.requirements) { + keys( + requirement, + ["id", "kind", "testKind", "maxAgeMilliseconds", "trustedRunnerIds"], + "requirement", + ); + text(requirement.id, "requirement.id"); + ids.push(requirement.id); + if (!articleKinds.includes(requirement.kind)) + invalid("requirement.kind", "Unknown article kind"); + text(requirement.testKind, "requirement.testKind", 64); + count(requirement.maxAgeMilliseconds, "requirement.maxAgeMilliseconds"); + boundedArray( + requirement.trustedRunnerIds, + "requirement.trustedRunnerIds", + knowledgeLimits.trustedIdentities, + ); + if (requirement.trustedRunnerIds.length === 0) { + invalid( + "requirement.trustedRunnerIds", + "Each check must name trusted runners", + ); + } + for (const runner of requirement.trustedRunnerIds) + text(runner, "requirement.runner"); + unique(requirement.trustedRunnerIds, "requirement.trustedRunnerIds"); + } + unique(ids, "validationPolicy.requirements"); + for (const kind of articleKinds) { + const requirements = policy.requirements.filter( + (item) => item.kind === kind, + ); + if (!requirements.some((item) => item.testKind === "content")) { + invalid( + "validationPolicy.requirements", + "Every article kind requires a content check", + ); + } + if ( + kind === "walkthrough" && + !requirements.some((item) => item.testKind === "workflow") + ) { + invalid( + "validationPolicy.requirements", + "Walkthroughs require a workflow check", + ); + } + } +} + +export function validateRevisionFields( + revision: Omit, +): void { + keys( + revision, + [ + "articleId", + "number", + "collectionId", + "kind", + "title", + "summary", + "content", + "tags", + "applicability", + "validationPolicy", + "createdBy", + "createdAt", + ], + "articleRevision", + ); + text(revision.articleId, "articleId"); + count(revision.number, "articleRevision"); + text(revision.collectionId, "collectionId"); + if (!articleKinds.includes(revision.kind)) + invalid("kind", "Unknown article kind"); + text(revision.title, "title", knowledgeLimits.titleCharacters); + text(revision.summary, "summary", knowledgeLimits.summaryCharacters); + validateContent(revision.content); + boundedArray(revision.tags, "tags", knowledgeLimits.tags); + for (const tag of revision.tags) + text(tag, "tag", knowledgeLimits.tagCharacters); + unique(revision.tags, "tags"); + validateApplicability(revision.applicability); + keys(revision.validationPolicy, ["id", "version"], "validationPolicy"); + text(revision.validationPolicy.id, "validationPolicy.id"); + count(revision.validationPolicy.version, "validationPolicy.version"); + text(revision.createdBy, "createdBy"); + timestamp(revision.createdAt, "createdAt"); +} + +export function canonical(value: unknown): string { + if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"; + if (value !== null && typeof value === "object") { + return ( + "{" + + Object.keys(value) + .sort() + .map( + (key) => + JSON.stringify(key) + + ":" + + canonical((value as Record)[key]), + ) + .join(",") + + "}" + ); + } + const encoded = JSON.stringify(value); + if (encoded === undefined) + invalid("hash", "Hash input must contain JSON values only"); + return encoded; +} + +export async function digest(value: unknown): Promise { + const bytes = new TextEncoder().encode(canonical(value)); + const result = await crypto.subtle.digest("SHA-256", bytes); + return Array.from(new Uint8Array(result), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} + +export function immutable(value: T): T { + if (value !== null && typeof value === "object") { + for (const child of Object.values(value)) immutable(child); + Object.freeze(value); + } + return value; +} + +export async function verifyRevision(revision: ArticleRevision): Promise { + if ( + revision === null || + typeof revision !== "object" || + Array.isArray(revision) + ) { + invalid("articleRevision", "Revision must be an object"); + } + const { contentHash, ...fields } = revision; + validateRevisionFields(fields); + hash(contentHash, "contentHash"); + if ((await digest(fields)) !== contentHash) { + throw new KnowledgeBaseError( + "conflict", + "contentHash", + "Revision content no longer matches its hash", + ); + } +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..da28257 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../contracts" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..18f294e --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,886 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@types/node': + specifier: 26.6.6 + version: 26.6.6 + prettier: + specifier: 3.9.10 + version: 3.9.10 + typescript: + specifier: 7.0.2 + version: 7.0.2 + vitest: + specifier: 5.0.5 + version: 5.0.5(@types/node@26.6.6)(vite@8.3.6(@types/node@26.6.6)) + + packages/contracts: + dependencies: + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + + packages/core: + dependencies: + '@pegma/knowledge-base-contracts': + specifier: 0.1.0 + version: link:../contracts + +packages: + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@pegma/spine@0.1.2': + resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==} + engines: {node: '>=22'} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/node@26.6.6': + resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + prettier@3.9.10: + resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==} + engines: {node: '>=14'} + hasBin: true + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + vite@8.3.6: + resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + +snapshots: + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.156.0': {} + + '@pegma/spine@0.1.2': {} + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.10': {} + + '@types/node@26.6.6': + dependencies: + undici-types: 8.9.0 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/mocker@5.0.5(vite@8.3.6(@types/node@26.6.6))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.6(@types/node@26.6.6) + + '@vitest/spy@5.0.5': {} + + assertion-error@2.0.1: {} + + chai@6.3.0: {} + + detect-libc@2.1.2: {} + + es-module-lexer@2.3.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + nanoid@3.3.20: {} + + obug@3.0.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + prettier@3.9.10: {} + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + source-map-js@1.2.2: {} + + std-env@4.3.0: {} + + tinybench@6.2.3: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@8.9.0: {} + + vite@8.3.6(@types/node@26.6.6): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.6 + fsevents: 2.3.3 + + vitest@5.0.5(@types/node@26.6.6)(vite@8.3.6(@types/node@26.6.6)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.6(@types/node@26.6.6)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.3 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.6(@types/node@26.6.6) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.6 + transitivePeerDependencies: + - msw + + why-is-node-running@3.2.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..87d3040 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,4 @@ +packages: + - "packages/*" + +linkWorkspacePackages: true diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs new file mode 100644 index 0000000..71665c0 --- /dev/null +++ b/scripts/release-packages.mjs @@ -0,0 +1,277 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + access, + copyFile, + mkdtemp, + mkdir, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, delimiter, dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const packages = [ + { directory: "contracts", name: "@pegma/knowledge-base-contracts" }, + { directory: "core", name: "@pegma/knowledge-base-core" }, +]; +const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; + +function run(command, arguments_, cwd, env = process.env) { + const result = spawnSync(command, arguments_, { + cwd, + env, + encoding: "utf8", + shell: false, + maxBuffer: 8 * 1024 * 1024, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error( + `${basename(command)} failed (${String(result.status)}): ${result.stderr || result.stdout}`, + ); + } + return result.stdout.trim(); +} + +async function exists(path) { + try { + await access(path); + return true; + } catch { + return false; + } +} + +async function npmCliPath() { + const directories = [ + dirname(process.execPath), + ...(process.env.PATH ?? "").split(delimiter).filter(Boolean), + ]; + const candidates = directories.map((directory) => + join(directory, "node_modules", "npm", "bin", "npm-cli.js"), + ); + if (basename(process.env.npm_execpath ?? "") === "npm-cli.js") { + candidates.unshift(process.env.npm_execpath); + } + for (const directory of directories) { + const executable = join(directory, "npm"); + if (await exists(executable)) { + const target = await realpath(executable); + if (basename(target) === "npm-cli.js") candidates.push(target); + } + } + for (const candidate of candidates) { + if (await exists(candidate)) return candidate; + } + throw new Error("Cannot locate npm-cli.js beside Node.js or on PATH."); +} + +async function json(path) { + return JSON.parse(await readFile(path, "utf8")); +} + +async function validatePackages() { + const manifests = []; + for (const specification of packages) { + const directory = join(root, "packages", specification.directory); + const manifest = await json(join(directory, "package.json")); + assert.equal(manifest.name, specification.name); + assert.match(manifest.version, stableVersion); + assert.equal(manifest.version, manifests[0]?.version ?? manifest.version); + assert.equal( + manifest.private, + undefined, + "Published packages cannot be private.", + ); + assert.equal(manifest.type, "module"); + assert.equal(manifest.license, "MIT"); + assert.equal(manifest.publishConfig?.access, "public"); + assert.equal(manifest.engines?.node, ">=22"); + assert.ok( + ["pnpm run build", "pnpm run --silent build"].includes( + manifest.scripts?.prepack, + ), + `${manifest.name} must build during prepack.`, + ); + assert.deepEqual(manifest.exports, { + ".": { types: "./dist/index.d.ts", import: "./dist/index.js" }, + }); + assert.deepEqual( + manifest.dependencies, + specification.directory === "core" + ? { "@pegma/knowledge-base-contracts": manifest.version } + : { "@pegma/spine": "0.1.2" }, + ); + for (const document of ["README.md", "LICENSE"]) { + const content = await readFile(join(directory, document), "utf8"); + assert.ok( + content.trim().length > 0, + `${manifest.name} requires its own ${document}.`, + ); + if (document === "LICENSE") assert.match(content, /MIT License/u); + } + const configuration = await json(join(directory, "tsconfig.json")); + assert.ok( + configuration.exclude?.includes("src/**/*.test.ts"), + `${manifest.name} must exclude compiled tests.`, + ); + manifests.push(manifest); + } + return manifests; +} + +function validateInventory(metadata) { + const paths = metadata.files.map(({ path }) => path); + for (const required of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.js", + "dist/index.d.ts", + ]) { + assert.ok(paths.includes(required), `Tarball is missing ${required}.`); + } + for (const path of paths) { + const parts = path.split("/"); + assert.ok(!parts.some((part) => part === "." || part === "..")); + assert.ok( + ["package.json", "README.md", "LICENSE"].includes(path) || + (/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( + path, + ) && + !/\.(?:test|spec)\./u.test(path)), + `Unexpected packaged file: ${path}`, + ); + } +} + +async function prepare(mode) { + assert.ok( + ["check", "pack"].includes(mode), + "Usage: release-packages.mjs check|pack", + ); + assert.equal( + process.argv.length, + 3, + "No additional arguments are supported.", + ); + const manifests = await validatePackages(); + const npm = await npmCliPath(); + const temporaryParent = await realpath(tmpdir()); + const temporary = await mkdtemp(join(temporaryParent, "pegma-kb-release-")); + try { + const npmrc = join(temporary, "npmrc"); + await writeFile(npmrc, "registry=https://registry.npmjs.org/\n"); + const env = { + ...process.env, + npm_config_userconfig: npmrc, + npm_config_registry: "https://registry.npmjs.org/", + }; + const artifacts = []; + for (const [index, specification] of packages.entries()) { + const output = run( + process.execPath, + [ + npm, + "pack", + "--json", + "--ignore-scripts=false", + "--pack-destination", + temporary, + ], + join(root, "packages", specification.directory), + env, + ); + const packed = JSON.parse(output); + assert.equal(packed.length, 1); + const metadata = packed[0]; + assert.equal(metadata.name, specification.name); + assert.equal(metadata.version, manifests[index].version); + assert.equal(basename(metadata.filename), metadata.filename); + validateInventory(metadata); + const bytes = await readFile(join(temporary, metadata.filename)); + assert.equal( + createHash("sha1").update(bytes).digest("hex"), + metadata.shasum, + ); + assert.equal( + `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + metadata.integrity, + ); + artifacts.push(metadata); + } + const consumer = join(temporary, "consumer"); + await mkdir(consumer); + await writeFile( + join(consumer, "package.json"), + JSON.stringify({ + name: "knowledge-base-artifact-smoke", + private: true, + type: "module", + dependencies: Object.fromEntries( + artifacts.map(({ name, filename }) => [ + name, + pathToFileURL(join(temporary, filename)).href, + ]), + ), + }), + ); + run( + process.execPath, + [ + npm, + "install", + "--ignore-scripts", + "--package-lock=false", + "--no-audit", + "--no-fund", + ], + consumer, + env, + ); + run( + process.execPath, + [ + "--input-type=module", + "--eval", + packages + .map(({ name }) => `await import(${JSON.stringify(name)});`) + .join("\n"), + ], + consumer, + env, + ); + if (mode === "pack") { + const releases = join(root, ".release"); + await mkdir(releases, { recursive: true }); + const destination = await mkdtemp(join(releases, "knowledge-base-")); + for (const { filename } of artifacts) { + await copyFile(join(temporary, filename), join(destination, filename)); + } + await writeFile( + join(destination, "manifest.json"), + `${JSON.stringify({ schemaVersion: 1, artifacts }, null, 2)}\n`, + ); + console.log(`Prepared verified artifacts in ${destination}`); + } + console.log( + `Verified packaging and clean-consumer imports for ${artifacts.length} packages.`, + ); + } finally { + const cleanup = await realpath(temporary); + assert.equal(dirname(cleanup), temporaryParent); + assert.ok(basename(cleanup).startsWith("pegma-kb-release-")); + await rm(cleanup, { recursive: true, force: true }); + } +} + +prepare(process.argv[2]).catch((error) => { + console.error(error.message); + process.exitCode = 1; +}); diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..012a496 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "composite": true, + "declaration": true, + "declarationMap": true, + "exactOptionalPropertyTypes": true, + "forceConsistentCasingInFileNames": true, + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmitOnError": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "target": "ES2022", + "verbatimModuleSyntax": true + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..632a88f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./packages/contracts" }, + { "path": "./packages/core" } + ] +} diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..857994d --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "noEmit": true + }, + "include": [ + "packages/*/src/**/*.test.ts", + "tests/**/*.test.ts", + "vitest.config.ts" + ] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..a191fca --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["packages/**/*.test.ts", "tests/**/*.test.ts"], + exclude: ["**/dist/**", "**/node_modules/**"], + }, +});