From f0745bfcdfbda25593b08a1b7e61eb582fc62284 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 7 Nov 2026 01:57:24 -0500 Subject: [PATCH 1/2] test: add native D1 conformance and synthetic KB composition --- .github/workflows/ci.yml | 3 + AGENTS.md | 12 +- README.md | 18 +- docs/HOST_COMPOSITION.md | 10 + docs/RELEASING.md | 12 +- docs/SOURCE_PREPARATION.md | 149 ++++++ examples/composition/README.md | 60 +++ examples/composition/composition.ts | 325 ++++++++++++ examples/composition/run.ts | 17 + package.json | 6 +- pnpm-lock.yaml | 519 +++++++++++++++++++ pnpm-workspace.yaml | 3 + test/README.md | 65 ++- test/application-stores.ts | 2 + test/d1.ts | 55 ++ tests/application-review-regressions.test.ts | 10 +- tests/application-storage.test.ts | 31 +- tests/application.test.ts | 46 +- tests/composition.test.ts | 146 ++++++ tests/d1-isolation.test.ts | 115 ++++ tests/retrieval-bounds.test.ts | 45 +- tests/retrieval-maintenance.test.ts | 43 +- tests/retrieval-review-regressions.test.ts | 18 +- tests/retrieval.test.ts | 37 +- tsconfig.test.json | 2 + vitest.config.ts | 3 + 26 files changed, 1612 insertions(+), 140 deletions(-) create mode 100644 docs/SOURCE_PREPARATION.md create mode 100644 examples/composition/README.md create mode 100644 examples/composition/composition.ts create mode 100644 examples/composition/run.ts create mode 100644 test/d1.ts create mode 100644 tests/composition.test.ts create mode 100644 tests/d1-isolation.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8431906..f502ea7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ jobs: validate: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -40,5 +41,7 @@ jobs: run: pnpm run check - name: Run tests run: pnpm test + - name: Run synthetic composition + run: pnpm example - name: Check package artifacts run: pnpm run release:check diff --git a/AGENTS.md b/AGENTS.md index 9eacbc3..723344c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,9 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. application services. KB-03 extends the application with bounded retrieval, authoritative confirmation, and repair; it adds no package. API/MCP and live host interfaces remain later tasks; do not create their packages early. +- Independent partial KB-05 source preparation adds local D1 conformance and + a public synthetic composition. It does not complete KB-04 credentials or + the full KB-05 release/publication task. All three packages remain unpublished. - 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. @@ -46,13 +49,18 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. 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. +- D1 consumer fixtures use the released adapter with a real local Miniflare + binding, not a fake port or cast. Each factory call gets an isolated database; + register asynchronous disposal before initialization and clean up failures. + Keep native workers/timeouts bounded. Fixture contexts/receipts are synthetic + trust inputs, not live authentication or staging proof. - 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 format:check`, `pnpm run check`, `pnpm test`, `pnpm example`, 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. @@ -71,3 +79,5 @@ durable operations and [host composition](docs/HOST_COMPOSITION.md) before changing authorization, verifier, replay, or DTO boundaries. For KB-03, read [retrieval](docs/RETRIEVAL.md) and the declared projection layout before changing query work, citations, or repair. +For partial KB-05, read [source preparation](docs/SOURCE_PREPARATION.md) before +changing local D1 fixtures, synthetic composition, or release-readiness claims. diff --git a/README.md b/README.md index d1c6f41..c63777b 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,11 @@ and exact publication approval. It requires no GitHub connection or AI provider. > Development status: KB-01 provides contracts and pure domain transitions; > KB-02 adds authorized application/persistence source, and KB-03 extends that > application with bounded retrieval and repair. Implementation and repository -> gates determine completion. All three packages are unpublished. API/MCP and -> live customer/staff interfaces remain later tasks. This repository is not yet -> an operational hosted KB or a production dependency. +> gates determine source evidence. Independent partial KB-05 preparation adds +> local D1 conformance and a public synthetic example. KB-04 credentials and the +> full KB-05 release task remain unfinished. All three packages are unpublished +> at `0.1.0`. API/MCP and live customer/staff interfaces remain later tasks. This +> repository is not yet an operational hosted KB or a production dependency. | Package | Scope | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | @@ -49,6 +51,13 @@ bot-answer uses have separate safe citations; bot-only knowledge does not grant an article browse capability. Read [retrieval](docs/RETRIEVAL.md) for physical work/source budgets, whole-article token accounting, and repair. +Partial [source preparation](docs/SOURCE_PREPARATION.md) runs shared public KB +conformance against memory, local Azurite, and real local Miniflare D1 through +the released D1 adapter. The [synthetic composition](examples/composition/README.md) +demonstrates the public author/test/review/publish/retrieve flow with fictional +trust inputs. Local emulators and that example establish neither live Workers +deployment nor scoped API/MCP credentials, publication, or host acceptance. + Develop on Node 22 or 24 with pnpm 10.34.5: ```sh @@ -56,6 +65,7 @@ pnpm install --frozen-lockfile pnpm run format:check pnpm run check pnpm test +pnpm example pnpm run release:check ``` @@ -63,6 +73,8 @@ The npm and pnpm workspace declarations deliberately name the same source packages: pnpm links them for development, while npm supplies artifact packing. The release check installs all three tarballs in a consumer outside either workspace to verify dependency resolution without source links. +Frozen installation permits the pinned native `workerd` install script only; +test workers/timeouts and per-factory D1 disposal remain bounded. 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. diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index b4b858d..af20268 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -10,6 +10,16 @@ not an HTTP server, an identity system, or an operational MCP endpoint. See [declared collections](COLLECTIONS.md) for the required layout, CAS, admission, and replay design. +Independent partial KB-05 [source preparation](SOURCE_PREPARATION.md) adds +shared memory/Azurite/local-D1 conformance and a +[public synthetic composition](../examples/composition/README.md). The D1 +fixture passes a real Miniflare binding directly to the released +`@pegma/storage-cloudflare-d1@0.4.1` adapter with isolated per-factory cleanup. +It is local consumer evidence, not a deployed Workers binding or production +acceptance. The example's resolved contexts and receipt registry stand in for +trusted host facts; they authenticate no real browser, agent, or staging run. +KB-04's credential/client flow and full KB-05 publication remain unfinished. + The host owns identity verification, scoped local-agent credentials, current authorization resolution, browser/transport protections, store construction, clock/logger, trusted attestation verification, source-resource authorization, diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 7456022..336fe60 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -9,6 +9,11 @@ domain, authorized application, and bounded retrieval source plus packaging checks; their repository gates determine task completion. They do not publish, create tags/releases, configure credentials, or enable a publish workflow. +Independent partial KB-05 [source preparation](SOURCE_PREPARATION.md) adds the +local Miniflare D1 consumer fixture, shared three-backend conformance, and a +public synthetic example. This is not completion of KB-04 or full KB-05. No +package is added or published; all three remain unpublished at `0.1.0`. + 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. @@ -22,6 +27,7 @@ pnpm install --frozen-lockfile pnpm run format:check pnpm run check pnpm test +pnpm example pnpm run release:check ``` @@ -70,8 +76,10 @@ release procedure, not proof that external publisher settings exist. - [ ] Confirm package-name ownership and organization publishing permissions. - [ ] Complete KB-05's advertised package/adapter and dual-store release - criteria. KB-02/KB-03 memory/Azurite evidence does not establish the later D1 - consumer fixture, MCP client flow, or either host's production readiness. + criteria. Partial source preparation supplies a real local D1 consumer + fixture and synthetic composition subject to current-head gates. It does + not establish KB-04's authenticated real-client flow, live Workers/host + acceptance, or complete package/bootstrap/publication readiness. 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, diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md new file mode 100644 index 0000000..cada517 --- /dev/null +++ b/docs/SOURCE_PREPARATION.md @@ -0,0 +1,149 @@ +# KB-05 source preparation + +## Scope and readiness + +This is an independent, partial KB-05 source-preparation slice. It adds a real +local D1 consumer fixture and a public synthetic composition example over the +existing contracts/core/application packages. It does not finish KB-04 or the +full KB-05 release task. All three KB packages remain unpublished at source +version `0.1.0`. + +| Evidence area | This source slice | Separate remaining proof | +| ---------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | +| Storage consumer | Shared public KB suites on memory, local Azurite, and local Miniflare D1 | Production Azure/Workers configuration, operations, and host acceptance | +| Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, scoped API/MCP credentials, and UI | +| Artifacts | Existing three-package pack/import checks | First publication, trusted-publisher setup, registry integrity/provenance, and released consumers | +| Task readiness | Current-head repository gates establish this slice's evidence | KB-04 credential/client proof and all remaining KB-05 exit criteria | + +No test counts or pass verdicts are implied by this document. Record verified +current-head gate results before treating the source slice as validated. +Local emulator and fixture results are not production or live Workers proof. + +## Pinned local D1 consumer + +The source dependency snapshot was verified on **2026-11-07**. These are exact +repository pins, not a claim about the latest available versions: + +| Dependency/configuration | Pin | +| -------------------------------- | ---------------------------------------- | +| Released D1 adapter | `@pegma/storage-cloudflare-d1@0.4.1` | +| Storage contract | `@pegma/storage-core@0.4.0` | +| Local emulator | `miniflare@4.20260730.0` | +| Miniflare declaration dependency | `@cloudflare/workers-types@5.20260730.1` | +| Locked native runtime | `workerd@1.20260730.1` (transitive) | +| Local compatibility date | `2026-07-28` | +| Repository toolchain | Node 22/24, `pnpm@10.34.5` | + +[test/d1.ts](../test/d1.ts) obtains Miniflare's real `getD1Database("DB")` +binding and passes it directly to the released `createCloudflareD1Store`. +It uses no handwritten SQL/HTTP facade, fake D1 binding, or type cast to hide +an incompatible adapter port. Miniflare owns the local D1 execution and native +runtime; the KB still owns no database implementation. Cloudflare types are +test tooling, not a new public core dependency. + +Each factory invocation creates a fresh Miniflare runtime and randomly named +D1 database, even when a test asks for multiple stores. It uses loopback with +an ephemeral port, `cf: false`, and `d1Persist: false`; no live Cloudflare +account or persistent production database participates. + +The fixture registers Vitest's `onTestFinished` cleanup before native +construction or binding lookup. A shared memoized asynchronous disposal path +handles both initialization failure and normal completion; cleanup failures +remain visible, including combined setup/cleanup failure. Calling this helper +outside a Vitest test fails before a native runtime can be left behind. +[D1 isolation cases](../tests/d1-isolation.test.ts) exercise factory isolation. + +## Shared conformance and bounded execution + +[test/application-stores.ts](../test/application-stores.ts) supplies the same +store-factory surface to public KB application, storage, retrieval, and +regression suites. Memory uses Storage Core's real memory adapter; Azurite +uses the released Azure Tables adapter and unique table names; D1 uses the +released D1 adapter above. Tests call public application entry points and the +actual declared codecs. No parallel KB repository or authorization engine is +introduced. [test/README.md](../test/README.md) records fixture usage. + +Memory stores are fresh per factory call. Azurite's emulator lifecycle and +guarded temporary-directory cleanup remain in +[test/azurite.ts](../test/azurite.ts). D1's per-factory native disposal is +separate from that global emulator lifecycle. Do not reuse a D1 database for +convenience or omit asynchronous cleanup on a failing test. + +Native execution has explicit repository bounds: + +| Control | Bound | +| ----------------- | ----------------------------- | +| Vitest workers | At most 4 | +| Test timeout | 180 seconds | +| Hook timeout | 30 seconds | +| D1 disposal hook | 30 seconds | +| CI validation job | 30 minutes per Node 22/24 job | + +Windows development measurements include local Node-to-workerd RPC and setup +overhead across the real adapter's operations. These bounded budgets allow +that native conformance work; assertions, cleanup, and full current-head gates +still establish correctness. Local elapsed time is not production D1 latency +or a performance certification. + +The frozen pnpm workspace explicitly permits only the pinned `workerd` +dependency's install script through `onlyBuiltDependencies`. It does not +authorize unrelated dependency scripts. New workspaces use the normal pinned +installation path: + +```sh +pnpm install --frozen-lockfile +pnpm run format:check +pnpm run check +pnpm test +pnpm example +pnpm run release:check +``` + +The CI workflow runs those checks, including the synthetic example, on Node +22 and 24. A local run does not substitute for required current-head CI or +reviews. Adapter conformance also does not certify production throughput, +retention, backups, network protections, or distributed deployment behavior. + +## Public synthetic composition + +[examples/composition](../examples/composition/README.md) is repository-owned +fictional source. `createExampleComposition` accepts a host Store (memory by +default), and `runCompleteExampleFlow` exercises the public KB services. The +example imports no test-only helper and contains no commercial host routes, +credentials, customer data, or operational topology. + +Its resolved access contexts are synthetic trusted inputs, not authenticated +browser/API requests. A private receipt registry binds immutable serialized +synthetic-run facts to the exact principal, article revision, whole evidence +submission, and governance configuration. The verifier returns a fixed +synthetic attester only after lookup and exact comparison; it does not echo +caller-supplied `passed` or runner identity as proof. This demonstrates the +host trust seam, not a production runner, OAuth server, signature scheme, or +live staging test. + +Source checks, review/publication, audience separation, and safe retrieval +still pass through the real application. The example does not establish real +external source-reference eligibility. One UTF-8 byte counts as one fixture +token; that is not a provider tokenizer or billing measurement. No model +provider or GitHub connection is required. + +[tests/composition.test.ts](../tests/composition.test.ts) runs the same public +flow through all three store factories and defines negative cases for tampered +evidence, author publication authority, private-data exclusion, bot-only +citations, and retirement with old projection hints. Current-head gate results +remain the evidence of execution. + +## Remaining gates + +KB-04 must still establish the real scoped/revocable/audience-bound author +credential and protected-resource/client flow. Manually supplied fixture +contexts do not close that prerequisite. The optional API/MCP contract and +real local-client author/test/evidence loop require their own task evidence. + +The full KB-05 release candidate still needs its advertised package/adapter +and client criteria, reviewed bootstrap/trusted-publisher configuration, exact +registry publication, artifact/provenance verification, and released consumer +checks. See [release operations](RELEASING.md). No empty adapter package, +release tag, publication, or host activation is created by this source slice. +Hosts must wait for exact released artifacts rather than adopting branches, +copied source, local paths, or unpublished production tarballs. diff --git a/examples/composition/README.md b/examples/composition/README.md new file mode 100644 index 0000000..91f82c7 --- /dev/null +++ b/examples/composition/README.md @@ -0,0 +1,60 @@ +# Fictional Knowledge Base composition + +This runnable Node example uses public package entry points and Storage Core's +real memory Store. It demonstrates authoring, bound synthetic verification +evidence, separate staff review/publication, bounded index repair, and bot-source +retrieval followed immediately by citation confirmation. + +Run from the repository root on Node 22 or 24 after installing the repository's +pinned dependencies: + +```sh +pnpm run example +``` + +[`composition.ts`](composition.ts) exports `createExampleComposition(store?)` +and `runCompleteExampleFlow(composition)`. The optional Store defaults to +`createMemoryStore()`; the example imports no test helpers. [`run.ts`](run.ts) +prints a safe completion summary. These are workspace source examples; the KB +packages remain unpublished and cannot yet be installed as production releases. + +The flow creates a fictional workshop collection with portal use disabled and a +separate bot audience. A synthetic author creates a walkthrough, submits its +content/workflow evidence, and requests review. A different synthetic staff +context publishes the exact review snapshot. Each mutation uses the current +application generation, rather than the content revision. A finite repair loop +requires the article's projection to converge before retrieval. + +The synthetic runner recognizes the known fictional procedure and constructs +fixed check results. Its private registry stores immutable serialized bindings +to the actor, complete article revision/hash, complete evidence submission, and +governance configuration. The verifier accepts only an exact registry match; +editing submitted evidence cannot create a valid receipt. This scripted fixture +does not execute a product guide on staging or authenticate any real runner. + +All AccessContext values are explicitly trusted synthetic inputs. They are not +credentials, request bodies, a role model, or an authentication implementation. +The customer's context governs retrieval; broad staff authority never supplies +the answer audience. Bot-only citations carry a label and omit a portal browse +reference. The returned serialization contains approved article content, not +private evidence or verifier facts. One UTF-8 byte counts as one fixture token; +that counter is unrelated to a provider's tokenizer or billing. + +[`composition.test.ts`](../../tests/composition.test.ts) runs the same public flow +over the real memory, Azurite, and local Miniflare D1 Store factories. It also +checks tampered evidence, denied author publication, private-data exclusion, +bot-only citations, and refusal of references after retirement while an old +projection remains. Each D1 test owns and disposes its local runtime. + +A host must supply authenticated and freshly resolved scoped access, an actual +trusted evidence verifier and staging execution/artifact integration, a durable +Store, operational clock, the intended model's local token counter, safe content +rendering, and durable maintenance scheduling. The default memory Store loses +state when the process exits. Confirmation is a current observation, not an +authorization lease; use confirmed sources promptly and resolve access again +for the next operation. + +This is independent KB-05 source preparation. It establishes no KB-04 API/MCP +credential proof, live host acceptance, deployment, publication, or production +readiness. See [host composition](../../docs/HOST_COMPOSITION.md) and +[release operations](../../docs/RELEASING.md) for the remaining boundaries. diff --git a/examples/composition/composition.ts b/examples/composition/composition.ts new file mode 100644 index 0000000..564ab9f --- /dev/null +++ b/examples/composition/composition.ts @@ -0,0 +1,325 @@ +/** + * Fictional, source-only composition: no transport, authenticated identity, + * live staging runner, model provider, or production durability claim. + */ +import type { AccessContext } from "@pegma/authorization-core"; +import { + createKnowledgeBaseApplication, + type EvidenceVerificationRequest, + type GovernanceConfiguration, +} from "@pegma/knowledge-base-application"; +import { + articleKinds, + knowledgePermissions, + type ValidationPolicy, +} from "@pegma/knowledge-base-contracts"; +import type { + ArticleDraft, + EvidenceSubmission, +} from "@pegma/knowledge-base-core"; +import { createMemoryStore, type Store } from "@pegma/storage-core"; +import assert from "node:assert/strict"; +import { isDeepStrictEqual } from "node:util"; + +/** Trusted fixture inputs, never an example of accepting access from a client. */ +function syntheticAccess( + principalId: string, + permissions: readonly string[], +): AccessContext { + return Object.freeze({ + principalId, + policyVersion: "synthetic-example-1", + roles: Object.freeze([]), + entitlements: Object.freeze([]), + permissions: Object.freeze([...permissions]), + }); +} + +export function createExampleComposition(store: Store = createMemoryStore()) { + const articleId = "article/fictional-export"; + const collectionId = "collection/fictional-workshop"; + const audiencePermission = "fictional.workshop.customer"; + const contexts = Object.freeze({ + administrator: syntheticAccess("synthetic/staff/administrator", [ + knowledgePermissions.collectionRead, + knowledgePermissions.collectionManage, + knowledgePermissions.validationManage, + ]), + author: syntheticAccess("synthetic/runner/author", [ + knowledgePermissions.collectionRead, + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, + knowledgePermissions.reviewSubmit, + ]), + reviewer: syntheticAccess("synthetic/staff/reviewer", [ + knowledgePermissions.collectionRead, + knowledgePermissions.draftRead, + knowledgePermissions.review, + knowledgePermissions.publish, + knowledgePermissions.retire, + knowledgePermissions.indexManage, + ]), + customer: syntheticAccess("synthetic/customer/workshop", [ + knowledgePermissions.articleRead, + knowledgePermissions.botRead, + audiencePermission, + ]), + }); + const guide: ArticleDraft = { + kind: "walkthrough", + title: "Download a workspace export", + summary: "Save a fictional workshop workspace as a CSV spreadsheet.", + content: { + format: "markdown", + text: "1. Open Workspace.\n2. Choose Export.\n3. Download the CSV spreadsheet.", + }, + tags: ["download", "export", "csv", "spreadsheet"], + applicability: { + productId: "fictional-workshop", + productVersion: "1.0", + buildId: "synthetic-staging-42", + locale: "en-US", + }, + }; + const policy: ValidationPolicy = { + id: "validation/fictional-workshop", + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: `${kind}-content`, + kind, + testKind: "content", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: [contexts.author.principalId], + })), + { + id: "walkthrough-workflow", + kind: "walkthrough", + testKind: "workflow", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: [contexts.author.principalId], + }, + ], + }; + const configuration: GovernanceConfiguration = { + validationPolicy: { id: policy.id, version: policy.version }, + expectedStagingBuildId: "synthetic-staging-42", + trustedAttesterIds: ["synthetic/staff/verifier"], + }; + let time = Date.parse("2026-11-07T12:00:00.000Z"); + let commandOrdinal = 0; + let receiptOrdinal = 0; + const clock = { now: () => new Date(time).toISOString() }; + // Only the scripted runner below writes these private, immutable strings. + // They are synthetic external receipts, not an alternative KB persistence. + const receipts = new Map(); + function binding(request: Omit) { + return { + principalId: request.access.principalId, + article: request.article, + submission: request.submission, + configuration: request.configuration, + }; + } + const app = createKnowledgeBaseApplication({ + store, + clock, + evidenceVerifier: { + async verify(request) { + const recorded = receipts.get(request.receipt); + if ( + recorded === undefined || + !isDeepStrictEqual(JSON.parse(recorded), binding(request)) + ) + return null; + return { + id: request.receipt, + verifiedBy: "synthetic/staff/verifier", + verifiedAt: clock.now(), + }; + }, + }, + retrieval: { + // One UTF-8 byte is one fixture token; this is not a model tokenizer. + tokenCounter: { + count: (text) => new TextEncoder().encode(text).byteLength, + }, + }, + }); + + function command(action: string, expectedGeneration: number) { + time += 1_000; + return { + commandId: `synthetic/${action}/${++commandOrdinal}`, + correlationId: "synthetic-composition", + expectedGeneration, + }; + } + + async function prepareDraft() { + const created = await app.createCollection(contexts.administrator, { + ...command("collection", 0), + collectionId, + name: "Fictional workshop guides", + }); + await app.putValidationPolicy(contexts.administrator, { + ...command("validation", 0), + policy, + }); + await app.putGovernanceConfiguration(contexts.administrator, { + ...command("governance", created.value.generation), + collectionId, + configuration, + }); + const preview = await app.previewCollectionPolicy(contexts.administrator, { + collectionId, + uses: { + portal: { enabled: false }, + bot: { + enabled: true, + audience: { kind: "permission", permission: audiencePermission }, + }, + }, + }); + await app.updateCollectionPolicy(contexts.administrator, { + ...command("audience", preview.generation), + collectionId, + preview: preview.preview, + }); + await app.createDraft(contexts.author, { + ...command("draft", 0), + articleId, + collectionId, + draft: guide, + }); + return app.getDraft(contexts.author, { articleId }); + } + + async function runSyntheticChecks() { + const current = await app.getDraft(contexts.author, { articleId }); + // This scripted runner recognizes only the known fictional procedure. + // It accepts no submitted result, runner, artifact, or attestation claims. + assert.deepEqual(current.revision.content, guide.content); + time += 1_000; + return policy.requirements + .filter((check) => check.kind === guide.kind) + .map((check) => { + const evidence: EvidenceSubmission = { + id: `evidence/${check.id}`, + articleId, + articleRevision: current.revision.number, + contentHash: current.revision.contentHash, + validationPolicy: current.revision.validationPolicy, + checkId: check.id, + testKind: check.testKind, + applicability: current.revision.applicability, + stagingBuildId: configuration.expectedStagingBuildId, + steps: [ + "SYNTHETIC_PRIVATE_EVIDENCE: fictional export check completed.", + ], + result: "passed", + executedAt: clock.now(), + runnerId: contexts.author.principalId, + artifacts: [ + { id: `synthetic/private/${check.id}`, hash: "a".repeat(64) }, + ], + }; + const receipt = `synthetic-receipt/${++receiptOrdinal}`; + receipts.set( + receipt, + JSON.stringify( + binding({ + access: contexts.author, + article: current.revision, + submission: evidence, + configuration, + }), + ), + ); + return { receipt, evidence: structuredClone(evidence) }; + }); + } + + return { + app, + contexts, + articleId, + collectionId, + applicability: structuredClone(guide.applicability), + command, + prepareDraft, + runSyntheticChecks, + }; +} + +export async function runCompleteExampleFlow( + composition: ReturnType, +) { + const c = composition; + let current = await c.prepareDraft(); + for (const check of await c.runSyntheticChecks()) { + const submitted = await c.app.submitEvidence(c.contexts.author, { + ...c.command("evidence", current.generation), + articleId: c.articleId, + evidence: check.evidence, + receipt: check.receipt, + }); + current = await c.app.getDraft(c.contexts.author, { + articleId: c.articleId, + }); + assert.equal(current.generation, submitted.value.generation); + } + await c.app.submitForReview(c.contexts.author, { + ...c.command("review", current.generation), + articleId: c.articleId, + }); + const reviewed = await c.app.getReview(c.contexts.reviewer, { + articleId: c.articleId, + }); + await c.app.publishArticle(c.contexts.reviewer, { + ...c.command("publish", reviewed.generation), + articleId: c.articleId, + review: reviewed.review, + }); + let indexed = false; + for (let attempt = 0; attempt < 16; attempt += 1) { + const status = await c.app.repairArticleIndex(c.contexts.reviewer, { + articleId: c.articleId, + }); + assert.notEqual( + status.status, + "blocked", + `Index blocked: ${status.reason}`, + ); + if (status.status === "ready") { + assert.equal(status.indexed, true); + indexed = true; + break; + } + } + assert.equal(indexed, true, "Index did not converge within 16 bounded calls"); + const retrieved = await c.app.retrieveAnswerSources(c.contexts.customer, { + collectionIds: [c.collectionId], + query: "How can I download a CSV export?", + applicability: c.applicability, + }); + // Reconfirm the exact references immediately before consuming these sources. + // The result is a current observation, not an authorization lease. + const confirmed = await c.app.confirmAnswerSources(c.contexts.customer, { + references: retrieved.sources.map((source) => source.reference), + applicability: c.applicability, + }); + assert.equal(confirmed.outcome, "results"); + assert.equal(confirmed.sources.length, 1); + assert.deepEqual(confirmed.sources, retrieved.sources); + const source = confirmed.sources[0]!; + assert.equal(source.reference.articleId, c.articleId); + assert.equal(source.citation.portalArticle, undefined); + return { + articleId: c.articleId, + revision: source.reference.articleRevision, + citationLabel: source.citation.label, + answerSources: confirmed, + }; +} diff --git a/examples/composition/run.ts b/examples/composition/run.ts new file mode 100644 index 0000000..ba7d29e --- /dev/null +++ b/examples/composition/run.ts @@ -0,0 +1,17 @@ +import { + createExampleComposition, + runCompleteExampleFlow, +} from "./composition.ts"; + +const result = await runCompleteExampleFlow(createExampleComposition()); +process.stdout.write( + [ + "Knowledge Base synthetic composition completed.", + `articleId=${result.articleId}`, + `revision=${result.revision}`, + `citation=${result.citationLabel}`, + `confirmedSources=${result.answerSources.sources.length}`, + `syntheticSourceTokens=${result.answerSources.sourceTokens}`, + "", + ].join("\n"), +); diff --git a/package.json b/package.json index b0874eb..e0c8c90 100644 --- a/package.json +++ b/package.json @@ -19,19 +19,23 @@ "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" + "release:pack": "node scripts/release-packages.mjs pack", + "example": "pnpm run build && node --experimental-strip-types examples/composition/run.ts" }, "devDependencies": { "@azure/data-tables": "13.3.2", + "@cloudflare/workers-types": "5.20260730.1", "@pegma/authorization-core": "0.4.0", "@pegma/knowledge-base-application": "0.1.0", "@pegma/knowledge-base-contracts": "0.1.0", "@pegma/knowledge-base-core": "0.1.0", "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", + "@pegma/storage-cloudflare-d1": "0.4.1", "@pegma/storage-core": "0.4.0", "@types/node": "26.6.6", "azurite": "3.37.0", + "miniflare": "4.20260730.0", "prettier": "3.9.10", "typescript": "7.0.2", "vitest": "5.0.5" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 222b5ec..630d7f0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@azure/data-tables': specifier: 13.3.2 version: 13.3.2 + '@cloudflare/workers-types': + specifier: 5.20260730.1 + version: 5.20260730.1 '@pegma/authorization-core': specifier: 0.4.0 version: 0.4.0 @@ -29,6 +32,9 @@ importers: '@pegma/storage-azure-tables': specifier: 0.4.0 version: 0.4.0 + '@pegma/storage-cloudflare-d1': + specifier: 0.4.1 + version: 0.4.1 '@pegma/storage-core': specifier: 0.4.0 version: 0.4.0 @@ -38,6 +44,9 @@ importers: azurite: specifier: 3.37.0 version: 3.37.0(@types/node@26.6.6) + miniflare: + specifier: 4.20260730.0 + version: 4.20260730.0 prettier: specifier: 3.9.10 version: 3.9.10 @@ -187,6 +196,39 @@ packages: resolution: {integrity: sha512-FJCHWlMA//XMs5rxf1z/mN0gaWPbJhlAVw5l4IxKhEtZX2bgNERlqbdBWXNjjkok+nTh0UcKqV5G0rrCupo+4A==} engines: {node: '>=20.0.0'} + '@cloudflare/workerd-darwin-64@1.20260730.1': + resolution: {integrity: sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==} + engines: {node: '>=16'} + cpu: [x64] + os: [darwin] + + '@cloudflare/workerd-darwin-arm64@1.20260730.1': + resolution: {integrity: sha512-SBHKntPkKvNPgaCrTe99xC1CAl8ygJDzlYfK0LbuJ1muKadIw35WnhO0wu894fKBtllsVQdNzDLee+cm0ppLSQ==} + engines: {node: '>=16'} + cpu: [arm64] + os: [darwin] + + '@cloudflare/workerd-linux-64@1.20260730.1': + resolution: {integrity: sha512-ouyPOSMbiKPeSwUJUvxtMcxGAXs2J4aPE4T5ABIYX5ClcQx5j5bbHTmnqOQEY8sAuLTPjH7dY+iB6UI5ISlwwA==} + engines: {node: '>=16'} + cpu: [x64] + os: [linux] + + '@cloudflare/workerd-linux-arm64@1.20260730.1': + resolution: {integrity: sha512-YQ+Mi78U3TPdgBPtwq+Sm6rJU+Ihl2y0pjYtuuKkdmUbYzL7oLR6Xqq9wljhasnuCFICssDJaqhMep5WizYoEQ==} + engines: {node: '>=16'} + cpu: [arm64] + os: [linux] + + '@cloudflare/workerd-windows-64@1.20260730.1': + resolution: {integrity: sha512-27fAN+vUECW1oYVc1KOcHYpkL8COM2Uxtxql7TL595kxbjoqS5yckw7NLz7bTf2pALFCZWjqXDjZGJ/xbG4ZKQ==} + engines: {node: '>=16'} + cpu: [x64] + os: [win32] + + '@cloudflare/workers-types@5.20260730.1': + resolution: {integrity: sha512-3e1cBXcPTwXBk2ur0CfxZKQKL6X7vUZlOn1R7VYU0zZVJcSKFcq1AoOZM+ps0LuL0uTAxdcLg+qwXrBXVu+UuQ==} + '@colors/colors@1.6.0': resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==} engines: {node: '>=0.1.90'} @@ -195,9 +237,16 @@ packages: resolution: {integrity: sha512-dTmUJzXSuayBK+hZydEaXd2mhx61qWQwkwaBBY6LyEOVx/L9aQU5ac8eFNEsd9nrD1+zb9zvDCphLSe8g1F4Qw==} engines: {node: '>=0.1.90'} + '@cspotcode/source-map-support@0.8.1': + resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} + engines: {node: '>=12'} + '@dabh/diagnostics@2.0.9': resolution: {integrity: sha512-R6siwR65Hm+3yfgP7o8DKhNvputQAwfoz9zTc3kyDudnomj2/BcLmD+uGQQPICjuFUp8ounPBU+jmKsocwVVAg==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + '@grpc/grpc-js@1.14.7': resolution: {integrity: sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ==} engines: {node: '>=12.10.0'} @@ -207,6 +256,168 @@ packages: engines: {node: '>=6'} hasBin: true + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.2': + resolution: {integrity: sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.2': + resolution: {integrity: sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.2': + resolution: {integrity: sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.1': + resolution: {integrity: sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.1': + resolution: {integrity: sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.1': + resolution: {integrity: sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.3.1': + resolution: {integrity: sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.3.1': + resolution: {integrity: sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.1': + resolution: {integrity: sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.1': + resolution: {integrity: sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.3.1': + resolution: {integrity: sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.1': + resolution: {integrity: sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.3.1': + resolution: {integrity: sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.35.2': + resolution: {integrity: sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.35.2': + resolution: {integrity: sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.35.2': + resolution: {integrity: sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.2': + resolution: {integrity: sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.2': + resolution: {integrity: sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.35.2': + resolution: {integrity: sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.35.2': + resolution: {integrity: sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.35.2': + resolution: {integrity: sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.35.2': + resolution: {integrity: sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.2': + resolution: {integrity: sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.35.2': + resolution: {integrity: sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.2': + resolution: {integrity: sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.2': + resolution: {integrity: sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -217,6 +428,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jridgewell/trace-mapping@0.3.9': + resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + '@js-joda/core@6.3.2': resolution: {integrity: sha512-BVsYu84Gut8YTNR1v5/PnifmqXv4SVcfA/hVIM/mXADZfIocip/DfNppBtv+4am5hGH1XuH6FSoU8OHkBvZMeA==} @@ -562,10 +776,23 @@ packages: resolution: {integrity: sha512-cHVrLyQRf8qu2d83fgO7spPxKxAZlOOfvEi/t38S6l3SD2678khJvUMcvAHm/rAQ8BlReDWd6WSnIZuQiI3A1Q==} engines: {node: '>=22'} + '@pegma/storage-cloudflare-d1@0.4.1': + resolution: {integrity: sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==} + engines: {node: '>=22'} + '@pegma/storage-core@0.4.0': resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} + '@poppinss/colors@4.1.6': + resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} + + '@poppinss/dumper@0.6.5': + resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} + + '@poppinss/exception@1.2.3': + resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} + '@protobufjs/aspromise@1.1.2': resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} @@ -692,9 +919,16 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@sindresorhus/is@7.2.0': + resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} + engines: {node: '>=18'} + '@so-ric/colorspace@1.1.6': resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==} + '@speed-highlight/core@1.2.24': + resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==} + '@types/bunyan@1.8.11': resolution: {integrity: sha512-758fRH7umIMk5qt5ELmRMff4mLDlN+xyYzC+dkPTdKwbSkJFvz6xwyScrytPU0QIBbRRwbiE8/BIg8bpajerNQ==} @@ -1047,6 +1281,10 @@ packages: resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} engines: {node: '>= 0.6'} + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + debug@2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} peerDependencies: @@ -1112,6 +1350,9 @@ packages: resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==} engines: {node: '>= 0.8'} + error-stack-parser-es@1.0.5: + resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} + es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -1367,6 +1608,10 @@ packages: jws@4.0.1: resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==} + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + kuler@2.0.0: resolution: {integrity: sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==} @@ -1520,6 +1765,11 @@ packages: resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} engines: {node: '>=18'} + miniflare@4.20260730.0: + resolution: {integrity: sha512-1Z9SB9r/o//80UA02Re3QhtcecSHAyAjf5EcKBfQVlQrCg7Miy79hl2PvtkwFLIaJ5rcrOPdDcRr577okwZPsg==} + engines: {node: '>=22.0.0'} + hasBin: true + module-details-from-path@1.0.4: resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} @@ -1794,6 +2044,10 @@ packages: setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} + sharp@0.35.2: + resolution: {integrity: sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==} + engines: {node: '>=20.9.0'} + side-channel-list@1.0.1: resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} @@ -1846,6 +2100,10 @@ packages: strnum@2.5.1: resolution: {integrity: sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==} + supports-color@10.2.2: + resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} + engines: {node: '>=18'} + supports-color@5.5.0: resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} engines: {node: '>=4'} @@ -1905,6 +2163,10 @@ packages: undici-types@8.9.0: resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + undici@7.28.0: + resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} + engines: {node: '>=20.18.1'} + universalify@2.0.1: resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} engines: {node: '>= 10.0.0'} @@ -2038,6 +2300,11 @@ packages: wkx@0.5.0: resolution: {integrity: sha512-Xng/d4Ichh8uN4l0FToV/258EjMGU9MGcA0HV2d9B/ZpZB3lqQm7nkOdZdm5GhKtLLhAE7PiVQwN4eN+2YJJUg==} + workerd@1.20260730.1: + resolution: {integrity: sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA==} + engines: {node: '>=16'} + hasBin: true + wrap-ansi@7.0.0: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} @@ -2045,6 +2312,18 @@ packages: wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + ws@8.21.0: + resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + wsl-utils@1.0.1: resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} engines: {node: '>=20'} @@ -2086,6 +2365,12 @@ packages: resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} engines: {node: '>=12'} + youch-core@0.3.3: + resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} + + youch@4.1.0-beta.10: + resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} + snapshots: '@azure-rest/core-client@2.9.0': @@ -2346,16 +2631,42 @@ snapshots: transitivePeerDependencies: - supports-color + '@cloudflare/workerd-darwin-64@1.20260730.1': + optional: true + + '@cloudflare/workerd-darwin-arm64@1.20260730.1': + optional: true + + '@cloudflare/workerd-linux-64@1.20260730.1': + optional: true + + '@cloudflare/workerd-linux-arm64@1.20260730.1': + optional: true + + '@cloudflare/workerd-windows-64@1.20260730.1': + optional: true + + '@cloudflare/workers-types@5.20260730.1': {} + '@colors/colors@1.6.0': {} '@colors/colors@1.6.1': {} + '@cspotcode/source-map-support@0.8.1': + dependencies: + '@jridgewell/trace-mapping': 0.3.9 + '@dabh/diagnostics@2.0.9': dependencies: '@so-ric/colorspace': 1.1.6 enabled: 2.0.0 kuler: 2.0.0 + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.9.1 + optional: true + '@grpc/grpc-js@1.14.7': dependencies: '@grpc/proto-loader': 0.8.1 @@ -2368,6 +2679,112 @@ snapshots: protobufjs: 7.6.6 yargs: 17.7.3 + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.1 + optional: true + + '@img/sharp-darwin-x64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.1 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.2': + dependencies: + '@img/sharp-wasm32': 0.35.2 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.1': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.1': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.1': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.1': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.1': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.1': + optional: true + + '@img/sharp-linux-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.1 + optional: true + + '@img/sharp-linux-arm@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.1 + optional: true + + '@img/sharp-linux-ppc64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.1 + optional: true + + '@img/sharp-linux-riscv64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.1 + optional: true + + '@img/sharp-linux-s390x@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.1 + optional: true + + '@img/sharp-linux-x64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.1 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.2': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.1 + optional: true + + '@img/sharp-wasm32@0.35.2': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.2': + dependencies: + '@img/sharp-wasm32': 0.35.2 + optional: true + + '@img/sharp-win32-arm64@0.35.2': + optional: true + + '@img/sharp-win32-ia32@0.35.2': + optional: true + + '@img/sharp-win32-x64@0.35.2': + optional: true + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} @@ -2377,6 +2794,11 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping@0.3.9': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + '@js-joda/core@6.3.2': {} '@js-sdsl/ordered-map@4.4.2': {} @@ -2789,8 +3211,24 @@ snapshots: transitivePeerDependencies: - supports-color + '@pegma/storage-cloudflare-d1@0.4.1': + dependencies: + '@pegma/storage-core': 0.4.0 + '@pegma/storage-core@0.4.0': {} + '@poppinss/colors@4.1.6': + dependencies: + kleur: 4.1.5 + + '@poppinss/dumper@0.6.5': + dependencies: + '@poppinss/colors': 4.1.6 + '@sindresorhus/is': 7.2.0 + supports-color: 10.2.2 + + '@poppinss/exception@1.2.3': {} + '@protobufjs/aspromise@1.1.2': {} '@protobufjs/base64@1.1.2': {} @@ -2858,11 +3296,15 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@sindresorhus/is@7.2.0': {} + '@so-ric/colorspace@1.1.6': dependencies: color: 5.0.3 text-hex: 1.0.0 + '@speed-highlight/core@1.2.24': {} + '@types/bunyan@1.8.11': dependencies: '@types/node': 26.6.6 @@ -3214,6 +3656,8 @@ snapshots: cookie@0.7.2: {} + cookie@1.1.1: {} + debug@2.6.9: dependencies: ms: 2.0.0 @@ -3257,6 +3701,8 @@ snapshots: encodeurl@2.0.1: {} + error-stack-parser-es@1.0.5: {} + es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -3546,6 +3992,8 @@ snapshots: jwa: 2.0.1 safe-buffer: 5.2.1 + kleur@4.1.5: {} + kuler@2.0.0: {} leven@2.1.0: {} @@ -3654,6 +4102,18 @@ snapshots: dependencies: mime-db: 1.54.0 + miniflare@4.20260730.0: + dependencies: + '@cspotcode/source-map-support': 0.8.1 + sharp: 0.35.2 + undici: 7.28.0 + workerd: 1.20260730.1 + ws: 8.21.0 + youch: 4.1.0-beta.10 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + module-details-from-path@1.0.4: {} moment-timezone@0.5.48: @@ -3941,6 +4401,38 @@ snapshots: setprototypeof@1.2.0: {} + sharp@0.35.2: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.6 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.2 + '@img/sharp-darwin-x64': 0.35.2 + '@img/sharp-freebsd-wasm32': 0.35.2 + '@img/sharp-libvips-darwin-arm64': 1.3.1 + '@img/sharp-libvips-darwin-x64': 1.3.1 + '@img/sharp-libvips-linux-arm': 1.3.1 + '@img/sharp-libvips-linux-arm64': 1.3.1 + '@img/sharp-libvips-linux-ppc64': 1.3.1 + '@img/sharp-libvips-linux-riscv64': 1.3.1 + '@img/sharp-libvips-linux-s390x': 1.3.1 + '@img/sharp-libvips-linux-x64': 1.3.1 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 + '@img/sharp-libvips-linuxmusl-x64': 1.3.1 + '@img/sharp-linux-arm': 0.35.2 + '@img/sharp-linux-arm64': 0.35.2 + '@img/sharp-linux-ppc64': 0.35.2 + '@img/sharp-linux-riscv64': 0.35.2 + '@img/sharp-linux-s390x': 0.35.2 + '@img/sharp-linux-x64': 0.35.2 + '@img/sharp-linuxmusl-arm64': 0.35.2 + '@img/sharp-linuxmusl-x64': 0.35.2 + '@img/sharp-webcontainers-wasm32': 0.35.2 + '@img/sharp-win32-arm64': 0.35.2 + '@img/sharp-win32-ia32': 0.35.2 + '@img/sharp-win32-x64': 0.35.2 + side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 @@ -3999,6 +4491,8 @@ snapshots: dependencies: anynum: 1.0.1 + supports-color@10.2.2: {} + supports-color@5.5.0: dependencies: has-flag: 3.0.0 @@ -4073,6 +4567,8 @@ snapshots: undici-types@8.9.0: {} + undici@7.28.0: {} + universalify@2.0.1: {} unpipe@1.0.0: {} @@ -4154,6 +4650,14 @@ snapshots: dependencies: '@types/node': 26.6.6 + workerd@1.20260730.1: + optionalDependencies: + '@cloudflare/workerd-darwin-64': 1.20260730.1 + '@cloudflare/workerd-darwin-arm64': 1.20260730.1 + '@cloudflare/workerd-linux-64': 1.20260730.1 + '@cloudflare/workerd-linux-arm64': 1.20260730.1 + '@cloudflare/workerd-windows-64': 1.20260730.1 + wrap-ansi@7.0.0: dependencies: ansi-styles: 4.3.0 @@ -4162,6 +4666,8 @@ snapshots: wrappy@1.0.2: {} + ws@8.21.0: {} + wsl-utils@1.0.1: dependencies: is-wsl: 3.1.1 @@ -4198,3 +4704,16 @@ snapshots: string-width: 4.2.3 y18n: 5.0.8 yargs-parser: 21.1.1 + + youch-core@0.3.3: + dependencies: + '@poppinss/exception': 1.2.3 + error-stack-parser-es: 1.0.5 + + youch@4.1.0-beta.10: + dependencies: + '@poppinss/colors': 4.1.6 + '@poppinss/dumper': 0.6.5 + '@speed-highlight/core': 1.2.24 + cookie: 1.1.1 + youch-core: 0.3.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 87d3040..28756ce 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,3 +2,6 @@ packages: - "packages/*" linkWorkspacePackages: true + +onlyBuiltDependencies: + - workerd diff --git a/test/README.md b/test/README.md index 7cbbdcb..f962483 100644 --- a/test/README.md +++ b/test/README.md @@ -1,11 +1,13 @@ -# KB-02 application conformance fixtures +# Public KB conformance fixtures -The suites in `tests/application.test.ts` and `tests/application-storage.test.ts` -run the same public application commands against Storage Core's real memory -store and its real Azure Tables adapter connected to local Azurite. They use -the actual contracts/core, Authorization Core permission checks, declared -record codec, and application repository. No parallel KB repository or custom -authorization engine is supplied by the fixtures. +The application/storage/review and retrieval/bounds/maintenance/regression +suites under `tests/` share `application-stores.ts`. They target Storage Core's +real memory store, its released Azure Tables adapter connected to local +Azurite, and the released Cloudflare D1 adapter connected to real local +Miniflare D1. Every factory call is awaited, including calls that create +several stores in one test. They use actual contracts/core, Authorization Core +checks, declared codecs, and public application entry points. No parallel KB +repository or custom authorization engine is supplied. `application-fixtures.ts` supplies wholly fictional resolved `AccessContext` values, a controlled clock, and scripted external evidence/source verifiers. @@ -28,15 +30,50 @@ development-account connection is local-only; no cloud credentials or actual customer data are used. Temporary emulator data is removed only after checking that the resolved path belongs to the expected temporary-directory prefix. -Run the application conformance suites after building the workspace packages: +`d1.ts` creates a fresh Miniflare runtime and UUID database per factory call, +including two calls within one test. Its real `getD1Database("DB")` binding is +passed directly to `createCloudflareD1Store`, without a facade or cast. +`cf: false`, loopback/ephemeral port, and `d1Persist: false` keep this a local +fixture. It does not exercise a live Workers deployment or Cloudflare account. +Exact pins and the fixed compatibility date are in +[source preparation](../docs/SOURCE_PREPARATION.md#pinned-local-d1-consumer). + +D1 cleanup is registered with `onTestFinished` before native construction or +binding lookup. Initialization failure immediately uses the same memoized +asynchronous disposal path as normal test completion; cleanup errors remain +visible. Create D1 fixtures only inside a Vitest test. Do not share a runtime +between tests or omit awaiting a factory/disposal. The isolation suite uses +the same article IDs in independently created stores and verifies public +publication/retrieval/retirement behavior without inspecting storage. + +Vitest is bounded to four workers, 180-second tests, and 30-second hooks; D1's +disposal hook also has a 30-second limit. CI jobs on Node 22/24 each have a +30-minute timeout. The workspace allows only the pinned `workerd` install +script. These controls bound local native tooling, not production capacity. +Windows local elapsed time includes Node-to-workerd RPC and setup overhead; +it does not certify production D1 latency. A longer execution budget still +requires every assertion and cleanup step to succeed. + +`tests/composition.test.ts` runs the repository-owned fictional example over +the same three factories. The example imports no test helper. Its private +receipt registry matches exact immutable synthetic run bindings; it is not a +production credential or staging-verification implementation. See the +[example README](../examples/composition/README.md). + +Run a focused application subset after building the workspace packages: ```sh pnpm exec vitest run tests/application.test.ts tests/application-storage.test.ts ``` -These tests establish KB-02 service and storage behavior. Passing synthetic -resolved contexts does not establish a real OAuth/MCP credential flow, and -the suites do not establish KB-03 search, browser UI, model-provider settings, -live-host acceptance, production throughput, or retention operations. The full -repository type/test/release gates and later host activation evidence remain -required. +The complete repository gate also runs the retrieval, regression, composition, +and isolation suites plus `pnpm example` and artifact checks. A current-head +gate report supplies pass counts and verdicts; configured fixtures alone do +not assert a passing run. + +These suites exercise KB-02/KB-03 source and partial KB-05 consumer preparation. +Passing synthetic resolved contexts does not establish KB-04's real OAuth/MCP +credential/client flow. Local storage tests establish no browser UI, live +Workers/host acceptance, model-provider settings, production throughput, or +retention operations. All three KB packages remain unpublished; the full +KB-05 release/publication and host activation gates remain required. diff --git a/test/application-stores.ts b/test/application-stores.ts index 14ec3d2..daec73b 100644 --- a/test/application-stores.ts +++ b/test/application-stores.ts @@ -7,6 +7,7 @@ import { import { createAzureTablesStore } from "@pegma/storage-azure-tables"; import { createMemoryStore, type Store } from "@pegma/storage-core"; import { TABLE_PORT } from "./azurite.js"; +import { createD1Store } from "./d1.js"; function azureStore(): Store { const connection = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;TableEndpoint=http://127.0.0.1:${TABLE_PORT}/devstoreaccount1;`; @@ -21,6 +22,7 @@ function azureStore(): Store { export const storeFactories = [ ["memory", createMemoryStore], ["Azurite", azureStore], + ["Miniflare D1", createD1Store], ] as const; /** Bounded observation of the actual backing collection, not a parallel store. */ diff --git a/test/d1.ts b/test/d1.ts new file mode 100644 index 0000000..f179e6b --- /dev/null +++ b/test/d1.ts @@ -0,0 +1,55 @@ +import { createCloudflareD1Store } from "@pegma/storage-cloudflare-d1"; +import type { Store } from "@pegma/storage-core"; +import { Miniflare } from "miniflare"; +import { randomUUID } from "node:crypto"; +import { onTestFinished } from "vitest"; + +/** A fixed date supported by the pinned local workerd, not today's date. */ +export const D1_COMPATIBILITY_DATE = "2026-07-28"; +const cleanupTimeoutMilliseconds = 30_000; + +/** + * One real local D1 database per factory invocation, including multiple stores + * within the same test. Call only inside a Vitest test; its lifetime owns cleanup. + */ +export async function createD1Store(): Promise { + let runtime: Miniflare | undefined; + let disposal: Promise | undefined; + + const dispose = (): Promise => { + const current = runtime; + if (current === undefined) return Promise.resolve(); + disposal ??= Promise.resolve().then(() => current.dispose()); + return disposal; + }; + + // Register before constructing a runtime or awaiting its binding. Calling the + // factory outside a test fails before it can leave a native process running. + onTestFinished(dispose, cleanupTimeoutMilliseconds); + + try { + runtime = new Miniflare({ + modules: true, + script: + "export default { fetch() { return new Response(null, { status: 204 }); } };", + compatibilityDate: D1_COMPATIBILITY_DATE, + host: "127.0.0.1", + port: 0, + cf: false, + d1Persist: false, + d1Databases: { DB: randomUUID() }, + }); + const database = await runtime.getD1Database("DB"); + return createCloudflareD1Store({ database }); + } catch (error) { + try { + await dispose(); + } catch (cleanupError) { + throw new AggregateError( + [error, cleanupError], + "Local D1 initialization and cleanup failed", + ); + } + throw error; + } +} diff --git a/tests/application-review-regressions.test.ts b/tests/application-review-regressions.test.ts index c6e7adc..b52e8de 100644 --- a/tests/application-review-regressions.test.ts +++ b/tests/application-review-regressions.test.ts @@ -23,7 +23,7 @@ import { barrier, traceStore } from "../test/trace-store.js"; for (const [name, createStore] of storeFactories) { describe(`KB application review regressions (${name})`, () => { it("denies collection, validation, governance and review metadata reads without their staff permissions", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const current = (await f.submitEvidence(await f.createDraft())).current; await f.review(current); @@ -69,7 +69,7 @@ for (const [name, createStore] of storeFactories) { it.each(["article", "governance"] as const)( "maps a stored %s partition exceeding the reader capacity to generic article unavailability", async (path) => { - const store = createStore(); + const store = await createStore(); const f = applicationFixture(store); await f.setupCollection(); if (path === "governance") { @@ -125,7 +125,7 @@ for (const [name, createStore] of storeFactories) { ] as const)( "deliberately rejects a malformed policy preview: %s", async (defect) => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const proposed = await f.app.previewCollectionPolicy(admin, { collectionId: "collection/workshop", @@ -173,7 +173,7 @@ for (const [name, createStore] of storeFactories) { ); it("rejects validation policy generation changed while governance was loading", async () => { - const backing = createStore(); + const backing = await createStore(); const administrator = applicationFixture(backing); await administrator.setupCollection(); const traced = traceStore(backing); @@ -227,6 +227,6 @@ for (const [name, createStore] of storeFactories) { }); expect(await allKnowledgeRows(backing)).toEqual(committedRows); expect(traced.transactions).toHaveLength(0); - }, 30_000); + }); }); } diff --git a/tests/application-storage.test.ts b/tests/application-storage.test.ts index 7378310..6192c2e 100644 --- a/tests/application-storage.test.ts +++ b/tests/application-storage.test.ts @@ -19,7 +19,7 @@ const capacity = { name: "RepositoryCapacityError" }; for (const [name, createStore] of storeFactories) { describe(`KB application atomicity and admission (${name})`, () => { it("commits authoritative revision, audit, replay receipt and causal job together", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const current = await f.createDraft(); const rows = (await allKnowledgeRows(f.store)).filter( @@ -38,7 +38,7 @@ for (const [name, createStore] of storeFactories) { }); it("retries a refused transaction whose failedAction is absent without duplicating accepted work", async () => { - const backing = createStore(); + const backing = await createStore(); const traced = traceStore(backing); const f = applicationFixture(traced.store); await f.setupCollection(); @@ -68,7 +68,7 @@ for (const [name, createStore] of storeFactories) { }); it("replays an identical concurrent command after a timestamp-dependent immutable planning collision", async () => { - const backing = createStore(); + const backing = await createStore(); const winner = applicationFixture(backing); await winner.setupCollection(); const traced = traceStore(backing); @@ -132,12 +132,12 @@ for (const [name, createStore] of storeFactories) { }) ).revision.createdAt, ).toBe("2026-11-06T20:00:00.000Z"); - }, 30_000); + }); it.each(["create", "edit"] as const)( "replays an identical %s when the winning receipt appears after the cached head was read", async (operation) => { - const backing = createStore(); + const backing = await createStore(); const winner = applicationFixture(backing); await winner.setupCollection(); const articleId = "article/receipt-read-race"; @@ -208,11 +208,10 @@ for (const [name, createStore] of storeFactories) { ); expect(traced.transactions).toHaveLength(0); }, - 30_000, ); it("refuses repeated failed preconditions atomically, including absent failedAction", async () => { - const backing = createStore(); + const backing = await createStore(); const traced = traceStore(backing); const f = applicationFixture(traced.store); await f.setupCollection(); @@ -240,7 +239,7 @@ for (const [name, createStore] of storeFactories) { }); it("allows one concurrent edit, counts every history row, and preserves retirement reserve", async () => { - const store = createStore(); + const store = await createStore(); await applicationFixture(store).setupCollection(); const f = applicationFixture(store, { limits: { maxPhysicalRows: 14, controlReserveRows: 4 }, @@ -295,10 +294,10 @@ for (const [name, createStore] of storeFactories) { (row) => row.resourceKind === "article", ), ).toHaveLength(13); - }, 30_000); + }); it("does not lose independent evidence submissions across an application-generation conflict", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const current = await f.createDraft( "article/walkthrough", @@ -348,10 +347,10 @@ for (const [name, createStore] of storeFactories) { await f.review( await f.app.getDraft(author, { articleId: current.articleId }), ); - }, 30_000); + }); it("preserves exact retained-history limits without deleting old rows to admit an edit", async () => { - const store = createStore(); + const store = await createStore(); await applicationFixture(store).setupCollection(); const f = applicationFixture(store, { limits: { maxArticleRevisions: 2 }, @@ -382,7 +381,7 @@ for (const [name, createStore] of storeFactories) { }); it("keeps enough control capacity to revoke a live published proof", async () => { - const store = createStore(); + const store = await createStore(); await applicationFixture(store).setupCollection(); const f = applicationFixture(store, { limits: { maxPhysicalRows: 22, controlReserveRows: 4 }, @@ -427,10 +426,10 @@ for (const [name, createStore] of storeFactories) { }) ).publicationHeld, ).toBe(true); - }, 30_000); + }); it("fails current-policy serving after a collection update races a publication commit", async () => { - const backing = createStore(); + const backing = await createStore(); const traced = traceStore(backing); const f = applicationFixture(traced.store); await f.setupCollection(); @@ -483,6 +482,6 @@ for (const [name, createStore] of storeFactories) { await expect( f.app.getPublishedArticle(admin, { articleId: current.articleId }), ).rejects.toMatchObject({ name: "KnowledgeBaseNotFoundError" }); - }, 30_000); + }); }); } diff --git a/tests/application.test.ts b/tests/application.test.ts index ce6eda7..0d2ef75 100644 --- a/tests/application.test.ts +++ b/tests/application.test.ts @@ -36,7 +36,7 @@ const conflict = { name: "RepositoryConflictError" }; for (const [name, createStore] of storeFactories) { describe(`authorized KB application public entries (${name})`, () => { it("refuses collection management for a published-content reader", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await expect( f.app.createCollection(customer, { ...f.command("denied", 0), @@ -49,7 +49,7 @@ for (const [name, createStore] of storeFactories) { }); it("lets authors inspect safe active validation requirements before creating a draft", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const requirements = await f.app.getValidationRequirements(author, { collectionId: "collection/workshop", @@ -80,7 +80,7 @@ for (const [name, createStore] of storeFactories) { }); it("keeps author, reviewer, and private-read authority separate", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft(); current = (await f.submitEvidence(current)).current; @@ -119,7 +119,7 @@ for (const [name, createStore] of storeFactories) { }); it("returns an explicit approved-content DTO without evidence, actors, or provenance", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft(); current = await f.setSources(current, [source]); @@ -162,7 +162,7 @@ for (const [name, createStore] of storeFactories) { }); it("does not expose unpublished drafts, bot-only collections, or unauthorized portal audiences", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const unpublished = await f.createDraft("article/draft-only"); await expect( @@ -183,7 +183,7 @@ for (const [name, createStore] of storeFactories) { }); it("preserves old publication identity while a moved draft awaits review", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let sourced = await f.createDraft(); sourced = await f.setSources(sourced, [source]); @@ -227,8 +227,8 @@ for (const [name, createStore] of storeFactories) { }); it("isolates independently composed stores with matching resource IDs", async () => { - const a = applicationFixture(createStore()); - const b = applicationFixture(createStore()); + const a = applicationFixture(await createStore()); + const b = applicationFixture(await createStore()); await a.setupCollection(); await a.publishedArticle(); await expect( @@ -259,7 +259,7 @@ for (const [name, createStore] of storeFactories) { it.each(["false", "throw", "missing"] as const)( "hides published content when live source publication eligibility is %s after a draft move", async (mode) => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft(); current = await f.setSources(current, [source]); @@ -313,7 +313,7 @@ for (const [name, createStore] of storeFactories) { ); it("replays bounded acknowledgements without duplicate rows and rechecks current authority", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const input = { ...f.command("create-once", 0), @@ -344,7 +344,7 @@ for (const [name, createStore] of storeFactories) { }); it("fences evidence changes with application generation rather than content revision", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const old = await f.createDraft(); const changed = (await f.submitEvidence(old)).current; @@ -364,7 +364,7 @@ for (const [name, createStore] of storeFactories) { }); it("rejects forged or rebound verifier receipts without accepted state", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const current = await f.createDraft(); f.setTime(3_000); @@ -410,7 +410,7 @@ for (const [name, createStore] of storeFactories) { }); it("fails closed when evidence verification is absent or unavailable", async () => { - const store = createStore(); + const store = await createStore(); const f = applicationFixture(store, { missingEvidenceVerifier: true }); await f.setupCollection(); const current = await f.createDraft(); @@ -439,7 +439,7 @@ for (const [name, createStore] of storeFactories) { }); it("invalidates pending review after provenance or active governance changes", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft(); current = (await f.submitEvidence(current)).current; @@ -480,7 +480,7 @@ for (const [name, createStore] of storeFactories) { }); it("rechecks current collection policy and governance before published reads", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); await f.publishedArticle(); const collectionId = "collection/workshop"; @@ -502,7 +502,7 @@ for (const [name, createStore] of storeFactories) { await expect( f.app.getPublishedArticle(customer, { articleId: "article/export" }), ).rejects.toMatchObject(missing); - const other = applicationFixture(createStore()); + const other = applicationFixture(await createStore()); await other.setupCollection(); await other.publishedArticle(); const head = await other.app.getCollection(admin, { collectionId }); @@ -523,7 +523,7 @@ for (const [name, createStore] of storeFactories) { }); it("requires source-resource permission and current source proof separately", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft(); current = await f.setSources(current, [source]); @@ -578,7 +578,7 @@ for (const [name, createStore] of storeFactories) { }); it("revokes a historical evidence binding, holds publication, and replays safely", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const published = await f.publishedArticle(); const proof = ( @@ -614,7 +614,7 @@ for (const [name, createStore] of storeFactories) { }); it("retains evidence by content revision without replacing an older publication", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const published = await f.publishedArticle(); const old = await f.app.getPublishedArticle(customer, { @@ -643,7 +643,7 @@ for (const [name, createStore] of storeFactories) { }); it("requires explicit privileged approval for public collection changes", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const collectionId = "collection/workshop"; const preview = await f.app.previewCollectionPolicy(admin, { @@ -680,7 +680,7 @@ for (const [name, createStore] of storeFactories) { }); it("rejects a stale policy preview after a governance-only generation change", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const collectionId = "collection/workshop"; const preview = await f.app.previewCollectionPolicy(admin, { @@ -706,7 +706,7 @@ for (const [name, createStore] of storeFactories) { }); it("roundtrips maximum quote-heavy content and verification metadata", async () => { - const f = applicationFixture(createStore()); + const f = applicationFixture(await createStore()); await f.setupCollection(); const before = await allKnowledgeRows(f.store); await expect( @@ -746,6 +746,6 @@ for (const [name, createStore] of storeFactories) { }) ).content.text, ).toBe(body); - }, 30_000); + }); }); } diff --git a/tests/composition.test.ts b/tests/composition.test.ts new file mode 100644 index 0000000..232b767 --- /dev/null +++ b/tests/composition.test.ts @@ -0,0 +1,146 @@ +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, +} from "@pegma/knowledge-base-application"; +import { describe, expect, it } from "vitest"; +import { + createExampleComposition, + runCompleteExampleFlow, +} from "../examples/composition/composition.js"; +import { storeFactories } from "../test/application-stores.js"; + +for (const [name, createStore] of storeFactories) { + describe(`fictional public composition (${name})`, () => { + it("confirms approved bot-only sources without private evidence or portal access", async () => { + const c = createExampleComposition(await createStore()); + const result = await runCompleteExampleFlow(c); + expect(result.articleId).toBe(c.articleId); + expect(result.revision).toBe(1); + expect(result.answerSources.sources).toHaveLength(1); + expect(result.answerSources.sources[0]?.citation).toEqual({ + label: "Download a workspace export", + }); + expect(result.answerSources.serializedSources).toContain( + "3. Download the CSV spreadsheet.", + ); + for (const privateValue of [ + "SYNTHETIC_PRIVATE_EVIDENCE", + "synthetic/private/", + "synthetic-receipt/", + c.contexts.author.principalId, + "synthetic/staff/verifier", + ]) { + expect(result.answerSources.serializedSources).not.toContain( + privateValue, + ); + expect(JSON.stringify(result.answerSources.sources)).not.toContain( + privateValue, + ); + } + expect(result.answerSources.sourceTokens).toBe( + new TextEncoder().encode(result.answerSources.serializedSources) + .byteLength, + ); + await expect( + c.app.getPublishedArticle(c.contexts.customer, { + articleId: c.articleId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect( + await c.app.searchPublishedArticles(c.contexts.customer, { + collectionId: c.collectionId, + query: "export", + applicability: c.applicability, + }), + ).toEqual({ outcome: "no_result", articles: [] }); + }); + + it("rejects a tampered passed check and keeps publication with the reviewer", async () => { + const c = createExampleComposition(await createStore()); + let current = await c.prepareDraft(); + const checks = await c.runSyntheticChecks(); + const first = checks[0]!; + await expect( + c.app.submitEvidence(c.contexts.author, { + ...c.command("tampered-evidence", current.generation), + articleId: c.articleId, + receipt: first.receipt, + evidence: { + ...first.evidence, + steps: ["Caller claims the check passed without the recorded run."], + }, + }), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + expect( + (await c.app.getDraft(c.contexts.author, { articleId: c.articleId })) + .generation, + ).toBe(current.generation); + for (const check of checks) { + await c.app.submitEvidence(c.contexts.author, { + ...c.command("evidence", current.generation), + articleId: c.articleId, + evidence: check.evidence, + receipt: check.receipt, + }); + current = await c.app.getDraft(c.contexts.author, { + articleId: c.articleId, + }); + } + await c.app.submitForReview(c.contexts.author, { + ...c.command("review", current.generation), + articleId: c.articleId, + }); + const reviewed = await c.app.getReview(c.contexts.reviewer, { + articleId: c.articleId, + }); + await expect( + c.app.publishArticle(c.contexts.author, { + ...c.command("author-publish", reviewed.generation), + articleId: c.articleId, + review: reviewed.review, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + const published = await c.app.publishArticle(c.contexts.reviewer, { + ...c.command("staff-publish", reviewed.generation), + articleId: c.articleId, + review: reviewed.review, + }); + expect(published.value.state).toBe("published"); + }); + + it("refuses an earlier citation immediately after retirement before index cleanup", async () => { + const c = createExampleComposition(await createStore()); + const result = await runCompleteExampleFlow(c); + const current = await c.app.getDraft(c.contexts.reviewer, { + articleId: c.articleId, + }); + await c.app.retireArticle(c.contexts.reviewer, { + ...c.command("retire", current.generation), + articleId: c.articleId, + }); + expect( + await c.app.confirmAnswerSources(c.contexts.customer, { + references: result.answerSources.sources.map( + (source) => source.reference, + ), + applicability: c.applicability, + }), + ).toEqual({ + outcome: "no_result", + sources: [], + serializedSources: "", + sourceTokens: 0, + }); + expect( + ( + await c.app.retrieveAnswerSources(c.contexts.customer, { + collectionIds: [c.collectionId], + query: "export", + applicability: c.applicability, + }) + ).sources, + ).toEqual([]); + }); + }); +} diff --git a/tests/d1-isolation.test.ts b/tests/d1-isolation.test.ts new file mode 100644 index 0000000..befff2c --- /dev/null +++ b/tests/d1-isolation.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vitest"; +import { customer } from "../test/application-fixtures.js"; +import { createD1Store } from "../test/d1.js"; +import { + botCustomer, + indexAdministrator, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; + +describe("separate native D1 database composition", () => { + it("isolates matching collection, article, command and principal IDs through public application calls", async () => { + const first = retrievalFixture(await createD1Store()); + const second = retrievalFixture(await createD1Store()); + await first.setupCollection(); + await second.setupCollection(); + const firstGuide = { + ...retrievalGuides[0]!, + id: "article/shared-export", + draft: { + ...retrievalGuides[0]!.draft, + title: "Export from the first fictional workspace", + content: { + format: "plain_text" as const, + text: "First database: choose Export to download the workspace.", + }, + }, + }; + const secondGuide = { + ...firstGuide, + draft: { + ...firstGuide.draft, + title: "Export from the second fictional workspace", + content: { + format: "plain_text" as const, + text: "Second database: choose Export to save this independent workspace.", + }, + }, + }; + const publishedFirst = await first.publishGuide(firstGuide); + await expect( + second.app.getPublishedArticle(customer, { articleId: firstGuide.id }), + ).rejects.toMatchObject({ name: "KnowledgeBaseNotFoundError" }); + expect( + (await second.app.searchPublishedArticles(customer, second.portalInput())) + .articles, + ).toEqual([]); + expect( + (await second.app.retrieveAnswerSources(botCustomer, second.botInput())) + .sources, + ).toEqual([]); + + const publishedSecond = await second.publishGuide(secondGuide); + expect(publishedFirst.current.articleId).toBe( + publishedSecond.current.articleId, + ); + expect(publishedFirst.current.revision.number).toBe(1); + expect(publishedSecond.current.revision.number).toBe(1); + for (const [fixture, guide] of [ + [first, firstGuide], + [second, secondGuide], + ] as const) { + expect( + ( + await fixture.app.getPublishedArticle(customer, { + articleId: guide.id, + }) + ).content, + ).toEqual(guide.draft.content); + expect( + ( + await fixture.app.searchPublishedArticles( + customer, + fixture.portalInput(), + ) + ).articles[0]?.title, + ).toBe(guide.draft.title); + expect( + ( + await fixture.app.retrieveAnswerSources( + botCustomer, + fixture.botInput(), + ) + ).sources[0]?.content, + ).toEqual(guide.draft.content); + } + + await first.authoringApp.retireArticle(indexAdministrator, { + ...first.command( + "retire-one-database", + publishedFirst.current.generation, + ), + articleId: firstGuide.id, + }); + expect( + (await first.app.searchPublishedArticles(customer, first.portalInput())) + .articles, + ).toEqual([]); + expect( + (await first.app.retrieveAnswerSources(botCustomer, first.botInput())) + .sources, + ).toEqual([]); + expect( + ( + await second.app.getDraft(indexAdministrator, { + articleId: secondGuide.id, + }) + ).generation, + ).toBe(publishedSecond.current.generation); + expect( + (await second.app.retrieveAnswerSources(botCustomer, second.botInput())) + .sources[0]?.content, + ).toEqual(secondGuide.draft.content); + }); +}); diff --git a/tests/retrieval-bounds.test.ts b/tests/retrieval-bounds.test.ts index 6331772..9867cab 100644 --- a/tests/retrieval-bounds.test.ts +++ b/tests/retrieval-bounds.test.ts @@ -19,7 +19,7 @@ import { for (const [name, createStore] of storeFactories) { describe(`retrieval physical and source bounds (${name})`, () => { it("rejects oversized query, term, scope and result requests before reading storage", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); const invalid = [ { ...f.botInput(), query: "a".repeat(257) }, { @@ -38,7 +38,7 @@ for (const [name, createStore] of storeFactories) { }); it("uses keyed reads only and respects total physical gets even when missing rows consume the budget", async () => { - const f = retrievalFixture(createStore(), { + const f = retrievalFixture(await createStore(), { limits: { maxRequestPhysicalGets: 5 }, }); await f.corpus(); @@ -52,10 +52,10 @@ for (const [name, createStore] of storeFactories) { expect(f.traced.reads.length).toBeLessThanOrEqual(5); expect(f.traced.enumerations).toEqual([]); expect(f.traced.transactions).toEqual([]); - }, 30_000); + }); it("keeps ordinary retrieval within all declared physical ceilings without scans or mutations", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.corpus(); f.clearObservations(); const answer = await f.app.retrieveAnswerSources( @@ -73,12 +73,12 @@ for (const [name, createStore] of storeFactories) { ).toBeLessThanOrEqual(defaultKnowledgeRetrievalLimits.maxIndexKeyReads); expect(f.traced.enumerations).toEqual([]); expect(f.traced.transactions).toEqual([]); - }, 30_000); + }); it.each([{ maxContentBytes: 1 }, { maxSourceTokens: 1 }])( "returns no partial procedure when the whole-source allowance is %j", async (limits) => { - const f = retrievalFixture(createStore(), { limits }); + const f = retrievalFixture(await createStore(), { limits }); await f.setupCollection(); await f.publishGuide(); const answer = await f.app.retrieveAnswerSources( @@ -88,12 +88,13 @@ for (const [name, createStore] of storeFactories) { expect(answer.sources).toEqual([]); expect(answer.outcome).toBe("no_result"); }, - 30_000, ); it("counts complete serialized sources including citations and reference metadata", async () => { const count = vi.fn(countSyntheticTokens); - const f = retrievalFixture(createStore(), { tokenCounter: { count } }); + const f = retrievalFixture(await createStore(), { + tokenCounter: { count }, + }); await f.setupCollection(); await f.publishGuide(); const answer = await f.app.retrieveAnswerSources( @@ -111,12 +112,12 @@ for (const [name, createStore] of storeFactories) { expect(answer.sourceTokens).toBeLessThanOrEqual( defaultKnowledgeRetrievalLimits.maxSourceTokens, ); - }, 30_000); + }); it.each(["maxContentBytes", "maxSourceTokens"] as const)( "fits whole ranked sources within %s while exact confirmation remains all-or-nothing", async (budget) => { - const backing = createStore(); + const backing = await createStore(); const normal = retrievalFixture(backing); await normal.setupCollection(); for (const id of ["article/export-a", "article/export-b"]) @@ -167,11 +168,10 @@ for (const [name, createStore] of storeFactories) { ).sources, ).toEqual(fitted.sources); }, - 30_000, ); it("fails closed when the local token counter is missing or returns an invalid count", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing); await f.setupCollection(); await f.publishGuide(); @@ -191,10 +191,10 @@ for (const [name, createStore] of storeFactories) { (await app.retrieveAnswerSources(botCustomer, f.botInput())).sources, ).toEqual([]); } - }, 30_000); + }); it("bounds confirmation count and returned results independently of available candidates", async () => { - const f = retrievalFixture(createStore(), { + const f = retrievalFixture(await createStore(), { limits: { maxHeadProbes: 1, maxConfirmations: 1, maxResults: 1 }, }); await f.corpus(); @@ -203,7 +203,7 @@ for (const [name, createStore] of storeFactories) { f.botInput("workspace"), ); expect(answer.sources.length).toBeLessThanOrEqual(1); - }, 30_000); + }); it.each([ "duplicate entries", @@ -213,7 +213,7 @@ for (const [name, createStore] of storeFactories) { ] as const)( "counts %s before filtering an optional candidate adapter response", async (fault) => { - const backing = createStore(); + const backing = await createStore(); const seed = retrievalFixture(backing); await seed.setupCollection(); await seed.publishGuide(); @@ -255,7 +255,6 @@ for (const [name, createStore] of storeFactories) { expect(search).toHaveBeenCalledTimes(1); expect(f.traced.enumerations).toEqual([]); }, - 30_000, ); it("stops empty continuation pages and accounts for physical pages with no candidates", async () => { @@ -269,7 +268,7 @@ for (const [name, createStore] of storeFactories) { pagesRead: 1, }, })); - const f = retrievalFixture(createStore(), { + const f = retrievalFixture(await createStore(), { candidateAdapter: { search }, limits: { maxPostingPagesPerTerm: 2 }, }); @@ -299,7 +298,7 @@ for (const [name, createStore] of storeFactories) { pagesRead: 1, }, })); - const f = retrievalFixture(createStore(), { + const f = retrievalFixture(await createStore(), { candidateAdapter: { search }, limits: { maxIndexKeyReads: 1 }, }); @@ -323,10 +322,10 @@ for (const [name, createStore] of storeFactories) { expect(search).toHaveBeenCalledTimes(1); expect(search.mock.calls[0]?.[0].budget.keyedReads).toBe(1); }, - 30_000, ); - it("rejects limit configurations above hard ceilings or outside integral positive bounds", () => { + it("rejects limit configurations above hard ceilings or outside integral positive bounds", async () => { + const store = await createStore(); for (const limits of [ { maxQueryCharacters: 257 }, { maxRequestPhysicalGets: 769 }, @@ -334,9 +333,7 @@ for (const [name, createStore] of storeFactories) { { maxHeadProbes: 1.5 }, { maxResults: -1 }, ]) - expect(() => retrievalFixture(createStore(), { limits })).toThrow( - TypeError, - ); + expect(() => retrievalFixture(store, { limits })).toThrow(TypeError); }); }); } diff --git a/tests/retrieval-maintenance.test.ts b/tests/retrieval-maintenance.test.ts index a401d6b..f7e24a8 100644 --- a/tests/retrieval-maintenance.test.ts +++ b/tests/retrieval-maintenance.test.ts @@ -18,7 +18,7 @@ import { barrier } from "../test/trace-store.js"; for (const [name, createStore] of storeFactories) { describe(`bounded retrieval maintenance (${name})`, () => { it("requires staff index authority for repair, status and physical scan operations", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); for (const operation of [ () => f.app.repairArticleIndex(customer, { articleId: "article/export" }), @@ -37,7 +37,7 @@ for (const [name, createStore] of storeFactories) { }); it("repairs missed work through bounded physical scan pages and opaque continuation", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing); await f.setupCollection(); await f.publishedArticle( @@ -106,10 +106,10 @@ for (const [name, createStore] of storeFactories) { (await f.app.searchPublishedArticles(customer, f.portalInput())) .articles[0]?.articleId, ).toBe("article/export"); - }, 30_000); + }); it("makes repeated repair idempotent without adding projection history", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing); await f.setupCollection(); await f.publishGuide(); @@ -120,10 +120,10 @@ for (const [name, createStore] of storeFactories) { for (let delivery = 0; delivery < 3; delivery += 1) expect(await f.repair("article/export")).toEqual(first); expect(await allRetrievalRows(backing)).toEqual(before); - }, 30_000); + }); it("withdraws retirement immediately and converges stale projection cleanup", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); const published = await f.publishGuide(); await f.authoringApp.retireArticle(indexAdministrator, { @@ -146,10 +146,10 @@ for (const [name, createStore] of storeFactories) { (await f.app.searchPublishedArticles(customer, f.portalInput())) .articles, ).toEqual([]); - }, 30_000); + }); it("moves a newly approved revision while cleaning its old collection scope", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); await f.setupCollection("collection/new-workshop"); const old = await f.publishGuide(); @@ -178,10 +178,10 @@ for (const [name, createStore] of storeFactories) { collectionId: "collection/new-workshop", revision: 2, }); - }, 30_000); + }); it("keeps capacity failure visible while authoritative content remains intact", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing, { limits: { maxIndexPartitionRows: 2 }, }); @@ -216,10 +216,10 @@ for (const [name, createStore] of storeFactories) { }) ).title, ).toBe(retrievalGuides[0]!.draft.title); - }, 30_000); + }); it("replaces a withdrawn policy epoch only after approving a revision under the new audience", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); const old = await f.publishGuide(); const before = await f.app.getCollection(admin, { @@ -289,10 +289,10 @@ for (const [name, createStore] of storeFactories) { }) ).collection.policy.version, ).toBeGreaterThan(before.collection.policy.version); - }, 30_000); + }); it("removes one article's shared-term postings without removing another approved guide", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); const first = await f.publishGuide({ ...retrievalGuides[0]!, @@ -312,10 +312,10 @@ for (const [name, createStore] of storeFactories) { await f.app.searchPublishedArticles(customer, f.portalInput()) ).articles.map((entry) => entry.articleId), ).toEqual(["article/export-b"]); - }, 30_000); + }); it("persists resumable pending work when one maintenance batch is allowed", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing, { limits: { maxMaintenanceBatches: 1 }, }); @@ -374,12 +374,12 @@ for (const [name, createStore] of storeFactories) { ) ).articles[0]?.articleId, ).toBe("article/export"); - }, 30_000); + }); it.each(["article", "collection"] as const)( "reports blocked capacity when an existing authoritative %s partition exceeds a recomposed instance limit", async (resource) => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing); await f.setupCollection(); if (resource === "collection") { @@ -457,11 +457,10 @@ for (const [name, createStore] of storeFactories) { }); expect(await allKnowledgeRows(backing)).toEqual(before); }, - 30_000, ); it("cannot let a delayed old repair restore retired knowledge", async () => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing); await f.setupCollection(); const published = await f.publishedArticle( @@ -519,10 +518,10 @@ for (const [name, createStore] of storeFactories) { (await f.app.searchPublishedArticles(customer, f.portalInput())) .articles, ).toEqual([]); - }, 30_000); + }); it("rejects physical repair page limits beyond the configured or hard scan bound", async () => { - const f = retrievalFixture(createStore(), { + const f = retrievalFixture(await createStore(), { limits: { maxRepairScanRows: 3 }, }); for (const limit of [0, 4, 1_001, 1.5]) diff --git a/tests/retrieval-review-regressions.test.ts b/tests/retrieval-review-regressions.test.ts index 4dd7004..96a1fb9 100644 --- a/tests/retrieval-review-regressions.test.ts +++ b/tests/retrieval-review-regressions.test.ts @@ -32,7 +32,7 @@ for (const [name, createStore] of storeFactories) { it.each([1, 2])( "preserves adapter relevance order with %i authoritative confirmations and tied local scores", async (confirmations) => { - const backing = createStore(); + const backing = await createStore(); const seed = retrievalFixture(backing); await seed.setupCollection(); for (const id of ["article/a-export", "article/z-export"]) @@ -57,11 +57,10 @@ for (const [name, createStore] of storeFactories) { result.sources.map((source) => source.reference.articleId), ).toEqual(rankedIds.slice(0, confirmations)); }, - 30_000, ); it("uses an adapter's approved body match without requiring title, summary or tag overlap", async () => { - const backing = createStore(); + const backing = await createStore(); const seed = retrievalFixture(backing); await seed.setupCollection(); const guide = { @@ -99,10 +98,10 @@ for (const [name, createStore] of storeFactories) { ); expect(result.sources).toHaveLength(1); expect(result.sources[0]?.content).toEqual(guide.draft.content); - }, 30_000); + }); it("does not let a healthy same-plan losing CAS worker block the winner's progress", async () => { - const backing = createStore(); + const backing = await createStore(); const loser = retrievalFixture(backing, { limits: { maxMaintenanceBatches: 1 }, }); @@ -146,7 +145,7 @@ for (const [name, createStore] of storeFactories) { expect( await retrievalFixture(backing).repair("article/export"), ).toMatchObject({ status: "ready", indexed: true }); - }, 30_000); + }); it.each([ ["retained targets", { maxIndexPartitionRows: 2 }], @@ -154,7 +153,7 @@ for (const [name, createStore] of storeFactories) { ] as const)( "reassesses a blocked %s after policy withdrawal without changing the article head", async (_label, limits) => { - const backing = createStore(); + const backing = await createStore(); const f = retrievalFixture(backing, { limits }); await f.setupCollection(); const published = await f.publishedArticle( @@ -199,11 +198,10 @@ for (const [name, createStore] of storeFactories) { indexed: false, }); }, - 30_000, ); it("supports explicitly approved anonymous portal and bot policy then rejects revoked stale hints", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); const preview = await f.authoringApp.previewCollectionPolicy(admin, { collectionId: "collection/workshop", @@ -265,6 +263,6 @@ for (const [name, createStore] of storeFactories) { }) ).sources, ).toEqual([]); - }, 30_000); + }); }); } diff --git a/tests/retrieval.test.ts b/tests/retrieval.test.ts index 29cc1db..7a9348f 100644 --- a/tests/retrieval.test.ts +++ b/tests/retrieval.test.ts @@ -19,7 +19,7 @@ import { for (const [name, createStore] of storeFactories) { describe(`approved lexical retrieval (${name})`, () => { it("finds representative title/tag paraphrases and returns a safe known no-result", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.corpus(); for (const guide of retrievalGuides) { for (const query of guide.questions) { @@ -37,10 +37,10 @@ for (const [name, createStore] of storeFactories) { f.portalInput(unsupportedRetrievalQuestion), ), ).toEqual({ outcome: "no_result", articles: [] }); - }, 30_000); + }); it("uses bot-only knowledge without portal browsing or a browse citation", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection("collection/bot-only", false); await f.publishGuide(retrievalGuides[0], "collection/bot-only"); expect( @@ -63,10 +63,10 @@ for (const [name, createStore] of storeFactories) { retrievalGuides[0]!.draft.title, ); expect(answer.sources[0]?.citation).not.toHaveProperty("portalArticle"); - }, 30_000); + }); it("excludes draft-only content and preserves the old publication after a draft move", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); await f.createDraft("article/draft-only", "collection/workshop", { ...draft(), @@ -106,10 +106,10 @@ for (const [name, createStore] of storeFactories) { title: retrievalGuides[0]!.draft.title, }); expect(JSON.stringify(result)).not.toContain("UNAPPROVED"); - }, 30_000); + }); it("requires the exact product, version, build and locale tuple", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); await f.publishGuide(); for (const field of [ @@ -136,10 +136,10 @@ for (const [name, createStore] of storeFactories) { ).sources, ).toEqual([]); } - }, 30_000); + }); it("does not widen a missing customer audience with broad service permissions", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); await f.publishGuide(); const wrongAudience = access( @@ -157,12 +157,12 @@ for (const [name, createStore] of storeFactories) { (await f.app.retrieveAnswerSources(wrongAudience, f.botInput())) .sources, ).toEqual([]); - }, 30_000); + }); it.each(["policy", "source", "evidence"] as const)( "lets current %s withdrawal defeat stale hints and previously returned source references", async (withdrawal) => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); let current = await f.createDraft( "article/export", @@ -228,11 +228,10 @@ for (const [name, createStore] of storeFactories) { ).sources, ).toEqual([]); }, - 30_000, ); it("returns safe exact citations and reconfirms them instead of trusting an earlier answer payload", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); const published = await f.publishGuide(); const answer = await f.app.retrieveAnswerSources( @@ -278,11 +277,11 @@ for (const [name, createStore] of storeFactories) { }) ).sources, ).toEqual([]); - }, 30_000); + }); it("keeps independently composed stores isolated even for matching article and collection IDs", async () => { - const first = retrievalFixture(createStore()); - const second = retrievalFixture(createStore()); + const first = retrievalFixture(await createStore()); + const second = retrievalFixture(await createStore()); await first.setupCollection(); await second.setupCollection(); await first.publishGuide(); @@ -298,10 +297,10 @@ for (const [name, createStore] of storeFactories) { (await second.app.retrieveAnswerSources(botCustomer, second.botInput())) .sources, ).toEqual([]); - }, 30_000); + }); it("uses deterministic article ordering for equal approved title/tag scores", async () => { - const f = retrievalFixture(createStore()); + const f = retrievalFixture(await createStore()); await f.setupCollection(); for (const id of ["article/z-export", "article/a-export"]) await f.publishGuide({ ...retrievalGuides[0]!, id }); @@ -318,6 +317,6 @@ for (const [name, createStore] of storeFactories) { "article/z-export", ]); expect(second).toEqual(first); - }, 30_000); + }); }); } diff --git a/tsconfig.test.json b/tsconfig.test.json index ce8a7eb..2b4f9c6 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -2,6 +2,7 @@ "extends": "./tsconfig.base.json", "compilerOptions": { "composite": false, + "allowImportingTsExtensions": true, "declaration": false, "declarationMap": false, "sourceMap": false, @@ -11,6 +12,7 @@ "packages/*/src/**/*.test.ts", "tests/**/*.test.ts", "test/**/*.ts", + "examples/**/*.ts", "vitest.config.ts" ] } diff --git a/vitest.config.ts b/vitest.config.ts index 14ff423..5d925cf 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -5,5 +5,8 @@ export default defineConfig({ include: ["packages/**/*.test.ts", "tests/**/*.test.ts"], exclude: ["**/dist/**", "**/node_modules/**"], globalSetup: ["./test/azurite.ts"], + maxWorkers: 4, + testTimeout: 180_000, + hookTimeout: 30_000, }, }); From ec15f5484fd6a6cdfca00374eca6d212d0232d6d Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 7 Nov 2026 02:12:59 -0500 Subject: [PATCH 2/2] fix: declare example toolchain floor and assert public source shapes --- .github/PULL_REQUEST_TEMPLATE.md | 1 + AGENTS.md | 3 +++ README.md | 2 +- docs/RELEASING.md | 4 ++- docs/SOURCE_PREPARATION.md | 7 +++++- examples/composition/README.md | 6 ++++- package.json | 2 +- test/README.md | 1 + tests/composition.test.ts | 43 ++++++++++++++++++++++++++++---- 9 files changed, 59 insertions(+), 10 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 83fb659..18525d2 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,6 +12,7 @@ impacts. Explain any new host prerequisites or artifact/release consequences. - [ ] `pnpm run format:check` - [ ] `pnpm run check` - [ ] `pnpm test` +- [ ] `pnpm example` - [ ] `pnpm run release:check` - [ ] Current-head Node 22/24, review, and security gates - [ ] No private host internals or real customer data diff --git a/AGENTS.md b/AGENTS.md index 723344c..081804c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,6 +63,9 @@ Work on a `claude/*` branch and open a PR. Required checks are `pnpm run format:check`, `pnpm run check`, `pnpm test`, `pnpm example`, 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. +Repository development and the TypeScript example require Node 22.6.0+ or 24. +The root engine floor covers the example's `--experimental-strip-types` flag; +published package engines remain `>=22`, and CI tracks current Node 22/24. 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. diff --git a/README.md b/README.md index c63777b..7a0868e 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ demonstrates the public author/test/review/publish/retrieve flow with fictional trust inputs. Local emulators and that example establish neither live Workers deployment nor scoped API/MCP credentials, publication, or host acceptance. -Develop on Node 22 or 24 with pnpm 10.34.5: +Develop on Node 22.6.0+ or 24 with pnpm 10.34.5: ```sh pnpm install --frozen-lockfile diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 336fe60..e347790 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -20,7 +20,9 @@ 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: +Use Node 22.6.0+ or 24 for the repository gate and source example, with the +pinned pnpm version. CI continues to track current Node 22 and 24; published +package engines remain `>=22`. ```sh pnpm install --frozen-lockfile diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index cada517..e8dac88 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -32,7 +32,12 @@ repository pins, not a claim about the latest available versions: | Miniflare declaration dependency | `@cloudflare/workers-types@5.20260730.1` | | Locked native runtime | `workerd@1.20260730.1` (transitive) | | Local compatibility date | `2026-07-28` | -| Repository toolchain | Node 22/24, `pnpm@10.34.5` | +| Repository toolchain | Node 22.6.0+ or 24, `pnpm@10.34.5` | + +The source example uses `node --experimental-strip-types`, introduced in +[Node 22.6.0](https://nodejs.org/en/blog/release/v22.6.0). The root development +engine floor is therefore `>=22.6.0`. Published package engines remain `>=22`; +the CI matrix continues to track current Node 22 and 24. [test/d1.ts](../test/d1.ts) obtains Miniflare's real `getD1Database("DB")` binding and passes it directly to the released `createCloudflareD1Store`. diff --git a/examples/composition/README.md b/examples/composition/README.md index 91f82c7..f7356d1 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -5,9 +5,13 @@ real memory Store. It demonstrates authoring, bound synthetic verification evidence, separate staff review/publication, bounded index repair, and bot-source retrieval followed immediately by citation confirmation. -Run from the repository root on Node 22 or 24 after installing the repository's +Run from the repository root on Node 22.6.0+ or 24 after installing the repository's pinned dependencies: +The runner uses `--experimental-strip-types`, introduced in +[Node 22.6.0](https://nodejs.org/en/blog/release/v22.6.0). This is a repository +development requirement; published package engines remain `>=22`. + ```sh pnpm run example ``` diff --git a/package.json b/package.json index e0c8c90..7d529b0 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "license": "MIT", "type": "module", "engines": { - "node": ">=22" + "node": ">=22.6.0" }, "workspaces": [ "packages/*" diff --git a/test/README.md b/test/README.md index f962483..207776e 100644 --- a/test/README.md +++ b/test/README.md @@ -60,6 +60,7 @@ receipt registry matches exact immutable synthetic run bindings; it is not a production credential or staging-verification implementation. See the [example README](../examples/composition/README.md). +Use Node 22.6.0+ or 24 for repository development and the TypeScript example. Run a focused application subset after building the workspace packages: ```sh diff --git a/tests/composition.test.ts b/tests/composition.test.ts index 232b767..e6130fc 100644 --- a/tests/composition.test.ts +++ b/tests/composition.test.ts @@ -17,12 +17,45 @@ for (const [name, createStore] of storeFactories) { const result = await runCompleteExampleFlow(c); expect(result.articleId).toBe(c.articleId); expect(result.revision).toBe(1); - expect(result.answerSources.sources).toHaveLength(1); - expect(result.answerSources.sources[0]?.citation).toEqual({ - label: "Download a workspace export", + const expectedSources = [ + { + reference: { + articleId: "article/fictional-export", + collectionId: "collection/fictional-workshop", + collectionPolicyVersion: 2, + articleRevision: 1, + contentHash: expect.stringMatching(/^[a-f0-9]{64}$/u), + applicationGeneration: 5, + governanceGeneration: 3, + validationGeneration: 1, + }, + citation: { label: "Download a workspace export" }, + title: "Download a workspace export", + summary: "Save a fictional workshop workspace as a CSV spreadsheet.", + content: { + format: "markdown", + text: "1. Open Workspace.\n2. Choose Export.\n3. Download the CSV spreadsheet.", + }, + applicability: { + productId: "fictional-workshop", + productVersion: "1.0", + buildId: "synthetic-staging-42", + locale: "en-US", + }, + }, + ]; + // Exact public shapes reject added fields, including private metadata + // nested in an otherwise legitimate source, reference, or content object. + expect(result.answerSources).toStrictEqual({ + outcome: "results", + sources: expectedSources, + serializedSources: expect.any(String), + sourceTokens: expect.any(Number), }); - expect(result.answerSources.serializedSources).toContain( - "3. Download the CSV spreadsheet.", + // Retrieval serializes the complete source array as canonical JSON. Test + // its decoded shape independently, so encoded evidence/artifacts fail too. + expect(JSON.parse(result.answerSources.serializedSources)).toStrictEqual( + expectedSources, ); for (const privateValue of [ "SYNTHETIC_PRIVATE_EVIDENCE",