diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..cacc5b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,26 @@ +name: Bug report +description: Report a reproducible problem with Preceptor +title: "[Bug]: " +body: + - type: markdown + attributes: + value: Report security issues privately using SECURITY.md. Use synthetic data only. + - type: input + id: version + attributes: + label: Version or commit + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Minimal reproduction + description: Include Node.js version and relevant adapter configuration without secrets. + validations: + required: true + - type: textarea + id: behavior + attributes: + label: Expected and actual behavior + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..e4fe5a6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Security policy + url: https://github.com/0xbuffdev/preceptor/security/policy + about: Read the reporting instructions before disclosing a vulnerability. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..4cd0207 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,17 @@ +name: Feature request +description: Propose an improvement to the public library +title: "[Proposal]: " +body: + - type: textarea + id: problem + attributes: + label: Problem and use case + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed behavior + description: Describe the interface, alternatives and host responsibilities. + validations: + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..3c603f1 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,16 @@ +## Purpose + +Link the issue or proposal and describe the intended behavior. + +## Changes + +## Verification + +Record the tested commit, commands, results and anything not run. Include relevant negative and security tests. + +## Checklist + +- [ ] No learner records, credentials or protected assessment material +- [ ] Public contracts, examples and documentation match implemented behavior +- [ ] Existing quality and offline package checks are preserved +- [ ] No unauthorized publication, tag, deployment or merge diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 995758c..1e81e22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,13 +34,16 @@ jobs: cache-dependency-path: pnpm-lock.yaml - run: pnpm install --frozen-lockfile - run: git diff --exit-code -- pnpm-lock.yaml + - name: Test release preflight with synthetic inputs + if: matrix.os == 'ubuntu-latest' + run: pnpm check:release-preflight - run: pnpm check env: PRECEPTOR_CANDIDATE: "1" PRECEPTOR_CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} - uses: actions/upload-artifact@v4 with: - name: preceptor-candidate-${{ matrix.os }}-${{ github.event.pull_request.head.sha || github.sha }} + name: preceptor-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/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..22addbd --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,48 @@ +name: Stage npm package + +on: + workflow_dispatch: + inputs: + quality_run_id: + description: Successful main quality run ID + required: true + type: string + +permissions: {} + +concurrency: + group: preceptor-npm-stage + cancel-in-progress: false + +jobs: + stage: + if: github.repository == '0xbuffdev/preceptor' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: npm-stage + permissions: + contents: read + actions: read + id-token: write + steps: + - name: Check out exact staging commit + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: 24.22.3 + package-manager-cache: false + + - name: Verify and stage exact approved archive + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.quality_run_id }} + APPROVED_RUN_ID: ${{ vars.PRECEPTOR_STAGE_RUN_ID }} + APPROVED_SHA: ${{ vars.PRECEPTOR_STAGE_COMMIT }} + APPROVED_DIGEST: ${{ vars.PRECEPTOR_STAGE_SHA256 }} + NPM_CONFIG_REGISTRY: https://registry.npmjs.org/ + run: bash scripts/stage-release.sh diff --git a/AGENTS.md b/AGENTS.md index dcd6565..008a88c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Repository-wide instructions for working on Preceptor. Preceptor is a portable instructional engine. It selects teaching strategies and coordinates optional model assistance, scoped tools and learner memory. Its outputs are advisory; formal academic authority belongs to the host. -- Before changing behavior, read the [Preceptor specification](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/specs/0001-instruction-engine.md), [ADR](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/adr/0001-independent-instruction.md) and [implementation tickets](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/tickets.md). Check acceptance status, dependencies and required tests. +- Before changing behavior, read the [Preceptor specification](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/specs/0001-instruction-engine.md), [ADR](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/adr/0001-independent-instruction.md) and [implementation tickets](https://github.com/0xbuffdev/context/blob/main/repos/preceptor/tickets.md). These maintainer planning documents may require organization access. Check acceptance status, dependencies and required tests; external contributors should use the public guides and discuss contract changes with maintainers. - Accepted contracts govern intended behavior; source, tests and package exports establish implemented behavior. Report contradictions and missing approvals. Do not implement proposed amendments as though accepted. - Keep the library independently useful without a model, network, account, database, framework, OEE curriculum, Assay, Retention or MemoFS. Inject optional providers. Do not import private application code or introduce mandatory provider SDKs, telemetry or host services. - Keep public documentation about implemented behavior and reader tasks. Track ticket IDs and requirement coverage in the canonical tracker and PRs, not user-facing guides. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f36946..dddf23b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,16 @@ # Changelog -All notable changes to Preceptor will be documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +Notable changes to Preceptor are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ### Added -- Standalone ESM package foundation, strict TypeScript configuration, Biome, Vitest and tsdown. -- Quality-only CI and independent offline packed-package checks. -- Apache-2.0 license and copyright notices. -- Deterministic model-free instruction planning, closed capability checks and assessment-lock guidance. -- Bounded session execution, optional injected model and lesson/practice ports, sequential tool dispatch, cancellation and provenance. +- Deterministic model-free instructional policy with five modes, fixed teaching prompts and default-deny capability filtering. +- Bounded advisory sessions with optional model, lesson and practice adapters, exact lesson revision checks, sequential typed tool dispatch and attributed results. +- Resource limits for UTF-8 input, context, responses and aggregate output, tool attempts and model requests. Cancellation and a monotonic deadline stop further dispatch and discard late results. +- Scoped narrative memory contracts for recall, creation, revision-bound updates and forget proposals, with host-owned consent, replay suppression and lifecycle interfaces. +- Pure projection of authorized committed academic-result summaries, including duplicate delivery, corrections, revocation, conflict withholding and read-only session context. +- Node.js 24+ ESM and TypeScript declarations, Apache-2.0 licensing, zero runtime dependencies, integration examples and independent offline packed-consumer checks. + +The first release is planned as `0.0.1`. The release date and version heading will be recorded when the publication candidate is approved. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6771e8f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of conduct + +Discuss technical issues respectfully. Critique code and ideas, not people. Harassment, threats, abuse, disclosure of personal data and posting confidential learner or assessment material are not permitted. + +Maintainers may moderate issues, comments and reviews that violate these expectations. Use GitHub's reporting features for platform abuse and the [security policy](SECURITY.md) for vulnerability reports. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64af45b..2ed7fb0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,10 @@ # Contributing -Preceptor is under development. Read [AGENTS.md](AGENTS.md) before making changes. +Preceptor welcomes reproducible bug reports, documentation corrections and technical proposals. Open an issue before changing a public contract or the architecture. Follow the [security policy](SECURITY.md) for confidential reports. -Use Node.js 24 or later, pnpm 11.2.2 and the versions locked in the repository. From the root: +## Development + +Install Node.js 24+ and pnpm 11.2.2, then run: ```sh corepack enable @@ -10,6 +12,10 @@ pnpm install --frozen-lockfile pnpm check ``` -Use `pnpm test` for the full test suite, `pnpm format` to format files and `pnpm check:style` for non-mutating style checks. The full check also builds the package and installs its local archive in an independent offline consumer. +Use a focused branch and add positive and negative tests for changed behavior. The full check runs typechecking, Biome, Vitest, the build and offline installed-package tests. See the [development guide](docs/development.md) and [repository instructions](AGENTS.md). + +## Pull requests + +Explain the intended behavior, relevant issue, and the checks you ran. Record the tested commit and anything not run. Use synthetic learner data; preserve the independent, zero-runtime-dependency library and keep confidential material out of public changes. Public contract changes require maintainer approval. -Open focused pull requests with the approved scope, tests and any outstanding limitations. Use synthetic learner data in tests. Contributions must comply with [Apache-2.0](LICENSE). Do not transfer private code or contribute material without confirmed rights. +Contributions intentionally submitted for inclusion follow Section 5 of the [Apache License 2.0](LICENSE), unless explicitly stated otherwise or covered by a separate agreement. Do not submit material you lack permission to distribute. diff --git a/README.md b/README.md index d57b03d..cecc01c 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,97 @@ # Preceptor -Preceptor is an instructional engine for building tutors and learning applications. It helps decide when to explain a concept, ask a question, offer a hint or suggest practice based on the learner's request and the purpose of the session. +[![CI](https://github.com/0xbuffdev/preceptor/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/0xbuffdev/preceptor/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/%400xbuff%2Fpreceptor)](https://www.npmjs.com/package/@0xbuff/preceptor) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/0xbuffdev/preceptor/blob/main/LICENSE) [![Node.js](https://img.shields.io/badge/node-%3E%3D24-blue)](https://github.com/0xbuffdev/preceptor/blob/main/package.json) -The instructional policy works without a language model. Applications can connect a model, lesson source and learner memory for contextual teaching. The host controls access to learner data and retains authority over assessment, grades and academic progress. +Preceptor is an instructional engine for tutors and learning applications. It selects teaching strategies, coordinates optional model assistance and gives applications control over which lesson material and learner context a tutor may use. -## Status +The planner works offline without a language model. Applications can supply their own model, lesson source and memory adapters for contextual instruction. Preceptor returns advisory guidance; the host retains authority over assessments, grades and academic progress. The library has no runtime dependencies. -Preceptor is in development. The model-free planner, bounded session engine and injected model, lesson, practice and narrative memory ports are implemented. Committed host-result summaries are also supported through a separate read-only projection. The package is not yet available on npm. +## Installation -## Intended features +Requires Node.js 24 or later and ESM. The first release, `0.0.1`, is being prepared. Once the version is available on npm: -- Deterministic teaching strategies with no model or network required for planning. -- Guided learning, ungraded practice, retrieval coaching and project defense preparation. -- Optional model-generated explanations and feedback grounded in authorized lesson material. -- Scoped tools with explicit permissions, resource limits and cancellation. -- Optional learner memory with provenance, revision checks and protection against stale writes. -- Read-only summaries of committed assessment decisions, including corrections and revocations. +```sh +npm install @0xbuff/preceptor@0.0.1 +``` -## Architecture +Until then, build and test from source using the development commands below. Pin the version you have tested. -```mermaid -flowchart LR - H[Host application] --> S[Session engine] - S --> P[Instructional policy] - S --> M[Optional model] - S --> D[Tool dispatcher] - D --> A[Scoped host adapters] - S --> R[Advisory result] -``` +## Quick start -The host supplies the session mode, authorized context, permissions and limits. The policy selects a teaching strategy without performing I/O. For generative assistance, the session engine calls the injected model and validates its tool requests before the dispatcher invokes a host adapter. +Request a question-led teaching strategy without connecting a model or any tools. -Effective tool permissions are restricted by the session mode, host grants, learner consent and installed operations. Lesson text, model responses and stored memory cannot grant additional permissions. The engine reports unavailable or partial results when a provider fails or a limit is reached. +```ts +import { type HostPolicy, planInstruction, POLICY_REVISION } from "@0xbuff/preceptor"; -### Instructional modes +const host: HostPolicy = { + policyRevision: POLICY_REVISION, + sessionId: "example", + mode: "guided_learning", + grants: [], + consent: [], + installed: [], +}; + +const plan = planInstruction(host, { + assistance: "plan", + intent: "question", +}); +if (plan.status !== "completed" || plan.strategy !== "question") { + throw new Error("Expected a question plan"); +} +console.log(plan.nextActions[0]?.text); +``` -| Mode | Purpose | -| --------------------- | ---------------------------------------------------------- | -| `guided_learning` | Explanations, questions and hints while studying | -| `ungraded_practice` | Exercises and formative feedback | -| `retrieval_coaching` | Recall and review of previously studied material | -| `defense_preparation` | Rehearsal using authorized public criteria | -| `assessment_locked` | Fixed public process guidance, without model or tool calls | +The result contains a fixed teaching prompt and the effective capability set. A generative request without a model returns an explicit unavailable result. To generate advice, pass a `ModelPort` to `runInstruction`; see the [model example](https://github.com/0xbuffdev/preceptor/tree/main/examples/custom-model). -For example, a programming tutor can ask a learner to predict a function's result before explaining its execution. A mathematics tutor can ask the learner to justify a step in a proof. Both use the same instructional policy with different lesson sources. +## Features -### Memory and assessment +- Deterministic teaching strategies for guided learning, ungraded practice, retrieval coaching and defense preparation. +- Assessment lock that returns fixed public process guidance without calling a model or protected adapter. +- Optional provider-neutral model, exact-revision lesson and practice ports. +- Closed sequential tool dispatch with explicit permissions, byte and request limits, cancellation and bounded retries. +- Optional scoped narrative memory with revision-bound mutation proposals and host-owned deletion and replay protection. +- Read-only context from authorized, committed academic-result summaries, including correction and revocation. + +## Architecture ```mermaid flowchart LR - A[Official assessment record] --> S[Authorized summary] - S --> P[Preceptor] - P --> G[Teaching guidance] - P --> H[Host memory adapter] - H <--> N[Narrative memory] + H[Host policy and request] --> P[Pure planner] + P --> S[Session engine] + S --> M[Optional model] + M --> S + S --> D[Typed dispatcher] + D --> A[Scoped host ports] + S --> R[Advisory result] ``` -Narrative memory holds instructional observations and learner preferences. The host enforces scope, consent, provenance and revision checks. Learner edits take precedence over delayed model proposals, and deleted facts must not be restored by replay. +The host authenticates the session and binds the mode, grants, consent and available adapters. The planner selects a strategy and computes permissions. For generation, the session engine validates each model response and dispatches only authorized operations. It reports provenance, usage and typed failures. -Official academic records remain separate. Preceptor can explain an authorized assessment summary, but cannot change grades, admit submissions or issue credentials. Review recommendations from an independent scheduler may inform instruction without granting academic credit. +```mermaid +flowchart LR + C[Committed host decision] --> P[Summary projection] + P --> T[Session context] + M[Scoped narrative memory] --> T + T --> G[Advisory guidance] +``` -## Integration +Narrative memory and academic-result summaries are separate. The host owns storage, authorization, retention and official academic records. See the [architecture guide](https://github.com/0xbuffdev/preceptor/blob/main/docs/architecture.md). -Preceptor is designed to run inside the consuming application with caller-provided adapters. It requires no particular curriculum, model provider, database or cloud service. The application owns authentication, storage, transcript handling, privacy rights and provider costs. +## Documentation -The planned package name is `@0xbuff/preceptor`. Installation instructions and executable examples will be added once the public API and package have been verified. +| Guide | Contents | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| [Policy](https://github.com/0xbuffdev/preceptor/blob/main/docs/policy.md) | Modes, strategies, capability checks and fixed prompts | +| [Sessions](https://github.com/0xbuffdev/preceptor/blob/main/docs/sessions.md) | Model and tool ports, limits, failures and cancellation | +| [Memory](https://github.com/0xbuffdev/preceptor/blob/main/docs/memory.md) | Scoped facts, proposals, revision checks and deletion | +| [Committed summaries](https://github.com/0xbuffdev/preceptor/blob/main/docs/summaries.md) | Host-only projection, read authorization and provenance | +| [Architecture](https://github.com/0xbuffdev/preceptor/blob/main/docs/architecture.md) | Module boundaries and host responsibilities | +| [Examples](https://github.com/0xbuffdev/preceptor/tree/main/examples) | Offline planning, model, memory and summary integration | -## Development +The current policy is `preceptor-policy-v1`; committed summaries use `preceptor-summary-v1`. Only the package root is exported. The library does not include a model provider, storage backend or review scheduler. -Requires Node.js 24 or later, pnpm 11.2.2 and TypeScript 5.9.3 for development. +## Development ```sh git clone https://github.com/0xbuffdev/preceptor.git @@ -78,10 +101,10 @@ pnpm install --frozen-lockfile pnpm check ``` -The full check runs strict type checking, Biome, Vitest, the tsdown build and an independent offline ESM and TypeScript package check. The model-free planner is available in the local build. See [the policy guide](docs/policy.md) and [session integration guide](docs/sessions.md) and [memory integration guide](docs/memory.md) and [committed summary guide](docs/summaries.md). +Use Node.js 24+ and pnpm 11.2.2. The full check includes an independent offline installation of the packed archive, integration tests, import checks and compiled examples. -See [contributing](CONTRIBUTING.md), [security](SECURITY.md) and [source and release status](docs/source-rights.md). +Read the [development guide](https://github.com/0xbuffdev/preceptor/blob/main/docs/development.md), [contribution guidelines](https://github.com/0xbuffdev/preceptor/blob/main/CONTRIBUTING.md), [security policy](https://github.com/0xbuffdev/preceptor/blob/main/SECURITY.md) and [release policy](https://github.com/0xbuffdev/preceptor/blob/main/docs/releasing.md). ## License -[Apache-2.0](LICENSE). See [copyright and attribution](COPYRIGHT.md). +[Apache-2.0](https://github.com/0xbuffdev/preceptor/blob/main/LICENSE). See [copyright and attribution](https://github.com/0xbuffdev/preceptor/blob/main/COPYRIGHT.md). diff --git a/SECURITY.md b/SECURITY.md index 23291e4..800d669 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,7 +1,19 @@ -# Security +# Security policy -Preceptor is unreleased. No production version is supported yet. +Report vulnerabilities involving unauthorized tool execution, assessment-lock bypass, lesson or memory disclosure, stale memory resurrection, forged academic summaries, unbounded resource use or compromised package contents. -Report vulnerabilities through the repository's private vulnerability reporting feature if enabled, or contact a maintainer privately before posting details. Do not include learner records, credentials, protected assessment content or private prompts in public issues. +## Supported versions -Include the affected revision, a minimal synthetic reproduction and the impact. Host authentication, consent, storage isolation and provider quotas require separate verification in consuming applications. +The first public npm release is being prepared. Reports against the current repository are welcome. After publication, maintainers prioritize the latest release; no fixed response time, backport schedule or bug bounty is promised. + +## Reporting a vulnerability + +Use GitHub's [private vulnerability reporting](https://github.com/0xbuffdev/preceptor/security/advisories/new) if enabled. Otherwise, open a non-sensitive issue requesting a confidential reporting route. Do not publish exploit details, credentials, learner records, hidden assessment content or private prompts. + +Include the affected version or commit, a minimal synthetic reproduction, the expected and observed behavior, and the impact. Allow maintainers to investigate before disclosing details publicly. + +## Integration responsibilities + +The host authenticates learners, binds permissions and scope, enforces consent and storage isolation, protects assessment content, and controls provider transport, quotas and costs. Preceptor validates data and enforces its local operation and resource boundaries. It cannot certify a remote adapter, actual deletion or the truth of a model response. + +See the [architecture guide](docs/architecture.md) for the boundary between the host and the library. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..94faefd --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,53 @@ +# Architecture + +Preceptor exposes three operations from the package root: + +| Operation | Responsibility | +| ------------------------- | --------------------------------------------------------- | +| `planInstruction` | Pure instructional strategy and permission selection | +| `runInstruction` | Bounded session orchestration with optional host ports | +| `projectCommittedSummary` | Pure projection of an authorized, committed host decision | + +The package also exports the policy and summary versions, library session ceilings and TypeScript contracts. Internal modules are not public entry points. + +```mermaid +flowchart LR + H[Host] --> V[Validate inputs] + V --> P[Policy and strategy] + P --> S[Session] + S --> D[Dispatcher] + S --> M[Model port] + D --> L[Lesson / practice / memory] + S --> R[Result] +``` + +Contracts and validation define inert input and output data. Policy and strategy are deterministic. The session layer owns the deadline, budget and per-run state. Dispatch validates each model request before invoking a specific installed operation. Adapter implementations belong to the consumer. The only built-in module imported by the runtime is Node's `node:crypto` for summary digests. + +## Authority and context + +The host supplies authenticated mode and scope. Grants, consent, the mode ceiling and installed operations determine the effective capability set. Retrieved material, previous messages and model requests cannot extend permissions. Locked mode returns fixed process guidance without invoking a port. + +The model receives structured policy, bounded untrusted context and descriptors of allowed operations. It never receives callable host adapters or an identity selector. + +## Data boundaries + +```mermaid +flowchart LR + H[Authenticated host] --> S[Committed summary] + H --> N[Scoped narrative memory] + S --> C[Session context] + N --> C + C --> A[Advisory result] +``` + +The official academic record, narrative facts, transcript and review schedule are separate. The host commits official decisions and may supply minimal authorized summaries. Narrative memory operations are proposals; the storage adapter admits them atomically. The host owns transcripts and schedules. The core does not persist any of these records or award credit. + +## Integration checklist + +- Authenticate the learner and bind the mode, lesson revision and storage scope outside model control. +- Enforce consent, permissions, privacy and provider transport limits in each adapter. +- Use only minimal authorized lesson excerpts, active narrative facts and settled feedback cleared for disclosure. +- Cancel sessions when authority changes. Reconcile uncertain remote mutations without replaying a new identity. +- Verify isolation, deletion, costs and academic record handling in the actual host environment. + +See [policy](policy.md), [sessions](sessions.md), [memory](memory.md) and [summaries](summaries.md) for integration details. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..71dcb7d --- /dev/null +++ b/docs/development.md @@ -0,0 +1,28 @@ +# Development + +Use Node.js 24 or later, pnpm 11.2.2 and the locked TypeScript 5.9.3 toolchain. From a clean clone: + +```sh +corepack enable +pnpm install --frozen-lockfile +pnpm check +``` + +| Command | Purpose | +| --------------------- | --------------------------------------------------------- | +| `pnpm typecheck` | Strict source and test type checking | +| `pnpm check:style` | Biome formatting and lint checks | +| `pnpm format` | Apply formatting | +| `pnpm test` | Source-level unit, integration and security tests | +| `pnpm build` | ESM and declaration output in `dist/` | +| `pnpm verify:package` | Verify an already built package and run offline consumers | + +Keep runtime dependencies empty. Tests use synthetic learner data and independent host fixtures. They exercise policy decisions, malformed requests, permissions, provider failures, resource limits, memory lifecycle and summary reconciliation. + +## Installed-package checks + +The verifier packs locally with scripts disabled, checks the exact archive inventory and digest, and installs it offline in an independent temporary project. It tests the public ESM surface, import purity, TypeScript declarations, runtime integrations, the README quick start and all four shipped examples. No provider or workspace alias is needed. Temporary files are removed after verification. + +The read-only quality workflow runs on Ubuntu and Windows and retains the tested archive and evidence JSON for the exact commit. See [release verification](releasing.md). + +Do not edit generated `dist/` files. Keep examples and documentation in step with the public contract. See [contributing](../CONTRIBUTING.md) and [security](../SECURITY.md). diff --git a/docs/memory.md b/docs/memory.md index b92d08b..af659bb 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -1,11 +1,37 @@ # Narrative memory -Preceptor can use an optional `MemoryPort` for narrative struggles, preferences and observations. Pass it as `SessionPorts.memory`; install and authorize each operation separately. Without the port, planning and model assistance still work, and memory requests are denied. Locked assessments do not call the port. +Add a `MemoryPort` to `SessionPorts.memory` to recall learner preferences, struggles and observations or propose changes. Install and authorize each operation separately. Planning and model assistance work without memory. Locked assessments never call a memory port. -The model may request bounded recall, propose a new observation, or propose updating or forgetting an exact model-owned revision already supplied to it during the current run. It cannot supply an actor, source lineage, operation identity, scope or consent epoch. The engine validates request and response shapes, UTF-8 envelopes, remaining recall item count and fact size; it counts every attempt. An omitted update target means create, not upsert. The model cannot update or forget learner-owned facts. The fact-size limit applies to the serialized proposal and returned fact; adapters receive the effective maximum and must bound the fact they admit. +## Operations -Bind the adapter to one authenticated scope and current consent/session epoch. The host must independently reauthorize every operation and atomically assign the model actor, source lineage and durable operation ID; the run-local session ID and attempt are correlation coordinates only. Do not use model call IDs as durable authorization. Identical operation replay returns its prior receipt while authorized; a conflicting payload, stale revision, learner edit or revoked consent must be declined. Never automatically retry mutations. Recall must return active facts only and accurately indicate truncation. Later recall of a newer revision or a successful mutation removes superseded facts from earlier model context without removing unrelated facts or refunding usage. Recall call identity and completeness describe the original recall; its fact list is the remaining active projection. A model-visible fact contains an opaque source reference and revision, not an account selector or academic result. +| Operation | Model request | +| ----------------- | ---------------------------------------------------------------------- | +| `memory.recall` | Optional topic and item limit | +| `memory.remember` | Kind and text, with an exact fact ID and expected revision for updates | +| `memory.forget` | Fact ID and expected revision | -Retraction removes a fact from active recall. The host must prevent older source/operation/session lineage from recreating a deleted fact, including after cache rebuild or restore. Use minimal opaque suppression markers, not deleted text as a denylist. The host owns authentication, export, correction, physical erasure, backups and consent revocation. `MemoryLifecyclePort` describes a separate host-only lifecycle boundary; the session does not accept it or expose it to the model. The library does not provide a storage implementation or certify deletion. +A remember request without an update target creates a fact. It is not an upsert. Updates and forget requests target only model-owned revisions already delivered to the model during the current run. The model cannot choose the actor, source lineage, durable operation identity, scope or consent epoch. -A validated applied receipt appears in the session tool outcomes even if later model generation fails. No automatic rollback is attempted. A cancelled, timed-out, malformed or oversized adapter response may leave the remote outcome unknown; reconcile it in the host, without minting a new operation identity. Use a fresh authorized session after scope or consent changes. +The engine validates requests and responses, bounds UTF-8 envelopes and the remaining recall count, and counts every attempt. The fact-size limit applies to serialized proposals and returned facts; the adapter receives the maximum and must also bound admitted facts. + +See the [custom memory example](../examples/custom-memory/index.ts) for a synthetic read-only adapter. + +## Bind memory to the host + +Bind each adapter to one authenticated scope and current consent/session epoch. Reauthorize every operation. Atomically assign the model actor, source lineage and durable operation ID. The run-local session ID and attempt are correlation coordinates, not durable authorization; model call IDs must not determine storage identity. + +When authorized, identical operation replay returns its previous receipt. Decline conflicting payloads, stale revisions, learner-edited targets and revoked consent. Never automatically retry mutations. Return active facts only and report truncation accurately. + +A newer recalled revision or successful mutation removes superseded facts from subsequent model context while preserving unrelated facts. The recall identity and completeness still describe the original recall. Usage already charged is not refunded. + +## Deletion and consent + +Retraction removes a fact from active recall. The host must prevent old source, operation and session lineage from recreating deleted facts, including after a cache rebuild or restore. Keep minimal opaque suppression markers; do not retain deleted prose as a denylist. + +Use `MemoryLifecyclePort` for a separate authenticated export/deletion boundary. It is not a session adapter or model-callable operation. The host manages retention, backup deletion, consent and physical erasure. Preceptor supplies contracts and validates the session boundary, but does not implement storage or certify deletion. + +## Reconcile mutations + +A validated applied receipt appears in tool outcomes even if later generation fails. Cancellation, deadline expiry, malformed or oversized responses can leave the remote mutation outcome unknown. Reconcile that outcome in the host without creating a new operation identity. Start a fresh authorized session after scope or consent changes. + +Narrative observations remain advisory. Keep them separate from [committed academic summaries](summaries.md), transcripts and scheduling data. diff --git a/docs/policy.md b/docs/policy.md index 58b4f8c..7de8eff 100644 --- a/docs/policy.md +++ b/docs/policy.md @@ -1,6 +1,10 @@ -# Model-free policy +# Instructional policy -The pure planner requires no model or provider. Pass a host-authenticated policy and a separate request to `planInstruction`. The host establishes identity, authorized mode, lesson revision, grants, consent and installed capability names; the library validates their structure. Never populate these authority fields from learner or model input. +Use `planInstruction(host, request)` to choose a teaching strategy and determine which operations the tutor may use. Planning is deterministic and requires no model, storage or network connection. + +The host authenticates the session and supplies its mode, grants, consent, installed capability names and, where needed, the exact lesson reference. Pass learner intent separately. Do not derive authority from learner text or model output. + +## Plan a session ```ts import { type HostPolicy, planInstruction, POLICY_REVISION } from "@0xbuff/preceptor"; @@ -20,10 +24,30 @@ if (result.status === "completed") { } ``` -A plan contains the policy revision, mode, strategy, reason, effective capability names, typed capability denials and fixed teaching prompts. The prompts do not claim to have read lessons, inspected work or evaluated a learner. A generation request returns `model_unavailable`; the assessment lock instead returns only fixed public process guidance and no capabilities. +A completed plan contains the policy version, mode, strategy, selection reason, effective capability set, typed denials and fixed prompts. These prompts do not inspect work or claim to have read lessons. With `assistance: "generate"`, the pure planner returns `model_unavailable` except in locked mode. Use [session integration](sessions.md) for model-assisted instruction. + +## Modes and strategies + +| Host mode | Default | Other supported strategies | +| --------------------- | ---------- | ----------------------------------------- | +| `guided_learning` | `explain` | `question`, `hint`, `practice`, `reflect` | +| `ungraded_practice` | `practice` | `question`, `hint`, `reflect` | +| `retrieval_coaching` | `retrieve` | `question`, `reflect`, `practice` | +| `defense_preparation` | `question` | `reflect`, `hint` | +| `assessment_locked` | `pause` | None | + +Unsupported intents fall back to the mode default. A locked assessment always returns fixed public process guidance and an empty capability set. Optional non-credit difficulty (`low`, `medium`, `high`) and progress (`starting`, `practicing`, `reviewing`) signals can affect fixed prompts, never permissions. + +## Capabilities + +The closed operation vocabulary is `lesson.read`, `practice.suggest`, `memory.recall`, `memory.remember` and `memory.forget`. An operation must be within the mode ceiling, appear in the grants and consent lists, and be installed. Empty lists grant nothing. Defense preparation denies memory writes and forget operations. + +Lesson access requires an exact document reference and revision with `visibility` (`public` or `restricted`) and `kind` (`lesson` or `assessment_criteria`). Defense preparation accepts only public assessment criteria. The host must authenticate and attest the classification of the exact revision. Missing classification rejects the input. + +Installed capability names describe availability. The session engine also checks that the corresponding callable adapter is present. -Grants, consent and installed operations are explicit lists of capability names, intersected with the host mode ceiling. Empty lists grant nothing. Lesson access also requires an exact document reference and revision, `visibility` (`public` or `restricted`) and `kind` (`lesson` or `assessment_criteria`). The host must attest the classification of the exact revision. In defense preparation, the planner permits `lesson.read` only when both `visibility: "public"` and `kind: "assessment_criteria"` are present. Public ordinary lessons and restricted criteria are denied. Missing or unknown classification rejects the input. The planner validates metadata; it cannot authenticate the classification or inspect lesson contents. Installed capability names describe availability, not actual callable adapters. The session engine additionally intersects them with the actual injected lesson and practice operations. See [session integration](sessions.md). +## Validation -Unknown fields, modes, revisions, intents, duplicate capabilities, invalid references and malformed data are rejected with fixed diagnostic reasons. Identifiers are nonempty, trimmed and at most 256 UTF-8 bytes. Optional host signals are non-credit difficulty (`low`, `medium`, `high`) and progress (`starting`, `practicing`, `reviewing`). They can affect a fixed prompt but cannot expand permissions. +Use `POLICY_REVISION` from the package. Unknown fields, modes, revisions, intents, duplicate capabilities, invalid references and malformed data are rejected with fixed diagnostic reasons. Identifiers must be nonempty, trimmed and at most 256 UTF-8 bytes. -Pass inert plain data, for example decoded JSON from a bounded transport. Accessors and unusual prototypes are rejected; object validation is not a sandbox for executable JavaScript proxies. The host remains responsible for authenticating requests, scoping adapters and enforcing consent at every protected operation. +Pass inert plain data from a bounded transport. Validation rejects accessors and unusual prototypes; it is not a sandbox for executable proxies. Authenticate requests, scope adapters and enforce consent in the host. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..7c4b6ca --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,46 @@ +# Releasing Preceptor + +Preceptor is preparing its first npm release as `@0xbuff/preceptor@0.0.1` under Apache-2.0. The package uses Semantic Versioning; consumers should pin versions before 1.0.0. A publishable manifest and public repository do not mean a package has been published. + +## Verify the candidate + +Use the documented Node.js and pnpm toolchain on a clean checkout: + +```sh +git rev-parse HEAD +corepack enable +pnpm install --frozen-lockfile +pnpm check +``` + +On Ubuntu, also run `pnpm check:release-preflight`. This requires Bash, jq, OpenSSL and GNU tar/coreutils. The release regression uses synthetic artifacts and stubbed GitHub and npm commands. It never contacts the registry or requests staging. On other platforms, record it as not run and require successful Ubuntu CI. + +The quality workflow verifies both Ubuntu and Windows. It retains the tested archive and `evidence.json` for the exact commit and workflow attempt. The npm archive must contain exactly seven files: + +- `package.json`, `README.md`, `CHANGELOG.md` +- `LICENSE`, `COPYRIGHT.md` +- `dist/index.js`, `dist/index.d.ts` + +Source maps, private records, provider SDKs and runtime dependencies are excluded. Verify the actual tarball's file list, SHA-256, npm SHA-512 integrity, byte count and public manifest. Download and inspect both candidate artifacts independently; matching tarball digests establish identical archive bytes. The packed tests cover ESM, declarations, import purity, integrations, the README quick start and examples. + +## Approve publication + +Before staging, confirm npm scope ownership, name/version availability, publisher identity, contributor rights, notices and dependency audit results. Review the exact current main commit, CI, artifact and its SHA-256. Approve the release date and move the Unreleased changelog entries into a dated `0.0.1` section. Rebuild and reverify if the changelog or any other packed file changes. + +The [source-rights record](source-rights.md) documents the initial implementation approval. Each release needs explicit approval for the exact candidate and for publication. Do not create a version tag or GitHub release without authorization. + +## Protected staging + +The manual `Stage npm package` workflow runs on `main` in the `npm-stage` environment. It downloads the successful current main quality run's Ubuntu artifact, verifies approval variables, run identity, archive metadata and contents, and rechecks main and digest before requesting npm staging. It does not rebuild, publish directly, or tag a commit. + +1. Configure GitHub Settings > Environments > `npm-stage` to restrict deployments to main, require reviewers and disallow administrator bypass. Prevent self-review where a separate reviewer is available. +2. After approval, set environment variables `PRECEPTOR_STAGE_COMMIT`, `PRECEPTOR_STAGE_RUN_ID` and `PRECEPTOR_STAGE_SHA256` to the approved current main commit, successful main quality run ID and actual tarball digest. Leave them unset before approval. +3. Configure [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) for `0xbuffdev/preceptor`, workflow `release.yml`, environment `npm-stage`, with staging-only permission. Disable direct publish and dist-tag changes. Use GitHub-hosted runners. Verify registry setup and current npm requirements before dispatch. Do not add a long-lived publishing token to quality CI. +4. Dispatch the workflow with the approved run ID and approve the protected environment job. Inspect the staged version and its tarball digest. Use npm's required human approval and authentication only after separate publication authorization. +5. Clear the approval variables when finished. + +## After publication + +Download the public registry tarball and compare its SHA-256 against the approved artifact. Confirm registry metadata, provenance, version and dist-tag. Install the exact version in an independent ESM project with scripts disabled and run the model-free quick start without credentials. Record the results, tag and release notes only when authorized. + +If a bad version is published, stop recommending it, notify consumers, and publish a reviewed correction. Use npm deprecation and dist-tag changes only with maintainer approval; do not overwrite an immutable published version. Follow the [security policy](../SECURITY.md) for confidential vulnerabilities. diff --git a/docs/sessions.md b/docs/sessions.md index 06cad49..0fb912d 100644 --- a/docs/sessions.md +++ b/docs/sessions.md @@ -1,13 +1,73 @@ # Session integration -Use `planInstruction` for pure planning, or `runInstruction(host, request, ports, options)` for bounded advisory assistance. Supply the host-authenticated policy separately from the learner's text. No adapter is required for planning. A locked assessment never invokes any adapter, even if a model and tools are supplied. +Call `runInstruction(host, request, ports, options)` for bounded advisory assistance. Supply authenticated host policy separately from the learner's text. Planning needs no adapter. An assessment lock never invokes any port, including a configured model or summary reader. -The model port has a configured provider/model identity and a `generate(input, signal)` method. Input separates public instructional policy from untrusted current learner text, alternating prior learner/assistant messages and dispatcher-generated tool results. It includes typed descriptors for the permitted installed operations, not callable functions. Return exactly one of `final`, `tools` or `unavailable`, with matching attribution and optional adapter-reported token counts. +## Connect a model -A lesson port takes the exact host-authorized reference, a maximum excerpt byte count and signal. Return the exact document/revision with UTF-8 text, actual text byte count and `complete` or `truncated` completeness, or a typed unavailable response. No alternate lookup is attempted. The host must independently enforce the scope, source classification and access rights. Set host option `requiredLesson: true` for generation that cannot proceed without a complete authorized source. Otherwise the model may request lesson access through `lesson.read` with empty arguments. Practice suggestions take only topic and objective and return advisory strings. Memory operations are available only with a scoped optional memory adapter and matching grants, consent and mode. See [memory integration](memory.md). An optional host-authorized committed summary is supplied separately through `options.summary` and the read-only `ports.summary`, never through a model tool. See [committed summaries](summaries.md). +The `ModelPort` declares its provider and model identity and implements `generate(input, signal)`. Its input separates policy from untrusted learner text, alternating prior learner/assistant messages, tool results and optional committed summary context. The model receives typed operation descriptors, not callable functions. -The host and request may provide smaller nonnegative integer limits; the effective limit is the smallest of both and the frozen library ceiling. See `SESSION_LIMITS` for the versioned limits. The input text/history JSON envelope, per-call model context, model response envelope and cumulative model output are measured in UTF-8 bytes. Tool result accounting charges the larger of an adapter response and its normalized tool-result envelope, including separate retry responses. Input and peak model-context bytes and cumulative model-output and tool-result bytes are reported for bounded data. Structured input is limited to depth 8, 4096 nodes, 32 object keys and 64 array elements; tool batches are capped at 16. Prior history must contain complete alternating learner/assistant pairs. Pass inert plain data rather than executable proxies. +Return one of the following response variants with matching attribution: -The dispatcher runs requests sequentially, denies unknown or unavailable tools, and counts invalid, denied and duplicate attempts. Before dispatch and after each tool result, the engine checks that a follow-up model request fits the remaining request, output and context budgets. Model-request usage and model provenance are recorded only when the adapter is actually invoked; the model receives the remaining request count after its current invocation. Completed tool outcomes remain visible if a later budget check stops the run. Call IDs are scoped to one run and a valid ID is reserved even when its call envelope is rejected. Only explicit transient model responses and idempotent lesson reads may be retried; practice is never automatically replayed. The host remains responsible for per-call scope checks, authorization changes, transport/materialization limits, provider quotas and actual remote cancellation. An abort signal and one monotonic deadline bound local waiting, including noncooperative promises; synchronous adapter code cannot be preempted, and the library cannot undo a remote action or guarantee that a provider did not bill. +| Kind | Contents | +| ------------- | ------------------------------------------ | +| `final` | Nonempty advisory text | +| `tools` | A bounded list of typed operation requests | +| `unavailable` | `transient` or `unavailable` reason | -Terminal states distinguish completed advisory text, unavailable generation, denied required access, invalid input, limits, cancellation, deadlines and incomplete context. Required truncated or unavailable lessons stop generation. Optional tool failures/truncation result in incomplete context even if a model later returns text. Provider-reported tokens are informational only. Memory mutations are bounded proposals admitted by the host; successful admissions are not rolled back on a later model failure. No official grades, enrollment or scheduling changes are part of these ports. +Each response can include adapter-reported input/output token counts. These counts are informational, not independently enforced token limits. See the [custom model example](../examples/custom-model/index.ts). + +## Lesson and practice + +A lesson adapter receives the exact host-authorized reference, maximum excerpt size and abort signal. Return the matching document and revision, UTF-8 excerpt, actual byte count and completeness (`complete` or `truncated`), or a typed unavailable response. Preceptor never attempts an alternate lookup. + +Set `options.requiredLesson: true` when generation requires a complete source. Otherwise the model may request `lesson.read` with empty arguments. Practice requests contain only topic and objective; return advisory suggestion strings. Enforce the source classification, scope and current access rights inside the adapter. + +Add a scoped [memory port](memory.md) only when required. Committed academic summaries use the separate host-only [summary integration](summaries.md). + +## Limits and usage + +Both the host and request may narrow the nonnegative integer limits. The effective value is the smallest of the request, host and frozen library ceiling. Import `SESSION_LIMITS` for the versioned defaults. + +| Limit | Default | +| ----------------- | ------: | +| `inputBytes` | 16,384 | +| `contextBytes` | 65,536 | +| `lessonBytes` | 16,384 | +| `toolResultBytes` | 32,768 | +| `responseBytes` | 16,384 | +| `outputBytes` | 65,536 | +| `memoryItems` | 32 | +| `memoryFactBytes` | 2,048 | +| `modelRequests` | 8 | +| `toolAttempts` | 16 | +| `retries` | 2 | +| `elapsedMs` | 60,000 | + +Input text/history, each model context, each model response and cumulative model output are measured as UTF-8 JSON envelopes. Tool result accounting charges the larger of the adapter response and normalized result envelope, including retry responses. Usage reports input bytes, peak model context, cumulative output and tool-result bytes, request and attempt counts, retries and memory items. + +Structured input is limited to depth 8, 4,096 nodes, 32 object keys and 64 array elements. Tool batches are capped at 16. History must contain complete alternating learner/assistant pairs. Pass inert data, not executable proxies. + +## Dispatch and termination + +The dispatcher runs tool requests sequentially. Unknown, denied, invalid and duplicate calls consume an attempt; a valid call ID is reserved for the run even when its envelope is rejected. Before dispatch and after each result, the engine checks whether a follow-up model request fits the remaining budget. Usage and model provenance are recorded when the adapter is invoked. The model receives the remaining request count after its current invocation. + +Only explicit transient model responses and idempotent lesson reads may be retried within the shared limits. Practice and memory mutations are never automatically replayed. + +An abort signal and one monotonic deadline bound local waiting, even for noncooperative promises. Late results are discarded and dispatch stops. Synchronous adapter code cannot be preempted. The host controls transport limits, remote cancellation, provider quotas and actual costs. + +## Handle the result + +| Status | Meaning | +| -------------------- | ------------------------------------------------------------------------------------- | +| `completed` | Plan or advisory result completed | +| `incomplete_context` | A requested context source was unavailable, denied, truncated or otherwise incomplete | +| `unavailable` | Generation unavailable or provider/model response failed | +| `denied` | Required lesson access was denied | +| `invalid_input` | Invalid session input | +| `limit_exhausted` | A named resource or structure limit was exceeded | +| `cancelled` | Host cancellation | +| `deadline_exceeded` | Local deadline expired | + +A required unavailable or truncated lesson stops generation. Optional tool failures or truncation yield incomplete context even if the model returns text. Inspect status, reason, tool outcomes, usage and provenance together. Completed outcomes remain visible if a later limit stops the run. + +Memory admissions are not rolled back when later generation fails. Reconcile ambiguous remote outcomes in the host. Session advice cannot grant grades, enrollment or scheduling changes. diff --git a/docs/source-rights.md b/docs/source-rights.md index e58d455..e6370d0 100644 --- a/docs/source-rights.md +++ b/docs/source-rights.md @@ -1,9 +1,7 @@ -# Source and release status +# Source rights and licensing -Preceptor's engineering foundation is in this standalone repository. The current bootstrap is original scaffolding; no private application implementation, learner content or provider code was transferred. The development dependency lock resolutions match the sibling Assay toolchain; no Assay runtime source is included. +Preceptor is maintained in one standalone repository. Its source was developed independently of private application code, learner records and provider implementations. The development toolchain shares dependency versions with Assay; no Assay runtime code is bundled. -On 2026-11-28 the maintainer selected Apache-2.0, matching Assay. See [LICENSE](../LICENSE) and [COPYRIGHT.md](../COPYRIGHT.md). The package remains private and unpublished at version `0.0.0`. The standalone history through the committed-summary implementation has one recorded Git author name; commit metadata alone does not establish ownership or contributor rights. On 2026-11-29 the maintainer explicitly confirmed sufficient ownership and contributor rights to distribute the reviewed complete candidate under Apache-2.0 and approved its provenance and licensing, subject to final verification. [Maintainer acceptance and verification evidence](https://github.com/0xbuffdev/preceptor/pull/10#issuecomment-7253842200). The reviewed source and merged source at `598f97e30aee4ffc924d5b79bb171d9bd1edeb4a` have identical file trees; both platform checks and independent archive verification passed. Source visibility and publication remain separate gates. No publication configuration is established by this foundation. +0xBUFF selected Apache-2.0 on 2026-11-28. On 2026-11-29, the maintainer [confirmed source provenance and sufficient ownership and contributor rights](https://github.com/0xbuffdev/preceptor/pull/10#issuecomment-7253842200) for the reviewed implementation. See [LICENSE](../LICENSE) and [COPYRIGHT.md](../COPYRIGHT.md). New contributions must comply with the license and maintainers must review their provenance. -The intended first release remains subject to the canonical specification, source review and approval. No registry publish, release tag or host deployment is authorized by engineering checks. - -The quality workflow retains the exact checked archive with its commit, file list, SHA-256 and npm integrity digest. These are engineering evidence, not a license grant or release approval. +The public repository and publishable package metadata do not themselves authorize npm publication. Review the exact archive before each release; see [releasing](releasing.md). diff --git a/docs/summaries.md b/docs/summaries.md index e0229a6..687c1a8 100644 --- a/docs/summaries.md +++ b/docs/summaries.md @@ -1,11 +1,42 @@ # Committed host-result summaries -Preceptor can explain a minimal summary of an already committed host decision. It cannot authenticate a grade, grade a submission, award credit or change the official record. +Preceptor can use minimal feedback from an already committed host decision to personalize instruction. The official academic record stays with the host. The library cannot authenticate a grade, assess a submission or award credit. -Use `projectCommittedSummary(authorization, previous, event, knownEvent)` from the authenticated host ingestion path. The host supplies an authorized scope, decision/source/course/outcome references, current source-policy revision and consent. Events use `SUMMARY_SCHEMA_VERSION`, committed status, a unique event ID, positive revision, disposition and optional safe feedback (at most 2048 UTF-8 bytes). Corrections and revocations are full snapshots with an explicit earlier superseded revision; revocations contain no feedback. JSON UTF-8 envelope limits are 8 KiB per incoming event, 16 KiB per stored projection and 16 KiB plus 64 bytes per framed read response. The projection allows for duplicated escaped identifiers and digests; admission validates the produced projection before returning it. Session reads also honor any narrower context limit. +## Project a committed event -The reducer is pure. Before invoking it, atomically load the current decision projection and the scope-wide receipt for the event ID (undefined only if genuinely unused). Persist returned projection and new receipt in the same host transaction. Never replace an existing receipt. Exact replay is a no-op; lower revisions cannot reinstate stale feedback. Conflicting same-revision content or conflicting event ID reuse withholds the decision. If `conflictingDecisionId` is returned, also withhold that other decision in the same transaction. Only a newer, independently authorized full snapshot referencing the withheld revision or later can reconcile a conflict. The host must not discard revision or event markers to bypass conflicts or revocations. Receipt digests use Node's built-in SHA-256 and contain no historic prose; they are not signatures, authentication, or erasure guarantees. +Call `projectCommittedSummary(authorization, previous, event, knownEvent)` only in the authenticated host ingestion path. -For a session, supply a `SummaryReadAuthorization` in host-only `options.summary` with the exact expected revision and source policy, and a scoped `SummaryReadPort` in `ports.summary`. The adapter reads only the current projection after authenticating the scope and consent. A session takes one bounded snapshot, not a live subscription; the host must cancel active sessions and invalidate caches on consent or authority changes. Planning and locked assessments do not invoke the adapter. A missing adapter, denied scope, revoked/conflicting/stale projection or unavailable summary yields explicitly incomplete advisory context when requested. Only an active matching summary reaches the model, without the scope key or receipt markers; its feedback is untrusted data. There is no model-callable ingestion or summary operation. Ordinary tutoring works without this integration. Terminal session provenance reports the exact delivered decision/source and snapshot/source-policy revisions in `summary`, without feedback, scope or receipt digests. This reference is recorded only when a model invocation receives an active summary, even if generation later fails. `summaryStatus` reports blocked or unavailable context, or `not_delivered` if a requested summary was not delivered. +The authorization identifies the permitted scope, decision, source, course, outcome, source-policy revision and consent. Events use `SUMMARY_SCHEMA_VERSION`, a committed marker, unique event ID, positive revision and disposition. Optional safe feedback is limited to 2,048 UTF-8 bytes. Corrections and revocations are full snapshots with an explicit earlier superseded revision. A revocation carries no feedback. -The host screens feedback for protected material, authenticates settled events, persists revision and idempotency markers, and enforces deletion, consent and real isolation. No raw technical findings, hidden rubrics, private test cases, official record writes or scheduling adapter are needed. +The reducer checks the JSON envelope size (8 KiB per incoming event and 16 KiB per stored projection) and validates the produced projection before returning it. The stored projection accommodates escaped identifiers and digests. Read responses are bounded to 16 KiB plus 64 bytes and any narrower session context limit. + +See the [custom summary example](../examples/custom-summary/index.ts). + +## Apply the projection atomically + +Load the current decision projection and scope-wide receipt for the event ID in the same host transaction. Pass an undefined receipt only when the ID is genuinely unused. Persist returned projection and new receipt atomically; never replace an existing receipt. + +| Delivery | Behavior | +| ----------------------------------------------------------- | ------------------------------------------ | +| Exact replay | No change | +| Lower revision | Current projection retained | +| Conflicting content at the same revision or reused event ID | Decision withheld | +| Authorized newer full snapshot | Replaces or revokes the current projection | + +If the reducer returns `conflictingDecisionId`, withhold that other decision in the same transaction. Resolve a conflict only with a newer independently authorized full snapshot referencing the withheld revision or later. Preserve revision and event markers across corrections and revocations. + +Receipt digests use Node's built-in SHA-256 and hold no historic prose. They identify content; they do not authenticate events or prove erasure. + +## Deliver context to a session + +Provide the exact expected revision and source policy in host-only `options.summary` (`SummaryReadAuthorization`) and a scoped `ports.summary` (`SummaryReadPort`). Recheck authentication and consent when reading the current projection. + +A session reads one bounded snapshot. Cancel active sessions and invalidate caches when authority or consent changes. Planning and locked assessments never invoke the summary adapter. Ordinary instruction works without one. + +A requested missing, denied, stale, conflicting, revoked or unavailable projection produces explicitly incomplete context. Only an active matching summary reaches the model; scope keys and receipt markers are excluded. Feedback remains untrusted text. There is no model-callable summary ingestion or read operation. + +## Inspect provenance + +Session provenance reports `summaryStatus` and, when an active summary was delivered to a model invocation, the exact decision, source, snapshot revision and source-policy revision in `summary`. This reference is preserved even if generation subsequently fails. A requested but undelivered summary reports `not_delivered` when applicable. Provenance omits feedback and private receipt or scope data. + +The host screens feedback for protected material, authenticates settled events, and enforces isolation, consent and deletion. Raw technical findings, hidden rubrics, private test cases and official record writes do not belong in this integration. diff --git a/package.json b/package.json index 6348aeb..4a508a8 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "@0xbuff/preceptor", - "version": "0.0.0", + "version": "0.0.1", "description": "Portable instructional engine for guided learning and practice", - "private": true, + "private": false, "license": "Apache-2.0", "type": "module", "packageManager": "pnpm@11.2.2", @@ -38,6 +38,7 @@ "check:style": "biome check .", "lint": "biome lint .", "verify:package": "node scripts/verify-package.mjs", + "check:release-preflight": "bash tests/release-preflight.sh", "check": "pnpm typecheck && pnpm check:style && pnpm test && pnpm build && pnpm verify:package" }, "devDependencies": { @@ -46,5 +47,17 @@ "tsdown": "0.23.7", "typescript": "5.9.3", "vitest": "4.1.12" + }, + "homepage": "https://github.com/0xbuffdev/preceptor#readme", + "keywords": [ + "education", + "instruction", + "tutoring", + "learning", + "pedagogy" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" } } diff --git a/scripts/release-preflight.sh b/scripts/release-preflight.sh new file mode 100644 index 0000000..fa5d0e5 --- /dev/null +++ b/scripts/release-preflight.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Read-only candidate validation; no credentials, network, or npm operations. +set -euo pipefail + +fail() { + printf 'Release preflight: %s\n' "$1" >&2 + exit 1 +} + +approval() { + [[ "$GITHUB_REPOSITORY" == "0xbuffdev/preceptor" ]] || fail repository + [[ "$GITHUB_REF" == "refs/heads/main" ]] || fail branch + [[ "$RUN_ID" =~ ^[1-9][0-9]*$ ]] || fail run-id + [[ "$APPROVED_RUN_ID" == "$RUN_ID" ]] || fail approved-run-id + [[ "$APPROVED_SHA" =~ ^[a-f0-9]{40}$ && "$APPROVED_SHA" == "$GITHUB_SHA" ]] || fail approved-sha + [[ "$APPROVED_DIGEST" =~ ^[a-f0-9]{64}$ ]] || fail approved-digest +} + +archive_files() { + printf '%s\n' CHANGELOG.md COPYRIGHT.md LICENSE README.md \ + dist/index.d.ts dist/index.js package.json +} + +approval +case "$1" in + approval) + [[ "$#" == 1 ]] || fail arguments + ;; + run) + [[ "$#" == 3 ]] || fail arguments + [[ "$2" == "$GITHUB_SHA" ]] || fail stale-main + jq -e --arg sha "$GITHUB_SHA" --arg repo "$GITHUB_REPOSITORY" --arg id "$RUN_ID" ' + (.id | tostring) == $id and + .head_sha == $sha and .head_branch == "main" and + .head_repository.full_name == $repo and .repository.full_name == $repo and + .path == ".github/workflows/ci.yml" and .event == "push" and + .status == "completed" and .conclusion == "success" and + (.run_attempt | type == "number" and . >= 1 and floor == .) + ' "$3" >/dev/null || fail quality-run + attempt="$(jq -er '.run_attempt' "$3")" + [[ "$attempt" =~ ^[1-9][0-9]*$ ]] || fail run-attempt + printf '%s\n' "$attempt" + ;; + archive) + [[ "$#" == 4 ]] || fail arguments + [[ "$3" =~ ^[1-9][0-9]*$ ]] || fail run-attempt + [[ "$4" == "preceptor-candidate-ubuntu-latest-$GITHUB_SHA-$3" ]] || fail artifact-name + cd "$2" + [[ -f 0xbuff-preceptor-0.0.1.tgz && ! -L 0xbuff-preceptor-0.0.1.tgz && -f evidence.json && ! -L evidence.json ]] || fail artifact-files + [[ "$(find . -mindepth 1 -maxdepth 1 | wc -l)" -eq 2 ]] || fail artifact-files + [[ "$(sha256sum 0xbuff-preceptor-0.0.1.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] || fail archive-digest + integrity="sha512-$(openssl dgst -sha512 -binary 0xbuff-preceptor-0.0.1.tgz | openssl base64 -A)" + jq -e --arg digest "$APPROVED_DIGEST" --argjson size "$(wc -c < 0xbuff-preceptor-0.0.1.tgz)" \ + --arg commit "$GITHUB_SHA" --arg integrity "$integrity" ' + .name == "@0xbuff/preceptor" and .version == "0.0.1" and + .commit == $commit and .platform == "linux" and + .filename == "0xbuff-preceptor-0.0.1.tgz" and .integrity == $integrity and + .sha256 == $digest and .bytes == $size and + (.files | sort) == [ + "CHANGELOG.md", "COPYRIGHT.md", "LICENSE", "README.md", + "dist/index.d.ts", "dist/index.js", "package.json" + ] + ' evidence.json >/dev/null || fail archive-manifest + expected="$(archive_files | sed 's|^|package/|')" + actual="$(tar -tzf 0xbuff-preceptor-0.0.1.tgz | LC_ALL=C sort)" + [[ "$actual" == "$expected" ]] || fail archive-contents + # Require regular files only; no symlink, hardlink or directory entries. + tar -tvzf 0xbuff-preceptor-0.0.1.tgz | awk 'substr($0,1,1) != "-" { bad=1 } END { exit bad }' || fail archive-types + tar -xOzf 0xbuff-preceptor-0.0.1.tgz package/package.json | jq -e ' + .name == "@0xbuff/preceptor" and .version == "0.0.1" and + .private == false and .license == "Apache-2.0" and .type == "module" and + .publishConfig.access == "public" and + .publishConfig.registry == "https://registry.npmjs.org/" and + ([.dependencies, .optionalDependencies, .peerDependencies, + .bundledDependencies, .bundleDependencies] | all(. == null or length == 0)) + ' >/dev/null || fail package-metadata + notes="$(tar -xOzf 0xbuff-preceptor-0.0.1.tgz package/CHANGELOG.md)" + heading="$(grep -E '^## \[0\.0\.1\] - [0-9]{4}-[0-9]{2}-[0-9]{2}$' <<< "$notes")" || fail dated-notes + release_date="$(cut -d ' ' -f 4 <<< "$heading")" + [[ "$release_date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || fail dated-notes + [[ "$(date -u -d "$release_date" +%F)" == "$release_date" ]] || fail dated-notes + printf '%s\n' "Release preflight passed" + ;; + *) fail mode ;; +esac diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh new file mode 100644 index 0000000..e85c4d3 --- /dev/null +++ b/scripts/stage-release.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Invoked only by the separately authorized protected manual workflow. +set -euo pipefail +root="$(cd "$(dirname "$0")/.." && pwd)" +preflight="$root/scripts/release-preflight.sh" + +bash "$preflight" approval +workspace="$(mktemp -d "$RUNNER_TEMP/preceptor-release.XXXXXXXX")" +trap 'rm -rf "$workspace"' EXIT +archive_dir="$workspace/artifact" +main_sha="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" +gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" > "$workspace/run.json" +attempt="$(bash "$preflight" run "$main_sha" "$workspace/run.json")" +artifact_name="preceptor-candidate-ubuntu-latest-$GITHUB_SHA-$attempt" +gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" \ + --name "$artifact_name" --dir "$archive_dir" +bash "$preflight" archive "$archive_dir" "$attempt" "$artifact_name" + +cd "$archive_dir" +unset NODE_AUTH_TOKEN NPM_TOKEN +node --version +npm --version +# Keep both rechecks immediately before the single staging invocation. +[[ "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" == "$GITHUB_SHA" ]] +[[ -f 0xbuff-preceptor-0.0.1.tgz && ! -L 0xbuff-preceptor-0.0.1.tgz ]] +[[ "$(sha256sum 0xbuff-preceptor-0.0.1.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] +npm stage publish ./0xbuff-preceptor-0.0.1.tgz --access public --tag latest --ignore-scripts --registry https://registry.npmjs.org/ diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index 19eeeb2..dd03572 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -40,7 +40,12 @@ function run(args, cwd) { const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")); assert.equal(manifest.name, "@0xbuff/preceptor"); -assert.equal(manifest.private, true); +assert.equal(manifest.private, false); +assert.match(manifest.version, /^\d+\.\d+\.\d+$/); +assert.deepEqual(manifest.publishConfig, { + access: "public", + registry: "https://registry.npmjs.org/", +}); assert.equal(manifest.license, "Apache-2.0"); assert.equal(manifest.type, "module"); assert.deepEqual(manifest.exports, { @@ -348,6 +353,10 @@ try { path.join(consumerDir, "scoped-memory.ts"), fixture.replace('"../../src/index"', '"@0xbuff/preceptor"'), ); + 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]); const examples = ["model-free", "custom-model", "custom-memory", "custom-summary"]; const exampleFiles = []; for (const example of examples) { @@ -376,11 +385,13 @@ try { "--moduleResolution", "NodeNext", "consumer.ts", + "quick-start.ts", "scoped-memory.ts", ...exampleFiles, ], consumerDir, ); + console.log(run(["compiled/quick-start.js"], consumerDir)); console.log(run(["compiled/consumer.js"], consumerDir)); console.log(run(["--test", "integration.mjs"], consumerDir)); for (const example of examples) { diff --git a/tests/release-preflight.sh b/tests/release-preflight.sh new file mode 100644 index 0000000..4977597 --- /dev/null +++ b/tests/release-preflight.sh @@ -0,0 +1,248 @@ +#!/usr/bin/env bash +# Synthetic candidate only. Run with Bash, jq and GNU tar/coreutils on Ubuntu. +set -euo pipefail +if [[ "$(uname -s)" != Linux ]]; then + echo "Release preflight regression requires Ubuntu/Linux with GNU utilities" >&2 + exit 1 +fi +root="$(cd "$(dirname "$0")/.." && pwd)" +preflight="$root/scripts/release-preflight.sh" +workspace="$(mktemp -d)" +trap 'rm -rf "$workspace"' EXIT + +export GITHUB_REPOSITORY=0xbuffdev/preceptor GITHUB_REF=refs/heads/main +export GITHUB_SHA=0123456789abcdef0123456789abcdef01234567 +export APPROVED_SHA="$GITHUB_SHA" RUN_ID=42 APPROVED_RUN_ID=42 +artifact_name="preceptor-candidate-ubuntu-latest-$GITHUB_SHA-2" +mkdir -p "$workspace/package/dist" "$workspace/artifact" +cd "$workspace" +for file in CHANGELOG.md COPYRIGHT.md LICENSE README.md dist/index.d.ts dist/index.js package.json; do + printf 'synthetic\n' > "package/$file" +done +printf '# Changelog\n\n## [0.0.1] - 2026-11-29\n' > package/CHANGELOG.md +printf '%s\n' '{"name":"@0xbuff/preceptor","version":"0.0.1","private":false,"license":"Apache-2.0","type":"module","publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"}}' > package/package.json +cp package/package.json metadata-good.json +cp package/CHANGELOG.md notes-good.md + +jq -n --arg sha "$GITHUB_SHA" --arg repo "$GITHUB_REPOSITORY" '{ + id:42, head_sha:$sha, head_branch:"main", + head_repository:{full_name:$repo}, repository:{full_name:$repo}, + path:".github/workflows/ci.yml", event:"push", + status:"completed", conclusion:"success", run_attempt:2 +}' > run-good.json + +pack() { + tar -czf artifact/0xbuff-preceptor-0.0.1.tgz package/CHANGELOG.md package/COPYRIGHT.md \ + package/LICENSE package/README.md package/dist/index.d.ts package/dist/index.js \ + package/package.json "$@" + export APPROVED_DIGEST + APPROVED_DIGEST="$(sha256sum artifact/0xbuff-preceptor-0.0.1.tgz | cut -d ' ' -f 1)" + local integrity="sha512-$(openssl dgst -sha512 -binary artifact/0xbuff-preceptor-0.0.1.tgz | openssl base64 -A)" + jq -n --arg digest "$APPROVED_DIGEST" --argjson bytes "$(wc -c < artifact/0xbuff-preceptor-0.0.1.tgz)" \ + --arg commit "$GITHUB_SHA" --arg integrity "$integrity" '{ + name:"@0xbuff/preceptor", version:"0.0.1", sha256:$digest, bytes:$bytes, + commit:$commit, integrity:$integrity, platform:"linux", filename:"0xbuff-preceptor-0.0.1.tgz", + files: ["CHANGELOG.md","COPYRIGHT.md","LICENSE","README.md","dist/index.d.ts", + "dist/index.js","package.json"] + }' > artifact/evidence.json +} + +reject() { + local reason="$1" output + shift + if output="$("$@" 2>&1)"; then + printf 'Unexpected preflight acceptance: %s\n' "$reason" >&2 + exit 1 + fi + if ! grep -Fq "Release preflight: $reason" <<< "$output"; then + printf 'Wrong preflight rejection for %s: %s\n' "$reason" "$output" >&2 + exit 1 + fi +} + +pack +[[ "$(bash "$preflight" run "$GITHUB_SHA" run-good.json)" == 2 ]] +bash "$preflight" archive artifact 2 "$artifact_name" + +reject repository env GITHUB_REPOSITORY=other/preceptor bash "$preflight" run "$GITHUB_SHA" run-good.json +reject branch env GITHUB_REF=refs/heads/other bash "$preflight" run "$GITHUB_SHA" run-good.json +reject run-id env RUN_ID=0 bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-run-id env APPROVED_RUN_ID= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-sha env APPROVED_SHA= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject approved-digest env APPROVED_DIGEST= bash "$preflight" run "$GITHUB_SHA" run-good.json +reject stale-main bash "$preflight" run 1111111111111111111111111111111111111111 run-good.json +for mutation in \ + '.id=43' '.head_sha="wrong"' '.head_branch="other"' \ + '.head_repository.full_name="other/preceptor"' '.repository.full_name="other/preceptor"' \ + '.path=".github/workflows/other.yml"' '.event="pull_request"' \ + '.status="in_progress"' '.conclusion="failure"' '.conclusion=null' \ + '.run_attempt=0' '.run_attempt=1.5' '.run_attempt="2"'; do + jq "$mutation" run-good.json > run-bad.json + reject quality-run bash "$preflight" run "$GITHUB_SHA" run-bad.json +done +reject artifact-name bash "$preflight" archive artifact 3 "$artifact_name" +reject run-attempt bash "$preflight" archive artifact 0 "$artifact_name" +reject archive-digest env APPROVED_DIGEST=1111111111111111111111111111111111111111111111111111111111111111 \ + bash "$preflight" archive artifact 2 "$artifact_name" + +cp artifact/evidence.json manifest-good.json +for mutation in \ + '.bytes+=1' '.sha256="wrong"' '.name="other"' '.version="0.0.0"' \ + '.commit="wrong"' '.filename="wrong.tgz"' '.platform="win32"' '.integrity="wrong"' \ + '.files|=.[1:]' '.files += ["extra"]'; do + jq "$mutation" manifest-good.json > artifact/evidence.json + reject archive-manifest bash "$preflight" archive artifact 2 "$artifact_name" +done +cp manifest-good.json artifact/evidence.json +touch artifact/extra +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +rm artifact/extra +mv artifact/evidence.json manifest-moved.json +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +ln -s ../manifest-moved.json artifact/evidence.json +reject artifact-files bash "$preflight" archive artifact 2 "$artifact_name" +rm artifact/evidence.json +mv manifest-moved.json artifact/evidence.json + +# The manifest may claim the right files even when the tarball differs. +touch package/extra +pack package/extra +reject archive-contents bash "$preflight" archive artifact 2 "$artifact_name" +rm package/extra +pack package/README.md +reject archive-contents bash "$preflight" archive artifact 2 "$artifact_name" +rm package/README.md +ln -s LICENSE package/README.md +pack +reject archive-types bash "$preflight" archive artifact 2 "$artifact_name" +rm package/README.md +printf 'synthetic\n' > package/README.md + +for mutation in \ + '.name="other"' '.version="0.0.0"' '.private=true' \ + '.license="MIT"' '.type="commonjs"' '.dependencies={foo:"1.0.0"}' \ + '.publishConfig.access="restricted"' '.publishConfig.registry="https://example.invalid/"'; do + jq "$mutation" metadata-good.json > package/package.json + pack + reject package-metadata bash "$preflight" archive artifact 2 "$artifact_name" +done +cp metadata-good.json package/package.json + +for heading in '## [Unreleased]' '## [0.0.1] - 2026-02-30' '## [0.0.1] - 2026-11-99'; do + printf '%s\n' "$heading" > package/CHANGELOG.md + pack + reject dated-notes bash "$preflight" archive artifact 2 "$artifact_name" +done +cp notes-good.md package/CHANGELOG.md +pack +[[ "$(bash "$preflight" run "$GITHUB_SHA" run-good.json)" == 2 ]] +bash "$preflight" archive artifact 2 "$artifact_name" +printf '%s\n' 'Release preflight positive and negative matrix passed' + +# Exercise the exact staging entry point with an isolated environment and fake +# GitHub/npm commands. Only the stubs can see these synthetic candidate files. +mkdir "$workspace/bin" "$workspace/runner" +cat > "$workspace/bin/gh" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$*" == "api repos/0xbuffdev/preceptor/git/ref/heads/main --jq .object.sha" ]]; then + if grep -qx main "$TRACE"; then + echo final-main >> "$TRACE" + if [[ "$CASE" == stale-final ]]; then + echo 1111111111111111111111111111111111111111 + exit 0 + fi + if [[ "$CASE" == changed-final ]]; then + printf 'changed after validation\n' >> "$(cat "$TRACE.archive")/0xbuff-preceptor-0.0.1.tgz" + fi + else + echo main >> "$TRACE" + if [[ "$CASE" == stale-initial ]]; then + echo 1111111111111111111111111111111111111111 + exit 0 + fi + fi + echo "$GITHUB_SHA" +elif [[ "$*" == "api repos/0xbuffdev/preceptor/actions/runs/42" ]]; then + echo run >> "$TRACE" + if [[ "$CASE" == rejected-run ]]; then + jq '.conclusion="failure"' "$FIXTURE/run-good.json" + else + cat "$FIXTURE/run-good.json" + fi +elif [[ "$#" == 9 && "$1 $2 $3 $4 $5 $6 $7 $8" == \ + "run download 42 --repo 0xbuffdev/preceptor --name preceptor-candidate-ubuntu-latest-$GITHUB_SHA-2 --dir" ]]; then + echo download >> "$TRACE" + [[ "$CASE" != failed-download ]] || exit 7 + [[ "$9" == "$RUNNER_TEMP"/preceptor-release.*/artifact ]] + mkdir "$9" + cp "$FIXTURE/artifact/0xbuff-preceptor-0.0.1.tgz" "$FIXTURE/artifact/evidence.json" "$9/" + printf '%s\n' "$9" > "$TRACE.archive" + if [[ "$CASE" == rejected-archive ]]; then + jq '.bytes+=1' "$FIXTURE/artifact/evidence.json" > "$9/evidence.json" + fi +else + echo unexpected-gh >> "$TRACE" + exit 99 +fi +STUB +cat > "$workspace/bin/npm" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$#" == 1 && "$1" == --version ]]; then + echo npm-version >> "$TRACE" + echo synthetic-npm + exit 0 +fi +# Record any attempt before checking its arguments. +echo stage >> "$TRACE" +[[ "$*" == "stage publish ./0xbuff-preceptor-0.0.1.tgz --access public --tag latest --ignore-scripts --registry https://registry.npmjs.org/" ]] +[[ "$PWD" == "$(cat "$TRACE.archive")" ]] +[[ "$(sha256sum ./0xbuff-preceptor-0.0.1.tgz | cut -d ' ' -f 1)" == "$APPROVED_DIGEST" ]] +[[ -z "${NODE_AUTH_TOKEN+x}" && -z "${NPM_TOKEN+x}" ]] +STUB +cat > "$workspace/bin/node" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +[[ "$#" == 1 && "$1" == --version ]] +echo synthetic-node +STUB +chmod +x "$workspace/bin/gh" "$workspace/bin/npm" "$workspace/bin/node" + +orchestrate() { + local scenario="$1" expected="$2" trace="$workspace/trace-$1" status=0 + : > "$trace" + # Start with no inherited credentials (including OIDC). Restrict command + # lookup to the stub directory and standard Ubuntu system binaries. + env -i PATH="$workspace/bin:/usr/bin:/bin" \ + GITHUB_REPOSITORY="$GITHUB_REPOSITORY" GITHUB_REF="$GITHUB_REF" \ + GITHUB_SHA="$GITHUB_SHA" RUN_ID="$RUN_ID" APPROVED_RUN_ID="$APPROVED_RUN_ID" \ + APPROVED_SHA="$APPROVED_SHA" APPROVED_DIGEST="$APPROVED_DIGEST" \ + RUNNER_TEMP="$workspace/runner" FIXTURE="$workspace" TRACE="$trace" CASE="$scenario" \ + NODE_AUTH_TOKEN=synthetic NPM_TOKEN=synthetic \ + bash "$root/scripts/stage-release.sh" > "$trace.output" 2>&1 || status=$? + if [[ "$scenario" == approved ]]; then + [[ "$status" == 0 ]] || { cat "$trace.output" >&2; exit 1; } + else + [[ "$status" != 0 ]] || { echo "Unexpected staging success: $scenario" >&2; exit 1; } + if grep -qx stage "$trace"; then + echo "Rejected candidate reached staging: $scenario" >&2 + exit 1 + fi + fi + [[ "$(cat "$trace")" == "$expected" ]] || { + printf 'Unexpected orchestration trace for %s:\n' "$scenario" >&2 + cat "$trace" "$trace.output" >&2 + exit 1 + } + [[ -z "$(find "$workspace/runner" -mindepth 1 -maxdepth 1 -print -quit)" ]] +} + +orchestrate approved $'main\nrun\ndownload\nnpm-version\nfinal-main\nstage' +orchestrate stale-initial $'main\nrun' +orchestrate rejected-run $'main\nrun' +orchestrate failed-download $'main\nrun\ndownload' +orchestrate rejected-archive $'main\nrun\ndownload' +orchestrate stale-final $'main\nrun\ndownload\nnpm-version\nfinal-main' +orchestrate changed-final $'main\nrun\ndownload\nnpm-version\nfinal-main' +printf '%s\n' 'Protected staging orchestration passed with synthetic GitHub and npm stubs' diff --git a/tsdown.config.ts b/tsdown.config.ts index cfa1140..d737b17 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -5,6 +5,7 @@ export default defineConfig({ outDir: "dist", format: "esm", platform: "neutral", + external: ["node:crypto"], target: "es2022", fixedExtension: false, clean: true,