diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55e7bb8..e962d79 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,4 +34,19 @@ jobs: cache-dependency-path: pnpm-lock.yaml - run: pnpm install --frozen-lockfile - run: git diff --exit-code -- pnpm-lock.yaml + - name: Locate Chromium + if: matrix.os == 'ubuntu-latest' + shell: bash + run: | + browser="$(command -v google-chrome || command -v chromium || command -v chromium-browser)" + test -n "$browser" + echo "RETENTION_BROWSER=$browser" >> "$GITHUB_ENV" - run: pnpm check + env: + RETENTION_CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: actions/upload-artifact@v4 + with: + name: retention-candidate-${{ matrix.os }}-${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }} + path: .candidate/ + include-hidden-files: true + if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 35195fa..a49ae6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,5 +62,5 @@ Use `pnpm exec vitest run ` for a focused existing test. Run `pnpm ch - Prioritize nondeterminism, incorrect time arithmetic, invalid lifecycle acceptance, deleted-history resurrection, practice-to-credit leakage, policy/prefix mismatch, resource-bound bypasses, unsafe diagnostics, dependency violations and weakened gates. Include file/line, triggering condition, impact and a testable correction. - PRs must identify the ticket where applicable, requirement coverage, changes, tests and outstanding limitations. Do not mark tickets complete without required review, merge and acceptance evidence. -- Keep the package private in its manifest until publication approval. Preserve Apache-2.0 and copyright notices. Verify ownership and contributor rights before release. RV-I04 requires the exact packed ESM/types artifact, explicit archive/export allowlists, and independent offline Node/TypeScript and browser consumers. Host integration and registry publication are separate gates. +- The maintainer has authorized publishable manifest metadata for the first candidate. Keep publication separately gated; a public manifest is not permission to publish. Preserve Apache-2.0 and copyright notices. Verify ownership and contributor rights before release. RV-I04 requires the exact packed ESM/types artifact, explicit archive/export allowlists, and independent offline Node/TypeScript and browser consumers. Host integration and registry publication are separate gates. - No merge, tag, publication, deployment, maintainer signing, relicensing or repository ownership/visibility change without explicit maintainer authorization. diff --git a/CHANGELOG.md b/CHANGELOG.md index 587b556..b28255a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,3 +15,4 @@ Notable changes to Retention are recorded here. The format follows [Keep a Chang - Optional versioned eligibility-policy validation and internal eligible-only qualification with reset or ignore classification. - Public full-history review rebuild and complete-prefix advance, practice scheduling, eligible-only candidate readiness and structured explanations. - Public due ranking with bounded weighted features, validated concept relations and deterministic limits. +- Public npm package metadata, an executable quick start, integration guides and exact packed-artifact verification with independent Node/TypeScript and Chromium consumers. diff --git a/README.md b/README.md index d46c5d0..9fc7317 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,75 @@ # Retention +[![CI](https://github.com/0xbuffdev/retention/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/0xbuffdev/retention/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/0xbuffdev/retention/blob/main/LICENSE) + Retention is a review-scheduling engine for learning applications. It uses past learning observations and a review policy to decide what is due, when to revisit it and when to recommend further practice. Use it in a flashcard app, to revisit mathematical concepts or to reinforce programming skills. Retention works without a server, database, model provider or account. Applications retain ownership of their learning records and assessment decisions. -> Status: in development. The design below describes the planned first release, `@0xbuff/retention@0.0.1`. Installation and usage instructions will accompany the implemented package. +Retention has no runtime dependencies. The first release candidate is `@0xbuff/retention@0.0.1`. Registry publication is subject to maintainer approval. + +## Installation + +Use Node.js 24 or later and ESM. After publication, install from npm: + +```sh +npm install @0xbuff/retention@0.0.1 +``` + +Before publication, install the verified candidate tarball with `npm install /path/to/0xbuff-retention-0.0.1.tgz`. + +## Quick start + +Schedule a flashcard from a successful practice observation. Supply your own policy and clock; the example uses a fixed clock one day after the observation. + +```ts +import { + rebuildReview, + scheduleDue, + type Policy, + type PracticeObservation, +} from "@0xbuff/retention"; + +const day = 86_400_000; +const policy: Policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "flashcards", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; + +const event: PracticeObservation = { + schemaVersion: 1, + scopeId: "deck", + eventId: "review-1", + sequence: 0, + atMs: 0, + kind: "practice_observation", + conceptId: "binary-search", + sessionId: "session-1", + outcome: "pass", +}; + +const review = rebuildReview(policy, "deck", [event], day); +if (!review.ok) { + throw new Error("Review failed"); +} +const due = scheduleDue(policy, "deck", review.value, day); +if (!due.ok || due.value[0]?.dueAtMs !== day) { + throw new Error("Expected a due review"); +} +console.log(due.value); +``` + +The recommendation is due exactly one day after the observation. The application can present the queue without granting credit or changing the learner's official records. ## How it works @@ -78,25 +143,29 @@ An eligibility policy might require three fresh successes in at least two sessio Retention cannot establish whether evidence is authentic. The application admits evidence and makes any official assessment or credit decision independently. -## API status +## API | Operation | Purpose | | ------------------- | ------------------------------------------------------------------------- | -| `validatePolicy` | Implemented: validate scheduling and optional eligibility policy. | -| `validateEvents` | Implemented: validate scoped events and detect identity conflicts. | +| `validatePolicy` | validate scheduling and optional eligibility policy. | +| `validateEvents` | validate scoped events and detect identity conflicts. | | `rebuildReview` | Reconstruct review projections from complete history. | | `advanceReview` | Verify the prior identity and event prefix, then rebuild with new events. | | `evaluateReadiness` | Calculate advisory readiness from reconciled eligible evidence. | | `scheduleDue` | Select and rank due concepts. | | `explainReview` | Return structured reasons for a recommendation. | -See [due ranking](docs/priority.md), [policy validation](docs/policies.md), [event validation](docs/events.md) and [replay and readiness](docs/replay.md) for implemented behavior and limitations. +See [due ranking](https://github.com/0xbuffdev/retention/blob/main/docs/priority.md), [policy validation](https://github.com/0xbuffdev/retention/blob/main/docs/policies.md), [event validation](https://github.com/0xbuffdev/retention/blob/main/docs/events.md) and [replay and readiness](https://github.com/0xbuffdev/retention/blob/main/docs/replay.md) for implemented behavior and limitations. The [review scheduling specification](https://github.com/0xbuffdev/context/blob/main/repos/retention/specs/0001-review-scheduling.md) defines the event schemas, policy fields, transition rules, resource limits and error behavior. +## Documentation + +See the [documentation homepage](https://docs.0xbuff.com/docs/retention) and the repository guides for [API usage](https://github.com/0xbuffdev/retention/blob/main/docs/api.md), [integration](https://github.com/0xbuffdev/retention/blob/main/docs/integration.md) and [release verification](https://github.com/0xbuffdev/retention/blob/main/docs/releasing.md). + ## Development -The repository has an ESM package foundation with policy and event validation, checked time arithmetic, canonical history reconciliation, practice scheduling and eligible-only readiness and due ranking. Install Node.js 24+ and pnpm 11.2.2, then run: +Install Node.js 24+ and pnpm 11.2.2, then run: ```sh corepack enable @@ -104,7 +173,7 @@ pnpm install --frozen-lockfile pnpm check ``` -The check covers architecture, TypeScript, Biome, Vitest and distribution verification. See [development](docs/development.md), [contributing](CONTRIBUTING.md) and the [security policy](SECURITY.md). +The check covers architecture, TypeScript, Biome, Vitest, distribution verification and independent offline package installation. CI also exercises the packed library in Chromium. See [development](https://github.com/0xbuffdev/retention/blob/main/docs/development.md), [contributing](https://github.com/0xbuffdev/retention/blob/main/CONTRIBUTING.md) and the [security policy](https://github.com/0xbuffdev/retention/blob/main/SECURITY.md). See the [source architecture](https://github.com/0xbuffdev/context/blob/main/repos/retention/architecture.md) for the repository layout, module dependencies, build configuration and testing conventions. The [implementation tickets](https://github.com/0xbuffdev/context/blob/main/repos/retention/tickets.md) track progress toward the first release, including independent Node.js and browser consumer checks. @@ -112,4 +181,4 @@ To contribute before the first release, review the [architecture decision](https ## License -Licensed under [Apache-2.0](LICENSE). See [source rights](docs/source-rights.md) for provenance and publication requirements. +Licensed under [Apache-2.0](LICENSE). See [source rights](https://github.com/0xbuffdev/retention/blob/main/docs/source-rights.md) for provenance and publication requirements. diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..7259fe1 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,17 @@ +# API + +Import from `@0xbuff/retention`. The root exports seven synchronous operations and their contract types; internal paths are not public. + +| Operation | Result | +| ------------------------------------------------------------------ | ---------------------------------------------------- | +| `validatePolicy(policy)` | Validated policy | +| `validateEvents(scopeId, events)` | Validated distinct events | +| `rebuildReview(policy, scopeId, events, nowMs)` | Complete review result | +| `advanceReview(policy, scopeId, identity, prior, appended, nowMs)` | Rebuilt review after prefix verification | +| `evaluateReadiness(policy, scopeId, conceptId, events, nowMs)` | Candidate projection or null | +| `scheduleDue(policy, scopeId, review, nowMs, relations?, limit?)` | Ranked due recommendations | +| `explainReview(review)` | Structured practice, candidate and lifecycle reasons | + +Inputs are inert JSON data. Every operation returns `Result`: either `{ ok: true, value }` or `{ ok: false, errors }`. Treat errors as stable codes and safe field names, not user-facing prose. No operation accepts an implicit clock, and no success authenticates evidence. + +See [policies](policies.md), [events](events.md), [replay](replay.md) and [due ranking](priority.md) for the input shapes, failure semantics and bounds. diff --git a/docs/architecture.md b/docs/architecture.md index 28f312f..e28b381 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -15,7 +15,8 @@ Retention is a standalone review-scheduling engine. The engine takes an explicit - `src/explanation/`: fixed reason codes and lifecycle explanations. - `src/readiness/`: internal eligible-only qualification and candidate streak aggregation. - `tests/unit/` and `tests/fixtures/`: policy, time, event, lifecycle, qualification, identity and export-boundary tests. -- `scripts/`: architecture and distribution checks. +- `scripts/`: architecture, distribution and independent packed-consumer checks. +- `tests/consumer/`: independent package consumer fixtures compiled against the installed archive. - Root configuration and CI: strict TypeScript, Vitest, tsdown, Biome and frozen pnpm dependencies. ## Replay and projection layers diff --git a/docs/development.md b/docs/development.md index 4cce19a..de70a1f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -18,12 +18,12 @@ pnpm check | `pnpm test:watch` | Watch tests during development. | | `pnpm build` | Build ESM and declarations and verify distribution. | | `pnpm verify:dist` | Check existing distribution and root exports. | -| `pnpm check` | Run all currently configured quality checks. | +| `pnpm check` | Run quality checks, build and packed consumer verification. | CI runs the same commands on Ubuntu and Windows. The export-boundary test checks that the entry point exposes only implemented operations. Update its expected export list as approved operations are implemented; do not remove the boundary test. The source build targets ES2022, with no Node ambient types or DOM APIs. Test and build tools may use Node APIs. The root export map must match emitted files. The build emits only ESM and declarations, without source maps. Do not edit generated distribution files. -The compatibility target is Node.js 24 or later and ES2022-capable browsers (initial verification targets: Chromium 109+, Firefox 115+, Safari 16.4+). Browser support is not verified yet. +The build targets ES2022. CI checks Node.js 24 on Ubuntu and Windows, and runs a packed consumer in the installed Chromium browser on Ubuntu. See exact run evidence for browser versions; older Chromium, Firefox and Safari versions have not been established by these checks. -Release-candidate work includes exact archive verification, independent browser and Node consumers, and security and source-rights checks. Passing foundation checks does not establish runtime support or release readiness. +Run `pnpm verify:package` after building to verify the exact tarball and independent offline Node/TypeScript consumer. Set `RETENTION_BROWSER` to a Chromium executable on Linux to exercise the browser consumer too. See [release policy](releasing.md) for evidence and approval gates. diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..9b689cc --- /dev/null +++ b/docs/integration.md @@ -0,0 +1,15 @@ +# Integration + +A local study tool can pass practice observations directly. Bind the scope, assign durable unique event IDs and sequences, and supply a clock in integer Unix milliseconds. Persist the complete history outside Retention and rebuild whenever the policy changes. Use the [README quick start](../README.md) for a practice-only example. + +For advisory candidate readiness, configure an eligibility policy and supply only independently admitted credited retrievals. A successful practice event cannot satisfy eligibility. A model report, a tag or the canonical watermark cannot establish evidence authenticity. The [packed consumer fixture](../tests/consumer/consumer.ts) includes synthetic practice and credited observations to illustrate the distinction. + +For corrections, revocations and deletion, supply the complete durable history including controls. A scheduler result must not update official grades or credentials. The host owns stale-generation checks, history completeness, tenant authorization, physical erasure and delivery. + +## Failures and privacy + +Check `result.ok` before consuming a value. On failure, retain authoritative host records unchanged; do not apply a partial projection. Do not log raw payloads or canonical history watermarks. Bound incoming serialized data before materializing it; the validator is not a JavaScript sandbox. See the [security policy](../SECURITY.md). + +## Runtime + +Use the ESM root in Node.js 24 or a browser with ES2022 support and a bundler or import map. The package has no mandatory runtime dependencies. The release evidence records actual tested browser versions. diff --git a/docs/releasing.md b/docs/releasing.md index 02abb8e..35e7e35 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,7 +1,25 @@ # Release policy -The planned first release is `@0xbuff/retention@0.0.1`. The manifest remains private and no publication workflow is configured. +The first candidate is `@0xbuff/retention@0.0.1`. The manifest targets public npm access. No automatic publication workflow is configured. -Before publication, all seven implementation tickets must be accepted. Inspect the actual ESM and declaration archive against its allowlist. Test installation in independent offline Node/TypeScript and browser consumers, verify supported runtime claims, and complete conformance, security and source-rights checks. Record the exact commit, commands, results and limitations. +## Verify the candidate -Maintainers authorize publication after verifying the exact candidate artifact, Apache-2.0 license and notices, registry identity, version and provenance. Host integration is independent. No tag, signing or publication is authorized by passing CI. +From a clean checkout with Node.js 24 and pnpm 11.2.2: + +```sh +corepack enable +pnpm install --frozen-lockfile +pnpm check +``` + +The package check packs the built files with npm, checks the exact archive allowlist and integrity, and installs the tarball offline outside the checkout. It compiles and executes a TypeScript consumer and the README quick start against the installed root export. It rejects unexpected files, runtime dependencies, install hooks and external module imports. + +On Linux with Chromium or Google Chrome installed, set `RETENTION_BROWSER` to the browser executable before running the checks. CI exercises the same installed module in Chromium over a loopback-only HTTP server, with a content security policy blocking external resources. Record the actual browser version. Browser compatibility claims are limited to tested versions. + +CI retains the tested tarball and an evidence record (source SHA, archive SHA-256 and SHA-512 integrity, runtime versions, file list and consumer checks). The artifact is the candidate; rebuilding later creates a new candidate requiring verification. + +## Release approval + +Before accepting a candidate, review all library acceptance cases, the exact source, the package artifact, security and source rights. Record verified runtime versions and limitations. Confirm ownership and contributor rights, license and notices, registry scope access and version availability. The maintainer must authorize publication separately. CI never publishes, tags or signs a release. + +Host admission, authorization, grade invariance, deletion, delivery and stale-generation tests belong to a later integration. diff --git a/docs/replay.md b/docs/replay.md index 4eb3010..5044f92 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -31,7 +31,7 @@ The example assumes the application supplies a policy, complete scoped events an Practice scheduling uses all active observations. Candidate aggregation uses only reconciled credited evidence, independent of practice. The qualifying span runs from the first to last qualifying success, never the evaluation clock. A reset clears all streak counters and timestamps. A candidate is advisory, not mastery or an official decision. -Advance requires the exact prior identity and complete prior history, including suppressed and future events. A changed policy, incompatible identity, missing history or backward clock requires explicit rebuild. The appended records may include late effective observations or identical duplicates; the combined history is validated and replayed from scratch. A supplied identity is not authenticated evidence. Both input arrays count toward the raw-entry limit, including duplicates. +Advance requires the exact prior identity and complete prior history, including suppressed and future events. A changed policy, incompatible identity, missing history or backward clock requires explicit rebuild. The appended records may include late effective observations or identical duplicates; the combined history is validated and replayed from scratch. A supplied identity is not authenticated evidence. Both raw input arrays, including duplicates, count toward the raw-entry and aggregate string limits. Advance checks those limits across the policy, scope, prior identity and raw events before replaying either history. A resource-limit failure returns RESOURCE_LIMIT_EXCEEDED, including when the prior prefix alone exceeds the limit. The validated events are reused for both reference replays without charging them twice. Explain accepts a successful rebuild or advance value and returns only fixed reason codes, bounded numeric arguments and concept identifiers. It does not interpret raw correction reason strings, revalidate evidence or rerun scheduling. It validates the closed result envelope, identity, event IDs, projection states, counts, timestamps and reason bounds. The canonical identity strings have separate derived size limits and are treated as opaque content identifiers here; only advance verifies them against replayed input. Explanation is not a projection authenticity check. diff --git a/docs/source-rights.md b/docs/source-rights.md index 1728a6c..75877bb 100644 --- a/docs/source-rights.md +++ b/docs/source-rights.md @@ -1,6 +1,6 @@ # Source rights and licensing -Retention uses Apache-2.0. See [LICENSE](../LICENSE) and [COPYRIGHT.md](../COPYRIGHT.md) for the terms and notices. The package manifest remains private until publication approval. +Retention uses Apache-2.0. See [LICENSE](../LICENSE) and [COPYRIGHT.md](../COPYRIGHT.md) for the terms and notices. The maintainer authorized public package metadata for the candidate. Publication and source-rights verification remain separate. Maintainers must verify source ownership, contributor rights and third-party notices before release. Keep provenance records for contributions. Do not import private application code, learner records or protected evidence. diff --git a/package.json b/package.json index ec18cc5..b3b90b2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "@0xbuff/retention", "version": "0.0.1", "description": "Deterministic review scheduling for learning and long-term retention", - "private": true, + "private": false, "license": "Apache-2.0", "type": "module", "packageManager": "pnpm@11.2.2", @@ -39,7 +39,8 @@ "lint": "biome lint .", "check:architecture": "node scripts/check-architecture.mjs", "verify:dist": "node scripts/verify-dist.mjs", - "check": "pnpm check:architecture && pnpm typecheck && pnpm check:style && pnpm test && pnpm build" + "check": "pnpm check:architecture && pnpm typecheck && pnpm check:style && pnpm test && pnpm build && pnpm verify:package", + "verify:package": "node scripts/verify-package.mjs" }, "devDependencies": { "@biomejs/biome": "2.6.8", @@ -48,12 +49,16 @@ "typescript": "5.9.3", "vitest": "4.1.12" }, - "homepage": "https://github.com/0xbuffdev/retention#readme", + "homepage": "https://docs.0xbuff.com/docs/retention", "keywords": [ "education", "spaced-repetition", "retrieval-practice", "review-scheduling", "learning" - ] + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } } diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs new file mode 100644 index 0000000..3c7a9a4 --- /dev/null +++ b/scripts/verify-package.mjs @@ -0,0 +1,397 @@ +import assert from "node:assert/strict"; +import { execFile, spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync } from "node:fs"; +import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import ts from "typescript"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const require = createRequire(import.meta.url); +const execute = promisify(execFile); +const nodeDir = path.dirname(process.execPath); +const npmEntry = [ + path.join(nodeDir, "node_modules/npm/bin/npm-cli.js"), + path.join(nodeDir, "../lib/node_modules/npm/bin/npm-cli.js"), + path.join(nodeDir, "../node_modules/npm/bin/npm-cli.js"), +].find((candidate) => existsSync(candidate)); +assert.ok(npmEntry, "Use Node.js with its bundled npm CLI"); + +function run(args, cwd) { + const result = spawnSync(process.execPath, args, { + cwd, + encoding: "utf8", + env: { + ...process.env, + npm_config_offline: "true", + npm_config_audit: "false", + npm_config_fund: "false", + npm_config_update_notifier: "false", + }, + timeout: 120_000, + maxBuffer: 4 * 1024 * 1024, + }); + if (result.error || result.status !== 0) { + throw new Error(result.error?.message || result.stderr || result.stdout || "Command failed"); + } + return result.stdout; +} + +const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")); +assert.equal(manifest.name, "@0xbuff/retention"); +assert.equal(manifest.private, false); +assert.equal(manifest.version, "0.0.1"); +assert.equal(manifest.license, "Apache-2.0"); +assert.equal(manifest.type, "module"); +assert.deepEqual(manifest.publishConfig, { + access: "public", + registry: "https://registry.npmjs.org/", +}); +assert.deepEqual(manifest.exports, { + ".": { types: "./dist/index.d.ts", import: "./dist/index.js" }, +}); +for (const field of [ + "dependencies", + "optionalDependencies", + "peerDependencies", + "bundledDependencies", + "bundleDependencies", +]) { + assert.equal(Object.keys(manifest[field] ?? {}).length, 0, field); +} +for (const script of [ + "preinstall", + "install", + "postinstall", + "prepare", + "prepack", + "postpack", + "prepublish", + "prepublishOnly", + "publish", + "postpublish", +]) { + assert.ok(!Object.hasOwn(manifest.scripts, script), script); +} +const allowed = [ + "CHANGELOG.md", + "COPYRIGHT.md", + "LICENSE", + "README.md", + "dist/index.d.ts", + "dist/index.js", + "package.json", +]; + +async function listFiles(directory, prefix = "") { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const relative = prefix + entry.name; + if (entry.isDirectory()) { + files.push(...(await listFiles(path.join(directory, entry.name), `${relative}/`))); + } else { + assert.ok(entry.isFile(), "Unexpected non-file package entry"); + files.push(relative); + } + } + return files; +} + +function inspectModule(file, contents) { + assert.doesNotMatch(contents, /sourceMappingURL\s*=|sourceURL\s*=|"sourcesContent"\s*:/); + const ast = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, true); + function visit(node) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + assert.ok(!node.moduleSpecifier, "Unexpected dependency in packed module"); + } + assert.ok(!ts.isImportEqualsDeclaration(node), "Import equals in packed module"); + assert.ok(!ts.isImportTypeNode(node), "External type import in packed module"); + if (ts.isCallExpression(node)) { + assert.notEqual(node.expression.kind, ts.SyntaxKind.ImportKeyword, "Dynamic import"); + if (ts.isIdentifier(node.expression)) { + assert.notEqual(node.expression.text, "require"); + } + } + ts.forEachChild(node, visit); + } + visit(ast); + assert.equal(ast.referencedFiles.length, 0); + assert.equal(ast.typeReferenceDirectives.length, 0); +} + +async function verifyBrowser(browser, consumerDir, installed) { + const files = new Map([ + [ + "/", + [ + "text/html", + ``, + ], + ], + [ + "/run.js", + [ + "text/javascript", + 'import "/consumer.js"; import "/quick-start.js"; await fetch("/passed", { method: "POST" });', + ], + ], + ["/retention.js", ["text/javascript", await readFile(path.join(installed, "dist/index.js"))]], + [ + "/consumer.js", + ["text/javascript", await readFile(path.join(consumerDir, "compiled/consumer.js"))], + ], + [ + "/quick-start.js", + ["text/javascript", await readFile(path.join(consumerDir, "compiled/quick-start.js"))], + ], + ]); + let report; + const passed = new Promise((resolve) => { + report = resolve; + }); + const requests = []; + const server = createServer((request, response) => { + requests.push(request.url); + if (request.method === "POST" && request.url === "/passed") { + response.writeHead(204).end(); + report(); + return; + } + const resource = files.get(request.url); + if (request.method !== "GET" || !resource) { + response.writeHead(404).end(); + return; + } + response.writeHead(200, { + "Content-Type": resource[0], + "Content-Security-Policy": + "default-src 'none'; script-src 'self' 'unsafe-inline'; connect-src 'self'", + "X-Content-Type-Options": "nosniff", + }); + response.end(resource[1]); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + try { + const { stdout: version } = await execute(browser, ["--version"], { timeout: 10_000 }); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + const child = spawn( + browser, + [ + "--headless=new", + "--disable-gpu", + "--disable-background-networking", + "--no-first-run", + "--no-default-browser-check", + "--no-proxy-server", + "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", + `--user-data-dir=${path.join(consumerDir, "browser-profile")}`, + `http://127.0.0.1:${address.port}/`, + ], + { stdio: ["ignore", "ignore", "pipe"] }, + ); + let diagnostics = ""; + child.stderr.on("data", (chunk) => { + diagnostics = (diagnostics + chunk.toString()).slice(-8192); + }); + let timer; + const failed = new Promise((_, reject) => { + child.once("error", reject); + child.once("exit", (code) => { + reject(new Error(`Browser exited (${code}): ${diagnostics}`)); + }); + timer = setTimeout(() => { + reject(new Error(`Browser did not report success: ${requests.join(", ")}\n${diagnostics}`)); + }, 60_000); + }); + try { + await Promise.race([passed, failed]); + } finally { + clearTimeout(timer); + if (child.exitCode === null && child.signalCode === null) { + const exited = new Promise((resolve) => child.once("exit", resolve)); + if (child.kill()) { + await exited; + } + } + } + console.log(`Packed browser consumer passed: ${version.trim()}`); + return version.trim(); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +} + +const workspace = await mkdtemp(path.join(tmpdir(), "retention-consumer-")); +try { + const archiveDir = path.join(workspace, "archive"); + const consumerDir = path.join(workspace, "consumer"); + await mkdir(archiveDir); + await mkdir(consumerDir); + const packed = JSON.parse( + run( + [ + npmEntry, + "pack", + "--offline", + "--ignore-scripts", + "--json", + "--pack-destination", + archiveDir, + ], + root, + ), + ); + assert.equal(packed.length, 1); + const item = packed[0]; + assert.equal(item.name, manifest.name); + assert.equal(item.version, manifest.version); + assert.match(item.filename, /^[A-Za-z0-9._-]+\.tgz$/); + assert.deepEqual(item.files.map((file) => file.path).sort(), allowed); + const archive = path.join(archiveDir, item.filename); + const bytes = await readFile(archive); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + assert.equal(item.integrity, integrity); + assert.equal(item.size, bytes.length); + await writeFile( + path.join(consumerDir, "package.json"), + JSON.stringify({ private: true, type: "module" }), + ); + run( + [ + npmEntry, + "install", + "--offline", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--no-package-lock", + "--no-save", + "--omit=dev", + archive, + ], + consumerDir, + ); + const modules = path.join(consumerDir, "node_modules"); + assert.deepEqual( + (await readdir(modules)).filter((name) => !name.startsWith(".")), + ["@0xbuff"], + ); + assert.deepEqual(await readdir(path.join(modules, "@0xbuff")), ["retention"]); + const installed = path.join(modules, "@0xbuff/retention"); + assert.deepEqual( + JSON.parse(await readFile(path.join(installed, "package.json"), "utf8")), + manifest, + ); + assert.deepEqual((await listFiles(installed)).sort(), allowed); + for (const file of allowed) { + if (file !== "package.json") { + assert.deepEqual( + await readFile(path.join(installed, file)), + await readFile(path.join(root, file)), + file, + ); + } + } + for (const file of ["dist/index.js", "dist/index.d.ts"]) { + inspectModule(file, await readFile(path.join(installed, file), "utf8")); + } + assert.match( + await readFile(path.join(installed, "LICENSE"), "utf8"), + /Apache License\s+Version 2\.0/, + ); + assert.match( + await readFile(path.join(installed, "COPYRIGHT.md"), "utf8"), + /Copyright 2026 0xBUFF/, + ); + const readme = await readFile(path.join(installed, "README.md"), "utf8"); + const quickStart = readme.match(/## Quick start\n[\s\S]*?```ts\n([\s\S]*?)\n```/); + assert.ok(quickStart?.[1], "README quick start missing"); + await writeFile(path.join(consumerDir, "quick-start.ts"), quickStart[1]); + await copyFile( + path.join(root, "tests/consumer/consumer.ts"), + path.join(consumerDir, "consumer.ts"), + ); + run( + [ + require.resolve("typescript/bin/tsc"), + "--strict", + "--exactOptionalPropertyTypes", + "--noUncheckedIndexedAccess", + "--noEmitOnError", + "--target", + "ES2022", + "--module", + "NodeNext", + "--moduleResolution", + "NodeNext", + "--lib", + "ES2022,DOM", + "--outDir", + "compiled", + "consumer.ts", + "quick-start.ts", + ], + consumerDir, + ); + console.log(run(["compiled/consumer.js"], consumerDir)); + console.log(run(["compiled/quick-start.js"], consumerDir)); + const browser = process.env.RETENTION_BROWSER + ? await verifyBrowser(process.env.RETENTION_BROWSER, consumerDir, installed) + : null; + console.log(`Verified archive SHA-256: ${sha256}`); + if (process.env.RETENTION_CANDIDATE_SHA) { + const git = (args) => { + const result = spawnSync("git", args, { cwd: root, encoding: "utf8", timeout: 10_000 }); + assert.equal(result.status, 0, result.stderr); + return result.stdout.trim(); + }; + const commit = git(["rev-parse", "HEAD"]); + assert.match(commit, /^[a-f0-9]{40}$/); + assert.equal(commit, process.env.RETENTION_CANDIDATE_SHA); + assert.equal(git(["status", "--porcelain", "--untracked-files=all"]), ""); + const output = path.join(root, ".candidate"); + await rm(output, { recursive: true, force: true }); + await mkdir(output); + await copyFile(archive, path.join(output, item.filename)); + await writeFile( + path.join(output, "evidence.json"), + `${JSON.stringify( + { + commit, + name: item.name, + version: item.version, + filename: item.filename, + sha256, + integrity, + bytes: bytes.length, + files: allowed, + node: process.version, + platform: process.platform, + browser, + checks: [ + "archive", + "offline-install", + "typescript", + "node", + ...(browser ? ["browser"] : []), + ], + }, + null, + 2, + )}\n`, + ); + } +} finally { + await rm(workspace, { recursive: true, force: true }); +} diff --git a/src/replay/advance.ts b/src/replay/advance.ts index 00bc3c0..55c9b8a 100644 --- a/src/replay/advance.ts +++ b/src/replay/advance.ts @@ -3,10 +3,12 @@ import type { Result } from "../contracts/results"; import { failure } from "../errors"; import { policyIdentity } from "../events/identity"; import { validateClock } from "../validation/clock"; +import { deduplicateEvents, normalizeEventEntries } from "../validation/events"; import { array, arrayLength, LIMITS } from "../validation/limits"; import { validatePolicy } from "../validation/policies"; import { validateProjectionIdentity } from "../validation/projections"; -import { rebuildReview } from "./rebuild"; +import { StringBudget } from "../validation/string-budget"; +import { rebuildValidated } from "./rebuild"; export function advanceReview( inputPolicy: unknown, @@ -56,11 +58,42 @@ export function advanceReview( return failure("INVALID_EVENT", "appendedEvents"); } - // Reconstruct the prior result rather than trusting its projection or an opaque snapshot. - const reconstructed = rebuildReview(policy.value, scopeId, prior, previousClock); + // Validate and charge the entire raw input before either replay. The prior identity + // supplies a validated scope equal to the explicit caller scope. + const scope = previous.value.scopeId; + const budget = new StringBudget(); + if ( + !budget.consumePolicy(policy.value) || + !budget.consume(scope, previous.value.algorithmVersion, previous.value.scopeId) + ) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength); + } + const normalizedPrior = normalizeEventEntries(scope, prior, budget); + if (!normalizedPrior.ok) { + return normalizedPrior.errors[0]?.code === "RESOURCE_LIMIT_EXCEEDED" + ? normalizedPrior + : failure("REBUILD_REQUIRED", "previousEvents"); + } + const normalizedAdded = normalizeEventEntries(scope, added, budget); + if (!normalizedAdded.ok) { + return normalizedAdded; + } + const distinctPrior = deduplicateEvents(normalizedPrior.value); + if (!distinctPrior.ok) { + return distinctPrior.errors[0]?.code === "RESOURCE_LIMIT_EXCEEDED" + ? distinctPrior + : failure("REBUILD_REQUIRED", "previousEvents"); + } + const distinctCombined = deduplicateEvents([...normalizedPrior.value, ...normalizedAdded.value]); + if (!distinctCombined.ok) { + return distinctCombined; + } + + // Reconstruct the complete prior result rather than trusting its projection or an opaque + // snapshot. Both histories use the same reference reconciliation and projection logic. + const reconstructed = rebuildValidated(policy.value, scope, distinctPrior.value, previousClock); if (!reconstructed.ok || reconstructed.value.identity.watermark !== previous.value.watermark) { return failure("REBUILD_REQUIRED", "previousEvents"); } - // Validate raw combined bounds, identities and lifecycle again using the reference operation. - return rebuildReview(policy.value, scopeId, [...prior, ...added], clock.value); + return rebuildValidated(policy.value, scope, distinctCombined.value, clock.value); } diff --git a/src/replay/explain.ts b/src/replay/explain.ts index 8fe2cad..15bf9e8 100644 --- a/src/replay/explain.ts +++ b/src/replay/explain.ts @@ -2,10 +2,11 @@ import type { ConceptExplanation, ReviewExplanation } from "../contracts/project import type { Result } from "../contracts/results"; import { success } from "../errors"; import { validateReviewResult } from "../validation/projections"; +import { StringBudget } from "../validation/string-budget"; /** Explain a successful replay value; this does not revalidate evidence or run scheduling. */ export function explainReview(input: unknown): Result { - const result = validateReviewResult(input); + const result = validateReviewResult(input, false, new StringBudget()); if (!result.ok) { return result; } diff --git a/src/replay/rebuild.ts b/src/replay/rebuild.ts index 6ba538e..c0f4ce7 100644 --- a/src/replay/rebuild.ts +++ b/src/replay/rebuild.ts @@ -1,4 +1,5 @@ -import type { ReconciledObservation } from "../contracts/events"; +import type { ReconciledObservation, ReviewEvent } from "../contracts/events"; +import type { Policy } from "../contracts/policies"; import type { CandidateProjection, ConceptProjection, @@ -11,9 +12,10 @@ import { lifecycleReasons } from "../explanation/reasons"; import { projectCandidate } from "../readiness/candidate"; import { isEligibleObservation } from "../readiness/qualification"; import { projectPractice } from "../scheduling/transitions"; -import { identifier } from "../validation/limits"; +import { identifier, LIMITS } from "../validation/limits"; import { validatePolicy } from "../validation/policies"; -import { reconcile } from "./reconcile"; +import { StringBudget } from "../validation/string-budget"; +import { type ReconciledHistory, reconcile, reconcileValidated } from "./reconcile"; export function rebuildReview( inputPolicy: unknown, @@ -25,12 +27,28 @@ export function rebuildReview( if (!policy.ok) { return policy; } - const history = reconcile(scopeId, events, nowMs); - if (!history.ok) { - return history; + const budget = new StringBudget(); + if (!budget.consumePolicy(policy.value)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength); } + const history = reconcile(scopeId, events, nowMs, budget); + return history.ok ? projectReview(policy.value, history.value) : history; +} + +// Internal reference rebuild after advance has validated both raw histories. +export function rebuildValidated( + policy: Policy, + scopeId: string, + events: readonly ReviewEvent[], + nowMs: number, +): Result { + const history = reconcileValidated(scopeId, events, nowMs); + return history.ok ? projectReview(policy, history.value) : history; +} + +function projectReview(policy: Policy, history: ReconciledHistory): Result { const grouped = new Map(); - for (const observation of history.value.observations) { + for (const observation of history.observations) { const group = grouped.get(observation.conceptId); if (group) { group.push(observation); @@ -39,15 +57,15 @@ export function rebuildReview( } } const concepts: ConceptProjection[] = []; - for (const conceptId of history.value.conceptIds) { + for (const conceptId of history.conceptIds) { const observations = grouped.get(conceptId) ?? []; - const practice = projectPractice(policy.value.scheduling, observations); + const practice = projectPractice(policy.scheduling, observations); if (!practice.ok) { return practice; } - if (policy.value.eligibility) { + if (policy.eligibility) { const candidate = projectCandidate( - policy.value.eligibility, + policy.eligibility, observations.filter(isEligibleObservation), ); if (!candidate.ok) { @@ -61,17 +79,17 @@ export function rebuildReview( return success( Object.freeze({ identity: Object.freeze({ - schemaVersion: policy.value.schemaVersion, - algorithmVersion: policy.value.algorithmVersion, - scopeId: history.value.scopeId, - policyIdentity: policyIdentity(policy.value), - evaluatedAtMs: history.value.evaluatedAtMs, - watermark: history.value.watermark, + schemaVersion: policy.schemaVersion, + algorithmVersion: policy.algorithmVersion, + scopeId: history.scopeId, + policyIdentity: policyIdentity(policy), + evaluatedAtMs: history.evaluatedAtMs, + watermark: history.watermark, }), concepts: Object.freeze(concepts), - appliedEventIds: history.value.appliedEventIds, - controlEventIds: history.value.controlEventIds, - lifecycleReasons: lifecycleReasons(history.value.controls), + appliedEventIds: history.appliedEventIds, + controlEventIds: history.controlEventIds, + lifecycleReasons: lifecycleReasons(history.controls), }), ); } @@ -91,7 +109,11 @@ export function evaluateReadiness( if (!identifier(conceptId)) { return failure("INVALID_EVENT", "conceptId"); } - const history = reconcile(scopeId, events, nowMs); + const budget = new StringBudget(); + if (!budget.consumePolicy(policy.value) || !budget.consume(conceptId)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength); + } + const history = reconcile(scopeId, events, nowMs, budget); if (!history.ok) { return history; } diff --git a/src/replay/reconcile.ts b/src/replay/reconcile.ts index 9157d55..5ae2357 100644 --- a/src/replay/reconcile.ts +++ b/src/replay/reconcile.ts @@ -1,12 +1,13 @@ -import type { ReconciledObservation, ReviewControl } from "../contracts/events"; +import type { ReconciledObservation, ReviewControl, ReviewEvent } from "../contracts/events"; import type { Result } from "../contracts/results"; import { failure, success } from "../errors"; import { resolveCreditChains } from "../events/corrections"; import { resolveDeletions } from "../events/deletions"; import { compareObservations, compareSequence } from "../events/ordering"; import { validateClock } from "../validation/clock"; -import { validateEvents } from "../validation/events"; +import { validateEventsWithBudget } from "../validation/events"; import { identifier } from "../validation/limits"; +import { StringBudget } from "../validation/string-budget"; import { historyWatermark } from "./watermark"; export type ReconciledHistory = { @@ -25,11 +26,12 @@ export function reconcile( scopeId: unknown, input: unknown, nowMs: unknown, + budget = new StringBudget(), ): Result { if (!identifier(scopeId)) { return failure("INVALID_EVENT", "scopeId"); } - const validated = validateEvents(scopeId, input); + const validated = validateEventsWithBudget(scopeId, input, budget); if (!validated.ok) { return validated; } @@ -37,8 +39,17 @@ export function reconcile( if (!clock.ok) { return clock; } - const evaluatedAtMs = clock.value; - const events = [...validated.value].sort(compareSequence); + return reconcileValidated(scopeId, validated.value, clock.value); +} + +// Internal: the public orchestration has already checked the clock, normalized +// and deduplicated the complete input. Never accept this path from a public caller. +export function reconcileValidated( + scopeId: string, + validated: readonly ReviewEvent[], + evaluatedAtMs: number, +): Result { + const events = [...validated].sort(compareSequence); // Validate the entire decision history even when a deletion would suppress its output. const credit = resolveCreditChains(events, evaluatedAtMs); diff --git a/src/validation/events.ts b/src/validation/events.ts index 4473fb1..bfaa5b1 100644 --- a/src/validation/events.ts +++ b/src/validation/events.ts @@ -4,6 +4,7 @@ import { failure, success } from "../errors"; import { eventIdentity } from "../events/identity"; import { isInstant } from "../time/elapsed"; import { array, arrayLength, identifier, integer, LIMITS, label, record } from "./limits"; +import { StringBudget } from "./string-budget"; const envelope = ["schemaVersion", "scopeId", "eventId", "sequence", "atMs", "kind"]; const concept = [...envelope, "conceptId"]; @@ -247,9 +248,20 @@ function stringLength(event: ReviewEvent): number { * occurrence; the result is not chronological and does not establish admission or lifecycle validity. */ export function validateEvents(scopeId: unknown, events: unknown): Result { + return validateEventsWithBudget(scopeId, events, new StringBudget()); +} + +export function validateEventsWithBudget( + scopeId: unknown, + events: unknown, + budget: StringBudget, +): Result { if (!identifier(scopeId)) { return invalid("scopeId"); } + if (!budget.consume(scopeId)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength); + } const length = arrayLength(events); if (length !== null && length > LIMITS.rawEvents) { return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.rawEvents); @@ -258,20 +270,35 @@ export function validateEvents(scopeId: unknown, events: unknown): Result { const validated: ReviewEvent[] = []; - let total = 0; for (const entry of entries) { const result = validateEvent(entry, scopeId); if (!result.ok) { return result; } - total += stringLength(result.value); - if (total > LIMITS.aggregateStringLength) { + if (!budget.consumeLength(stringLength(result.value))) { return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength); } validated.push(result.value); } + return success(Object.freeze(validated)); +} +// Internal: consume normalized entries only. No repeated string-budget charging. +export function deduplicateEvents( + validated: readonly ReviewEvent[], +): Result { const identities = new Map(); const sequences = new Set(); const concepts = new Set(); diff --git a/src/validation/priority.ts b/src/validation/priority.ts index 3fa6e0c..aae2f19 100644 --- a/src/validation/priority.ts +++ b/src/validation/priority.ts @@ -22,28 +22,8 @@ export function validateRankingReview( if (!isInstant(nowMs)) { return failure("INVALID_TIMESTAMP", "nowMs"); } - const { scheduling, eligibility } = policy; - if ( - !budget.consume( - scopeId, - policy.algorithmVersion, - policy.policyId, - policy.policyVersion, - scheduling.longProbeAction, - scheduling.dateArithmetic, - ) || - (scheduling.dateArithmetic === "local_calendar_days" && - !budget.consume( - scheduling.calendarProfile.zoneId, - scheduling.calendarProfile.rulesVersion, - )) || - (eligibility && - !budget.consume( - eligibility.eligibilityPolicyVersion, - eligibility.onFailure, - eligibility.onNonqualifying, - )) - ) { + const { scheduling } = policy; + if (!budget.consume(scopeId) || !budget.consumePolicy(policy)) { return failure("RESOURCE_LIMIT_EXCEEDED", "policy", LIMITS.aggregateStringLength); } const review = validateReviewResult(input, true, budget); diff --git a/src/validation/string-budget.ts b/src/validation/string-budget.ts index d7606d0..04f03c4 100644 --- a/src/validation/string-budget.ts +++ b/src/validation/string-budget.ts @@ -1,3 +1,4 @@ +import type { Policy } from "../contracts/policies"; import { LIMITS } from "./limits"; // One counter per invocation. Only validated ordinary string values reach this helper; @@ -5,13 +6,38 @@ import { LIMITS } from "./limits"; export class StringBudget { private total = 0; + consumeLength(length: number): boolean { + this.total += length; + return this.total <= LIMITS.aggregateStringLength; + } + consume(...values: readonly string[]): boolean { for (const value of values) { - this.total += value.length; - if (this.total > LIMITS.aggregateStringLength) { + if (!this.consumeLength(value.length)) { return false; } } return true; } + + consumePolicy(policy: Policy): boolean { + const { scheduling, eligibility } = policy; + return ( + this.consume( + policy.algorithmVersion, + policy.policyId, + policy.policyVersion, + scheduling.longProbeAction, + scheduling.dateArithmetic, + ) && + (scheduling.dateArithmetic !== "local_calendar_days" || + this.consume(scheduling.calendarProfile.zoneId, scheduling.calendarProfile.rulesVersion)) && + (!eligibility || + this.consume( + eligibility.eligibilityPolicyVersion, + eligibility.onFailure, + eligibility.onNonqualifying, + )) + ); + } } diff --git a/tests/consumer/consumer.ts b/tests/consumer/consumer.ts new file mode 100644 index 0000000..308246d --- /dev/null +++ b/tests/consumer/consumer.ts @@ -0,0 +1,138 @@ +import { + advanceReview, + type EligibleCreditedRetrieval, + evaluateReadiness, + explainReview, + type Policy, + type PracticeObservation, + type Result, + rebuildReview, + scheduleDue, + validateEvents, + validatePolicy, +} from "@0xbuff/retention"; + +function check(condition: unknown, message: string): asserts condition { + if (!condition) { + throw new Error(message); + } +} + +function value(result: Result): T { + check(result.ok, "Unexpected typed failure"); + return result.value; +} + +const day = 86_400_000; +const scopeId = "deck"; +const conceptId = "binary-search"; +const practicePolicy: Policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "support", + dateArithmetic: "elapsed_milliseconds", + }, +}; +const practice: PracticeObservation = { + schemaVersion: 1, + kind: "practice_observation", + scopeId, + conceptId, + eventId: "practice", + sequence: 0, + atMs: 0, + sessionId: "practice-session", + outcome: "pass", + fresh: true, + hints: 0, + ladder: 3, +}; +const normalized = value(validatePolicy(practicePolicy)); +const history = value(validateEvents(scopeId, [practice, practice])); +check(history.length === 1, "Duplicate event changed history"); +const review = value(rebuildReview(normalized, scopeId, history, day)); +check(review.concepts[0]?.dueAtMs === day, "Wrong due time"); +check(review.concepts[0]?.candidate === undefined, "Unexpected candidate"); +check(value(scheduleDue(normalized, scopeId, review, day)).length === 1, "Wrong due queue"); +check(value(explainReview(review)).concepts.length === 1, "Missing explanation"); +check( + value(evaluateReadiness(normalized, scopeId, conceptId, history, day)) === null, + "Practice-only readiness must be null", +); +const advanced = value(advanceReview(normalized, scopeId, review.identity, history, [], day)); +check(JSON.stringify(advanced) === JSON.stringify(review), "Advance diverged from rebuild"); + +// Synthetic host-admitted records: Retention itself cannot authenticate their provenance. +const eligiblePolicy: Policy = { + ...practicePolicy, + eligibility: { + eligibilityPolicyVersion: "v1", + minSuccesses: 2, + minSessions: 2, + minSpanMs: day, + requireFresh: true, + maxHints: 0, + minLadder: 3, + onFailure: "reset", + onNonqualifying: "ignore", + }, +}; +function credited(sequence: number, atMs: number): EligibleCreditedRetrieval { + return { + ...practice, + kind: "eligible_credited_retrieval", + eventId: `credit-${sequence}`, + sequence, + atMs, + sessionId: `session-${sequence}`, + fresh: true, + hints: 0, + ladder: 3, + eligibilityPolicyVersion: "v1", + creditDecisionId: `decision-${sequence}`, + decisionVersion: 1, + outcome: "pass", + }; +} +const first = credited(1, day); +const second = credited(2, 2 * day); +const initial = value(rebuildReview(eligiblePolicy, scopeId, [practice, first], 2 * day)); +check(initial.concepts[0]?.candidate?.qualifyingSuccesses === 1, "Practice counted as credit"); +const admitted = value( + advanceReview(eligiblePolicy, scopeId, initial.identity, [practice, first], [second], 2 * day), +); +check(admitted.concepts[0]?.candidate?.readiness === "candidate_ready", "Candidate not ready"); +check( + JSON.stringify( + value( + evaluateReadiness(eligiblePolicy, scopeId, conceptId, [practice, first, second], 2 * day), + ), + ) === JSON.stringify(admitted.concepts[0]?.candidate), + "Readiness query differs", +); + +// Legacy and forged tags fail closed; the host ledger is outside the package. +const ledger = Object.freeze({ officialGrade: 70 }); +const canary = "PRIVATE-LEARNER-CANARY"; +const invalid = rebuildReview( + eligiblePolicy, + scopeId, + [{ ...practice, schemaVersion: 0, answer: canary }], + 2 * day, +); +check(!invalid.ok, "Legacy event accepted"); +check(!JSON.stringify(invalid).includes(canary), "Diagnostic leaked payload"); +check( + !validateEvents(scopeId, [{ ...practice, kind: "eligible_credited_retrieval", trusted: true }]) + .ok, + "Forged tag accepted", +); +check(ledger.officialGrade === 70, "Ledger changed"); +console.log("Packed practice and admitted-evidence consumer passed."); diff --git a/tests/unit/release-bounds.test.ts b/tests/unit/release-bounds.test.ts new file mode 100644 index 0000000..a0796e9 --- /dev/null +++ b/tests/unit/release-bounds.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "vitest"; +import type { PracticeObservation, Result } from "../../src/index"; +import { advanceReview, evaluateReadiness, rebuildReview, validateEvents } from "../../src/index"; +import { elapsedPolicy } from "../fixtures/policy"; + +const scope = "s".repeat(128); +const maximum = 4_000_000; +const policy = elapsedPolicy(); +const event: PracticeObservation = { + schemaVersion: 1, + eventId: "e".repeat(64), + scopeId: scope, + sequence: 0, + atMs: 0, + kind: "practice_observation", + conceptId: "c".repeat(64), + sessionId: "s".repeat(64), + outcome: "pass", +}; + +function units(input: unknown): number { + if (typeof input === "string") { + return input.length; + } + if (input !== null && typeof input === "object") { + return Object.values(input).reduce((total: number, item) => total + units(item), 0); + } + return 0; +} + +function eventsWithUnits(target: number): PracticeObservation[] { + const shortest = { ...event, eventId: "a", conceptId: "b", sessionId: "c", sequence: 1 }; + const minimum = units(shortest); + const count = Math.floor((target - minimum) / units(event)); + let extra = target - count * units(event) - minimum; + const tail = { ...shortest }; + for (const field of ["eventId", "conceptId", "sessionId"] as const) { + const length = Math.min(extra, 127); + tail[field] = tail[field].padEnd(length + 1, "x"); + extra -= length; + } + expect(extra).toBe(0); + const events = [...Array.from({ length: count }, () => event), tail]; + expect(units(events)).toBe(target); + return events; +} + +function value(result: Result): T { + if (!result.ok) { + throw new Error("Expected success at resource boundary"); + } + return result.value; +} + +const exceeded = { + ok: false, + errors: [{ code: "RESOURCE_LIMIT_EXCEEDED", field: "events", limit: maximum }], +}; + +describe("release conformance: aggregate ordinary string limits", () => { + it("counts explicit scope and raw duplicate events before normalization", () => { + const events = eventsWithUnits(maximum - scope.length); + expect(value(validateEvents(scope, events))).toHaveLength(2); + expect(validateEvents(scope, [...events, event])).toEqual(exceeded); + expect(rebuildReview(policy, scope, events, 0)).toEqual(exceeded); + }); + + it("includes policy, readiness concept, and prior identity in the per-call budget", () => { + const events = eventsWithUnits(maximum - scope.length - units(policy)); + const review = value(rebuildReview(policy, scope, events, 0)); + expect(review.concepts).toHaveLength(2); + expect(rebuildReview(policy, scope, [...events, event], 0)).toEqual(exceeded); + expect(evaluateReadiness(policy, scope, event.conceptId, events, 0)).toEqual(exceeded); + const previous = value(rebuildReview(policy, scope, [event], 0)); + expect(advanceReview(policy, scope, previous.identity, [event], events.slice(1), 0)).toEqual( + exceeded, + ); + const within = eventsWithUnits( + maximum - + scope.length - + units(policy) - + previous.identity.algorithmVersion.length - + previous.identity.scopeId.length, + ); + const advanced = value( + advanceReview(policy, scope, previous.identity, [event], within.slice(1), 0), + ); + expect(advanced).toEqual(value(rebuildReview(policy, scope, within, 0))); + }); + + it("rejects an oversized all-prior input before reconstructing the prefix", () => { + const events = eventsWithUnits(maximum - scope.length - units(policy)); + const review = value(rebuildReview(policy, scope, events, 0)); + expect(advanceReview(policy, scope, review.identity, events, [], 0)).toEqual(exceeded); + expect(advanceReview(policy, scope, review.identity, [...events, event], [], 0)).toEqual( + exceeded, + ); + // The aggregate bound takes precedence over a mismatched prior watermark. + const wrongIdentity = { ...review.identity, watermark: "[]" }; + expect(advanceReview(policy, scope, wrongIdentity, events, [], 0)).toEqual(exceeded); + + const within = eventsWithUnits( + maximum - + scope.length - + units(policy) - + review.identity.algorithmVersion.length - + review.identity.scopeId.length, + ); + const exact = value(rebuildReview(policy, scope, within, 0)); + expect(value(advanceReview(policy, scope, exact.identity, within, [], 0))).toEqual(exact); + expect(advanceReview(policy, scope, wrongIdentity, within, [], 0)).toEqual({ + ok: false, + errors: [{ code: "REBUILD_REQUIRED", field: "previousEvents" }], + }); + }); +});