diff --git a/.cursorrules b/.cursorrules deleted file mode 100644 index 28fe7ec2..00000000 --- a/.cursorrules +++ /dev/null @@ -1,55 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -# Authoritative source: docs/practice/AI-CONVENTIONS.adoc - -# Read the repo deed (*_chora.deed in the repo root) FIRST: canonical file locations -# live in its (ply ...) canonical-locations clauses. - -# LICENSE -# All original code: MPL-2.0 (SPDX header required on every file). -# Copyright: Jonathan D.A. Jewell (hyperpolymath) - -# STATE FILES -# No .a2ml file may exist anywhere: the format is retired. State, metadata, -# (neurosym) and (playbook) are clauses of the repo deed (*_chora.deed); -# the journal is docs/status/ROADMAP.adoc. Never recreate them as files. - -# BANNED PATTERNS -# Idris2: believe_me, assert_total, assert_smaller, unsafePerformIO -# Haskell: unsafeCoerce, unsafePerformIO, undefined, error -# OCaml: Obj.magic, Obj.repr, Obj.obj -# Coq: Admitted -# Lean: sorry -# Rust: transmute (unless FFI with // SAFETY: comment) - -# JS RUNTIME — Bun first (standards/3-practice/LANGUAGE-POLICY.adoc sections 1.3-1.4) -# 1. Bun tier 1: package.json + bun.lock, run with bun / bunx -# 2. Deno tier 2: permitted; runs the same package.json scripts (deno task) -# 3. pnpm tier 3 -# 4. npm last resort; permitted, never preferred; keeps no lock -# One package.json carries every runtime's lock (bun.lock, deno.lock, -# pnpm-lock.yaml); `js-runtimes regen` writes all three (owner ruling -# 2026-10-14). TypeScript and ReScript are banned; they migrate to -# AffineScript. Use plain JavaScript where JS is needed. - -# BANNED LANGUAGES -# Go -> use Rust -# Python -> use Julia or Rust - -# CONTAINERS -# Runtime: Podman (never Docker) -# File: Containerfile (never Dockerfile) -# Base: cgr.dev/chainguard/wolfi-base:latest - -# ABI/FFI STANDARD -# ABI definitions: Idris2 with dependent types (src/interface/abi/) -# FFI implementation: Zig with C ABI (src/interface/ffi/) -# Generated C headers: src/interface/generated/ - -# BUILD SYSTEM -# Use just (Justfile) for all build, test, lint, and format tasks. - -# CODE STYLE -# Use descriptive variable names. -# Annotate and document all files. -# Add SPDX-License-Identifier headers to every source file. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index b3fade4b..b6db1555 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -44,7 +44,7 @@ which is precisely why the map is now generated rather than typed. **When reporting**: -Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: +Use the [bug report template](ISSUE_TEMPLATE/bug_report.yml) and include: - Clear, descriptive title - Environment details (OS, versions, toolchain) @@ -61,7 +61,7 @@ Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: **When suggesting**: -Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: +Use the [feature request template](ISSUE_TEMPLATE/feature_request.yml) and include: - Problem statement (what pain point does this solve?) - Proposed solution diff --git a/.github/workflows/dogfood-gate.yml b/.github/workflows/dogfood-gate.yml index 8a4b4bdf..e6500088 100644 --- a/.github/workflows/dogfood-gate.yml +++ b/.github/workflows/dogfood-gate.yml @@ -587,7 +587,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: hyperpolymath/hypatia - ref: be98f74ce93df200752f3798efa1305bfa3e0e10 + # Pinned to a Hypatia commit that contains hypatia#1062 (the PinSites miscompile + # fix, merged as 37b8d01). The earlier pin be98f74 lacks it. + ref: 51539abf3d2472b955da9b051a68c5971f6cfa22 path: _hypatia persist-credentials: false # OTP 28.x (28.1 to 28.5.0.8) crashes this step with SIGSEGV in @@ -608,7 +610,7 @@ jobs: _hypatia/_build ~/.hex ~/.mix - key: hypatia-oracle-${{ runner.os }}-otp27.3.4.19-elx1194-be98f74ce93df200752f3798efa1305bfa3e0e10 + key: hypatia-oracle-${{ runner.os }}-otp27.3.4.19-elx1194-51539abf3d2472b955da9b051a68c5971f6cfa22 - name: Compile the oracle working-directory: _hypatia run: mix local.hex --force && mix local.rebar --force && mix deps.get && mix compile diff --git a/.hypatia-ignore b/.hypatia-ignore index 41563b7a..b4c79dc0 100644 --- a/.hypatia-ignore +++ b/.hypatia-ignore @@ -13,18 +13,6 @@ # below carries a stated reason. Prefer fix-the-code or an inline directive # over an entry here; this file is for whole-file/directory exemptions. -# ─── build/docs-seed/ describes DOWNSTREAM repos, not this one ───────────── -# -# `build/docs-seed/` is the canonical template of documentation that gets -# copied into scaffolded repos. Its example paths (e.g. `src/middleware/…`, -# `src/main.rs`) describe a hypothetical generated project, so they -# legitimately do not resolve against this template's own tree. SD022 -# (stale `src//` reference) is therefore a structural false positive -# for everything under this directory — mirrors the built-in CHANGELOG.md -# and third_party/ carve-outs. Scaffolded repos inherit this file, so the -# exemption travels with the template. -structural_drift/SD022:build/docs-seed/ - # ─── Research-extension workflow findings ─────────────────────────────────────── # # RE001 is an advisory recommendation to add harden-runner whenever a workflow diff --git a/.machine_readable/coaptation/witness-map.ncl b/.machine_readable/coaptation/witness-map.ncl index 834875db..683a6d90 100644 --- a/.machine_readable/coaptation/witness-map.ncl +++ b/.machine_readable/coaptation/witness-map.ncl @@ -17,10 +17,12 @@ # 'present | 'absent | 'zero | 'nonzero | 'equals | 'contains | 'not_contains # 'equals/'contains/'not_contains take `arg`. A clause's witnesses ALL must hold. # -# Soundness-critical entries (the Must/Trust gates) are the ones to graduate to -# Idris2 `Witnesses` proofs in a later session (build-path step 6); today they are -# declarative. Keep this list HONEST: only assert a witness you can defend — the -# whole point is to make boundary-erosion visible, not to manufacture green. +# The Must/Trust gate over these entries is modelled in core/Coaptation.idr and +# proved sound against a content-bearing witness relation; the entries +# themselves stay declarative (a human judges which fact witnesses which clause). +# Keep this list HONEST: only assert a witness you can defend — the whole point +# is to make boundary-erosion visible, not to manufacture green. Every +# `descriptile` entry needs at least one witness: an empty list is refuted. { # --- MUST: presence obligations --- # must.machine-readable-dir has NO descriptile witness any more. It was @@ -34,9 +36,11 @@ note = "anchor.authority is read from the deed's (anchor) clause, so its presence IS the clause's presence", }, # must.six-directory-present has NO descriptile witness. Its probe needs - # descriptiles/PLAYBOOK + NEUROSYM and exactly one deed, and no fact here - # attests that: state and ecosystem are deed clauses since rsr-template-repo#209, - # and the anchor facts come from the deed. It is probe-deferred to the Hunt tier. + # exactly one deed carrying the (anchor), (neurosym) and (playbook) clauses. + # The neurosym. and playbook. facts are fields inside those clauses, and a + # missing field is not a missing clause, so their presence cannot attest the + # clauses without risking a false refutation. It is probe-deferred to the + # Hunt tier. # --- TRUST: deliberately NO descriptile witness. --- # Every Trust obligation here (no-secrets / no-private-keys / author-correct / diff --git a/.machine_readable/mint-verbatim.txt b/.machine_readable/mint-verbatim.txt index 53ac43a0..8e0438a9 100644 --- a/.machine_readable/mint-verbatim.txt +++ b/.machine_readable/mint-verbatim.txt @@ -27,7 +27,12 @@ scripts/strip-instruction-blocks.rs # names the marker it strips scripts/resolve-template-pin.sh # documents the template it resolves tests/e2e/template_instantiation_test.sh # token answer list; marker exemptions tests/e2e/use_template_mint_test.sh # mints a template copy: template literals +tests/e2e/chain_mint_test.sh # chain fixtures: parent names and paths tests/workflows/mint_cleanup_test.sh # instruction-block fixture tests/workflows/self_name_pass_test.sh # template-name fixtures tests/workflows/template_conformance_test.sh # template-slug fixtures +tests/workflows/mint_gates_test.sh # names an unanswered token, on purpose +tests/e2e/language_profiles_mint_test.sh # minted-tree fixtures; keeps archetype paths tests/workflows/resolve_template_pin_test.sh # template-slug fixtures +tests/ffi_strings_test.sh # FFI token fixture, filled in a scratch copy +tests/workflows/container_kyaml_test.sh # container token fixtures (template only) diff --git a/.machine_readable/policies/hypatia-rule-order.json b/.machine_readable/policies/hypatia-rule-order.json index d073f9ec..d6f53751 100644 --- a/.machine_readable/policies/hypatia-rule-order.json +++ b/.machine_readable/policies/hypatia-rule-order.json @@ -1 +1 @@ -{"SPDX-License-Identifier":"MPL-2.0","clashes":[{"id":"C1","resolution":"single producer; scripts/check-workflow-edges.sh fails on a dead edge","summary":"one scanner, two workflows"},{"id":"C2","resolution":"one pin per tool per repository; the verdict job names the producer's commit","summary":"one tool, two pins"},{"id":"C3","resolution":"panicbot stays unenrolled; the grid's own row is the authority","summary":"panicbot versus the direct panic-attack row"},{"id":"C4","resolution":"every fragment must end on a path boundary","summary":"substring fragments suppress more than they name"},{"id":"C5","resolution":"subsumed entries are refused","summary":"a broad entry makes narrower ones dead"},{"id":"C6","resolution":"the named path must exist in the tree","summary":"an exemption outlives the file it names"},{"id":"C7","resolution":"stated, not worked around; un-suppression is an upstream change","summary":"a repository cannot narrow a built-in default"},{"id":"C8","resolution":"producers own their gates; a failed fleet is orange rows, not a block","summary":"the reporter must not re-gate"}],"concerns":[{"id":"hypatia-execution","owner":".github/workflows/hypatia-scan.yml","rationale":"Two workflows built and ran the same scanner at the same pin (clash C1)."},{"id":"hypatia-gate","owner":".github/workflows/hypatia-scan.yml","rationale":"The producer owns its gate; the verdict grid is not a gate (clash C8)."},{"id":"panic-attack-gate","owner":".github/workflows/static-analysis-gate.yml","rationale":"Blocks on critical exactly once, in the workflow that runs it."},{"id":"pons-asinorum","owner":".github/workflows/static-analysis-gate.yml","rationale":"Advisory by design: pons classifies evidence, it does not prove."},{"id":"verdict-grid-render","owner":".github/workflows/fork-governance.yml","rationale":"The reporter collects evidence and never scans (clash C8)."},{"id":"verdict-grid-comment","owner":".github/workflows/verdict-grid-publish.yml","rationale":"Only the trusted default-branch workflow_run publisher may write the single bot-owned verdict comment; PR rendering remains read-only."},{"id":"fleet-report-backs","owner":".github/workflows/fork-governance.yml","rationale":"The fleet job is the only producer of .gitbot-fleet evidence."},{"id":"exemption-policy","owner":".hypatia-ignore","rationale":"One file, checked by scripts/check-hypatia-ignore.sh."}],"grid":{"commit":"f0b3cd4c464d33e1584f8528c17bce104555e256","library":"scripts/lib/verdict-grid.jq","library_sha256":"36e7aa69afbe8c488b1a313fd9bd0cf2bf6af45d3f34b80afd793f6b20582896","renderer":"scripts/verdict-grid.sh","renderer_sha256":"7c2cac9248fd249f607de827dc8dc9a3f6276bf9ca662be86aa435e9aeca48d7","repository":"metadatastician/standards","specification":"docs/VERDICT-GRID-SPEC.adoc"},"layer_owners":["hypatia","this-repository","the-gate","the-grid"],"layers":[{"description":"Python, Go, Makefile and Gemfile are refused by a dedicated clause; no exemption reaches it.","id":"rule-total-ban","overrides":"nothing: every other layer is unreachable for this rule","owner":"hypatia","rank":1,"repository_can_change":false,"scope":"cicd_rules/banned_language_file"},{"description":"Applied to every rule before any module-specific table.","id":"universal-excludes","overrides":"every layer below it, for the paths it names","owner":"hypatia","rank":2,"repository_can_change":false,"scope":"vendored and generated paths: .git/, node_modules/, _build/, deps/, target/, dist/, .hypatia-baseline.json"},{"description":"Training corpora and fixtures are provenance, not signal.","id":"builtin-defaults","overrides":"every layer below it; a repository cannot narrow it (clash C7)","owner":"hypatia","rank":3,"repository_can_change":false,"scope":"@training_corpus_paths keyed per module, plus benches/ for code_safety only"},{"description":"Scoped, reasoned exemptions. Fragments are substring matches, so each must end on a path boundary.","id":"repository-ignore","overrides":"nothing above it; it may only widen layer 3","owner":"this-repository","rank":4,"repository_can_change":true,"scope":".hypatia-ignore"},{"description":"Line- or file-scoped. The narrowest layer, and the one to use when only one line is affected.","id":"inline-directive","overrides":"layers 3 and 4, for the line that carries it","owner":"this-repository","rank":5,"repository_can_change":true,"scope":"# hypatia: allow / -- "},{"description":"Applied at gate time only. The verdict grid ignores it, so standing debt stays visible.","id":"baseline","overrides":"the gate's decision, never a scanner's output","owner":"the-gate","rank":6,"repository_can_change":true,"scope":".hypatia-baseline.json"},{"description":"Presentation and grading. It never suppresses a finding.","id":"grid-normalisation","overrides":"nothing; it may not change what a scanner reported","owner":"the-grid","rank":7,"repository_can_change":false,"scope":"severity words, suppressed:true, the row's colour"}],"observed_modules":[{"layer":4,"module":"structural_drift","rationale":"SD022 (stale src/ reference) fires on build/docs-seed/, which documents DOWNSTREAM repositories: the paths in it are not this tree's."},{"layer":4,"module":"research_extensions","rationale":"RE001/RE005/RE008 are advisory recommendations for workflows that deliberately hold a credential or render an annotation non-fatally; each exemption is file-scoped."},{"layer":4,"module":"workflow_audit","rationale":"wrong_sha_pin compares against a static May-2026 table; authoritative pin verification is actions.lock plus check-lock-sync.sh, which runs on every pull request."}],"scanner":{"commit":"be98f74ce93df200752f3798efa1305bfa3e0e10","repository":"hyperpolymath/hypatia","sources":["lib/hypatia/scanner_suppression.ex","lib/rules/"]},"schema":"hypatia-rule-order/1"} +{"SPDX-License-Identifier":"MPL-2.0","clashes":[{"id":"C1","resolution":"single producer; scripts/check-workflow-edges.sh fails on a dead edge","summary":"one scanner, two workflows"},{"id":"C2","resolution":"one pin per tool per repository; the verdict job names the producer's commit","summary":"one tool, two pins"},{"id":"C3","resolution":"panicbot stays unenrolled; the grid's own row is the authority","summary":"panicbot versus the direct panic-attack row"},{"id":"C4","resolution":"every fragment must end on a path boundary","summary":"substring fragments suppress more than they name"},{"id":"C5","resolution":"subsumed entries are refused","summary":"a broad entry makes narrower ones dead"},{"id":"C6","resolution":"the named path must exist in the tree","summary":"an exemption outlives the file it names"},{"id":"C7","resolution":"stated, not worked around; un-suppression is an upstream change","summary":"a repository cannot narrow a built-in default"},{"id":"C8","resolution":"producers own their gates; a failed fleet is orange rows, not a block","summary":"the reporter must not re-gate"}],"concerns":[{"id":"hypatia-execution","owner":".github/workflows/hypatia-scan.yml","rationale":"Two workflows built and ran the same scanner at the same pin (clash C1)."},{"id":"hypatia-gate","owner":".github/workflows/hypatia-scan.yml","rationale":"The producer owns its gate; the verdict grid is not a gate (clash C8)."},{"id":"panic-attack-gate","owner":".github/workflows/static-analysis-gate.yml","rationale":"Blocks on critical exactly once, in the workflow that runs it."},{"id":"pons-asinorum","owner":".github/workflows/static-analysis-gate.yml","rationale":"Advisory by design: pons classifies evidence, it does not prove."},{"id":"verdict-grid-render","owner":".github/workflows/fork-governance.yml","rationale":"The reporter collects evidence and never scans (clash C8)."},{"id":"verdict-grid-comment","owner":".github/workflows/verdict-grid-publish.yml","rationale":"Only the trusted default-branch workflow_run publisher may write the single bot-owned verdict comment; PR rendering remains read-only."},{"id":"fleet-report-backs","owner":".github/workflows/fork-governance.yml","rationale":"The fleet job is the only producer of .gitbot-fleet evidence."},{"id":"exemption-policy","owner":".hypatia-ignore","rationale":"One file, checked by scripts/check-hypatia-ignore.sh."}],"grid":{"commit":"f0b3cd4c464d33e1584f8528c17bce104555e256","library":"scripts/lib/verdict-grid.jq","library_sha256":"36e7aa69afbe8c488b1a313fd9bd0cf2bf6af45d3f34b80afd793f6b20582896","renderer":"scripts/verdict-grid.sh","renderer_sha256":"7c2cac9248fd249f607de827dc8dc9a3f6276bf9ca662be86aa435e9aeca48d7","repository":"metadatastician/standards","specification":"docs/VERDICT-GRID-SPEC.adoc"},"layer_owners":["hypatia","this-repository","the-gate","the-grid"],"layers":[{"description":"Python, Go, Makefile and Gemfile are refused by a dedicated clause; no exemption reaches it.","id":"rule-total-ban","overrides":"nothing: every other layer is unreachable for this rule","owner":"hypatia","rank":1,"repository_can_change":false,"scope":"cicd_rules/banned_language_file"},{"description":"Applied to every rule before any module-specific table.","id":"universal-excludes","overrides":"every layer below it, for the paths it names","owner":"hypatia","rank":2,"repository_can_change":false,"scope":"vendored and generated paths: .git/, node_modules/, _build/, deps/, target/, dist/, .hypatia-baseline.json"},{"description":"Training corpora and fixtures are provenance, not signal.","id":"builtin-defaults","overrides":"every layer below it; a repository cannot narrow it (clash C7)","owner":"hypatia","rank":3,"repository_can_change":false,"scope":"@training_corpus_paths keyed per module, plus benches/ for code_safety only"},{"description":"Scoped, reasoned exemptions. Fragments are substring matches, so each must end on a path boundary.","id":"repository-ignore","overrides":"nothing above it; it may only widen layer 3","owner":"this-repository","rank":4,"repository_can_change":true,"scope":".hypatia-ignore"},{"description":"Line- or file-scoped. The narrowest layer, and the one to use when only one line is affected.","id":"inline-directive","overrides":"layers 3 and 4, for the line that carries it","owner":"this-repository","rank":5,"repository_can_change":true,"scope":"# hypatia: allow / -- "},{"description":"Applied at gate time only. The verdict grid ignores it, so standing debt stays visible.","id":"baseline","overrides":"the gate's decision, never a scanner's output","owner":"the-gate","rank":6,"repository_can_change":true,"scope":".hypatia-baseline.json"},{"description":"Presentation and grading. It never suppresses a finding.","id":"grid-normalisation","overrides":"nothing; it may not change what a scanner reported","owner":"the-grid","rank":7,"repository_can_change":false,"scope":"severity words, suppressed:true, the row's colour"}],"observed_modules":[{"layer":4,"module":"research_extensions","rationale":"RE001/RE005/RE008 are advisory recommendations for workflows that deliberately hold a credential or render an annotation non-fatally; each exemption is file-scoped."},{"layer":4,"module":"workflow_audit","rationale":"wrong_sha_pin compares against a static May-2026 table; authoritative pin verification is actions.lock plus check-lock-sync.sh, which runs on every pull request."}],"scanner":{"commit":"be98f74ce93df200752f3798efa1305bfa3e0e10","repository":"hyperpolymath/hypatia","sources":["lib/hypatia/scanner_suppression.ex","lib/rules/"]},"schema":"hypatia-rule-order/1"} diff --git a/.windsurfrules b/.windsurfrules deleted file mode 100644 index 46b3580e..00000000 --- a/.windsurfrules +++ /dev/null @@ -1,52 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -# Authoritative source: docs/practice/AI-CONVENTIONS.adoc - -# STARTUP: Read the repo deed (*_chora.deed at the repo root) first, then docs/status/ROADMAP.adoc. - -# LICENSE -# All original code: MPL-2.0. -# Never AGPL-3.0. MPL-2.0 only as platform-required fallback. -# SPDX header required on every source file. -# Copyright: Jonathan D.A. Jewell (hyperpolymath) - -# STATE FILES -# No .a2ml file may exist anywhere: the format is retired. State, metadata, -# (neurosym) and (playbook) are clauses of the repo deed (*_chora.deed); -# the journal is docs/status/ROADMAP.adoc. Never recreate them as files. -# The repo deed and .machine_readable/ are the single source of truth. - -# BANNED PATTERNS -# Idris2: believe_me, assert_total, assert_smaller, unsafePerformIO -# Haskell: unsafeCoerce, unsafePerformIO, undefined, error -# OCaml: Obj.magic, Obj.repr, Obj.obj -# Coq: Admitted -# Lean: sorry -# Rust: transmute (unless FFI with // SAFETY: comment) - -# JS RUNTIME — Bun first (standards/3-practice/LANGUAGE-POLICY.adoc sections 1.3-1.4) -# 1. Bun tier 1: package.json + bun.lock, run with bun / bunx -# 2. Deno tier 2: permitted; runs the same package.json scripts (deno task) -# 3. pnpm tier 3 -# 4. npm last resort; permitted, never preferred; keeps no lock -# One package.json carries every runtime's lock (bun.lock, deno.lock, -# pnpm-lock.yaml); `js-runtimes regen` writes all three (owner ruling -# 2026-10-14). TypeScript and ReScript are banned; they migrate to -# AffineScript. Use plain JavaScript where JS is needed. - -# BANNED LANGUAGES -# Go -> Rust -# Python -> Julia or Rust - -# CONTAINERS -# Runtime: Podman (never Docker). -# File: Containerfile (never Dockerfile). -# Base: cgr.dev/chainguard/wolfi-base:latest or cgr.dev/chainguard/static:latest. - -# ABI/FFI -# ABI: Idris2 with dependent types (src/interface/abi/). -# FFI: Zig with C ABI (src/interface/ffi/). -# Headers: src/interface/generated/. - -# BUILD: Use just (justfile) for all tasks. -# STYLE: Descriptive names. Document all files. SPDX headers everywhere. diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index c4643bca..ba3fdbbd 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -384,7 +384,7 @@ https://semver.org/spec/v2.0.0.html[Semantic Versioning]. mise tools rather than each language's binaries; ** `check-mint-tokens.sh` treated "no build/just/repo-init.just" as proof of a minted tree — but that recipe is carried verbatim into every child, so no child - was ever recognised and an unfilled `{{PROJECT_NAME}}` passed (and + was ever recognised and an unfilled `bactrian` passed (and `survey-template-damage.sh` reported such repositories token-clean). The marker is `archetypes/`, which the mint deletes; ** `archetypes/*/prune.txt` dropped only `build/container/`, so a minted Julia diff --git a/LICENSE.adoc b/LICENSE.adoc new file mode 100644 index 00000000..af089d45 --- /dev/null +++ b/LICENSE.adoc @@ -0,0 +1,2 @@ +SPDX-License-Identifier: MPL-2.0 AND CC-BY-SA-4.0 +Code: MPL-2.0. Prose: CC-BY-SA-4.0. diff --git a/README.adoc b/README.adoc index 591af20b..b33cb5fb 100644 --- a/README.adoc +++ b/README.adoc @@ -141,7 +141,7 @@ maintainers can brief an AI with `just ai-warmup dev` / `just ai-warmup maintain == Governance badges The *K9 conformance* badge in the row at the top becomes live after -`just repo-init` replaces the `{{OWNER}}` and `{{REPO}}` placeholders in its URL +`just repo-init` replaces the `hyperpolymath` and `bactrian` placeholders in its URL and an eligible push to `main` publishes it. It is published by `.github/workflows/dogfood-gate.yml` to a generated *orphan* branch called `governance-badges`, and read back through the shields endpoint. diff --git a/bactrian_chora.deed b/bactrian_chora.deed index 73476e6b..5de57c81 100644 --- a/bactrian_chora.deed +++ b/bactrian_chora.deed @@ -225,7 +225,9 @@ (directory :id "automation-unit-forge" :ply 3 :path ".machine_readable/scripts/forge" :description "Internal automation logic for project forge.") (directory :id "automation-unit-lifecycle" :ply 3 :path ".machine_readable/scripts/lifecycle" :description "Internal automation logic for project lifecycle.") (directory :id "automation-unit-verification" :ply 3 :path ".machine_readable/scripts/verification" :description "Internal automation logic for project verification."))) - (directory :id "container-templates" :ply 1 :path "build/container" :version "1.0.0" :description "Container templates for the stapeln container ecosystem. This directory\nprovides Podman-Chainguard-stapeln templates that are customised via\n`just container-init` or `just repo-init` during project bootstrap.\n\nAll files use {{PLACEHOLDER}} tokens that are substituted with project-\nspecific values during initialisation." :purpose "Provide a complete, security-first container deployment story for any\nRSR-compliant repository. The templates cover the full lifecycle:\nbuild, sign, verify, deploy, monitor, and govern." :overview "The stapeln container ecosystem comprises six tools:\n\nselur — Container orchestration with zero-copy IPC. Reads compose.toml.\ncerro-torre — Verified container packaging (.ctp bundles), Ed25519 signing.\nsvalinn — Policy-driven edge gateway (auth, rate limits, CORS, trust).\nvordr — Runtime monitoring (health, crashes, resources, logs).\nrokur — Secrets management (runtime injection, no baked secrets).\nk9-svc — Nickel deployment components (Kennel/Yard/Hunt trust levels)." + (directory :id "container-templates" :ply 1 :path "build/container" :version "1.0.0" :description "Container templates for the stapeln container ecosystem. This directory\nprovides Podman-Chainguard-stapeln templates that are customised via\n`just container-init` or `just repo-init` during project bootstrap.\n\nAll files use {{PLACEHOLDER}} tokens that are substituted with project-\nspecific values during initialisation." + :purpose "Provide a complete, security-first container deployment story for any\nRSR-compliant repository. The templates cover the full lifecycle:\nbuild, sign, verify, deploy, monitor, and govern." + :overview "The stapeln container ecosystem comprises six tools:\n\nselur — Container orchestration with zero-copy IPC. Reads compose.toml.\ncerro-torre — Verified container packaging (.ctp bundles), Ed25519 signing.\nsvalinn — Policy-driven edge gateway (auth, rate limits, CORS, trust).\nvordr — Runtime monitoring (health, crashes, resources, logs).\nrokur — Secrets management (runtime injection, no baked secrets).\nk9-svc — Nickel deployment components (Kennel/Yard/Hunt trust levels)." :context ("https://stapeln.dev/ns/v1") (canonical-locations :build_pipeline "build/container/stapeln/ct-build.sh" :compose "build/container/stapeln/compose.toml" :compose_example "build/container/stapeln/compose.example.toml" :compose_portable "build/container/compose.yaml" :compose_portable_example "build/container/compose.example.yaml" :containerfile "build/container/Containerfile" :containerignore "build/container/.containerignore" :deployment "build/container/stapeln/deploy.k9.ncl" :entrypoint "build/container/entrypoint.sh" :gatekeeper "build/container/stapeln/.gatekeeper.yaml" :just_module "build/just/container.just" :manifest "build/container/stapeln/manifest.toml" :monitoring "build/container/stapeln/vordr.toml" :secrets_gate "build/container/stapeln/rokur.toml") :invariants ("Base images MUST be cgr.dev/chainguard/wolfi-base or cgr.dev/chainguard/static" "Container runtime is Podman — never Docker" "Containerfile — never Dockerfile" "All images run as non-root (appuser or project-specific user)" ".ctp bundles are signed with Ed25519 via cerro-torre" "Health endpoints (/health, /ready) must always be public (no auth)") diff --git a/build/container/Containerfile b/build/container/Containerfile index 144f4b04..d786a158 100644 --- a/build/container/Containerfile +++ b/build/container/Containerfile @@ -61,7 +61,7 @@ # chain integrity, e.g.: # FROM cgr.dev/chainguard/wolfi-base:latest@sha256: AS builder # (cerro-torre's .ctp signing in build/container/stapeln/ records the resolved digest.) -FROM cgr.dev/chainguard/wolfi-base:latest AS builder +FROM cgr.dev/chainguard/wolfi-base@sha256:1f6b749929164c3d9e7cad0289254f39b2ba51e1dddaeb0fa57532ea03f2db31 AS builder # TODO: Install your language toolchain RUN apk add --no-cache build-base @@ -79,7 +79,7 @@ COPY . . # Minimal production image. Only the compiled binary/release and runtime # dependencies are included. No compilers, no source code, no build tools. # -FROM cgr.dev/chainguard/wolfi-base:latest +FROM cgr.dev/chainguard/wolfi-base@sha256:1f6b749929164c3d9e7cad0289254f39b2ba51e1dddaeb0fa57532ea03f2db31 # OCI image labels (compatible with cerro-torre .ctp bundle metadata) LABEL org.opencontainers.image.title="bactrian" \ diff --git a/docs/architecture/REPOSITORY-MAP.adoc b/docs/architecture/REPOSITORY-MAP.adoc index 63dc2022..ad87bec5 100644 --- a/docs/architecture/REPOSITORY-MAP.adoc +++ b/docs/architecture/REPOSITORY-MAP.adoc @@ -21,6 +21,10 @@ predecessors did. | yes | code-hygiene gate allowlist; template scaffolds are seams, not debt +| `.claude/` +| optional +| Claude Code project state (checkpoints, history) — created by the tool itself + | `.clinerules` | yes | AI editor rules. Cline reads them from the project ROOT, so the copies formerly under .machine_readable/ai/ were inert (.cursorrules and .windsurfrules were retired 2026-10-26) @@ -29,10 +33,6 @@ predecessors did. | optional | CodeRabbit reads its config from the root only; pins Docstring Coverage to mode: warning (estate decision, not a vendor default). Optional: only the template and the repos whose rulesets require the CodeRabbit context carry it -| `.cursorrules` -| yes -| - - | `.devcontainer/` | optional | VS Code dev container spec; present only where the container capability is declared @@ -49,6 +49,10 @@ predecessors did. | yes | - +| `.gitbot-fleet/` +| yes +| fleet enrolment manifest + report-backs/ (empty in git; filled per run by the fork-governance fleet job). Read by the Hypatia verdict grid at this path and no other + | `.github/` | yes | community health + workflows (GitHub reads this path and no other) + versioned git hooks (.github/hooks/, wired via core.hooksPath) @@ -77,10 +81,6 @@ predecessors did. | yes | git reads .mailmap from the worktree root only -| `.windsurfrules` -| yes -| - - | `CHANGELOG.adoc` | yes | AsciiDoc is the estate-standard documentation format @@ -93,13 +93,13 @@ predecessors did. | yes | generated arrival pack; the generator, pre-commit and Claude Code all read it from the ROOT (do not hand-edit; edit the repo deed) -| `CONTRIBUTING.adoc` +| `CODE_OF_CONDUCT.adoc` | optional -| estate docs gate (standards scripts/check-docs-presence.sh) requires CONTRIBUTING at the ROOT; this is the copy it verifies +| community health file; GitHub accepts it at root, docs/ or .github/ -| `GEMINI.md` +| `CONTRIBUTING.adoc` | optional -| pointer to CLAUDE.md for repos without AGENTS.md yet +| estate docs gate (standards scripts/check-docs-presence.sh) requires CONTRIBUTING at the ROOT; this is the copy it verifies | `Justfile` | yes @@ -109,6 +109,10 @@ predecessors did. | optional | forge-facing copy of LICENSES/MPL-2.0.txt. Optional, not required: +| `LICENSE.adoc` +| yes +| the licence (MPL-2.0); renamed from LICENSE to the estate AsciiDoc format 2026-10-26 + | `LICENSES/` | yes | REUSE licence texts, dual-licence model (code MPL-2.0 / docs CC-BY-SA-4.0) @@ -216,7 +220,6 @@ your own repo - but do not read their emptiness as neglect here. | `docs/governance/planning/could/` | `docs/governance/planning/must/` | `docs/governance/planning/should/` -| `docs/reports/compliance/` | `docs/reports/maintenance/` | `docs/reports/performance/` | `docs/reports/quality/` diff --git a/docs/reports/compliance/RSR-TEMPLATE-DAMAGE-2026-10-30.adoc b/docs/reports/compliance/RSR-TEMPLATE-DAMAGE-2026-10-30.adoc index 5d07f2c8..808916f0 100644 --- a/docs/reports/compliance/RSR-TEMPLATE-DAMAGE-2026-10-30.adoc +++ b/docs/reports/compliance/RSR-TEMPLATE-DAMAGE-2026-10-30.adoc @@ -13,7 +13,7 @@ not performed — see <>. `JuliaPackageSpitter.jl` was reported as a broken Julia package: a `mise.toml` declaring Python, Node, Go, Rust, Java, Bun and Cargo for a Julia library and no Julia; a `Containerfile` built from two floating `:latest` stages and otherwise -consisting of TODO comments; `{{PROJECT_NAME}}` and a `tier` token sitting in +consisting of TODO comments; `bactrian` and a `tier` token sitting in committed files; an SPDX gate that passed without reading a single file; a `Justfile` whose `fmt`, `fmt-check` and `lint` recipes are `@echo` statements, so `just quality` printed "All quality checks passed!" having run only `Pkg.test()`. @@ -86,7 +86,7 @@ anywhere, in any repository, for two months. The placeholder gate excludes `Justfile` and `*.just` (they contain just's own `{{...}}` interpolation), and the mint's token list is a fixed set. Between the -two, `Justfile project := "{{PROJECT_NAME}}"`, `tier := "…"` (the `tier` brace token), +two, `Justfile project := "bactrian"`, `tier := "…"` (the `tier` brace token), `.envrc`, `.reuse/dep5`, `Containerfile`, `devcontainer.json` and `.devcontainer/Containerfile` kept their braces all the way into commits. @@ -320,7 +320,7 @@ four gates against the clone — the same code a minted repository will run, not grep. Reproducible: ---- -gh api -X GET search/code -f q='org:hyperpolymath "{{PROJECT_NAME}}"' \ +gh api -X GET search/code -f q='org:hyperpolymath "bactrian"' \ --jq '[.items[].repository.full_name] | unique | .[]' scripts/survey-template-damage.sh --tsv owner/name owner/name … ---- @@ -332,13 +332,13 @@ separate query, so the populations overlap and none is a subset of another): |=== | Query | Files | What it establishes -| `org:hyperpolymath "{{PROJECT_NAME}}"` | 1536 | Unfilled tokens are not one +| `org:hyperpolymath "bactrian"` | 1536 | Unfilled tokens are not one repository's accident. | `org:hyperpolymath filename:mise.toml python` | 175 | 175 `mise.toml` files mention Python. Python is banned estate-wide. | `org:hyperpolymath filename:Containerfile ":latest"` | 421 | 421 `Containerfile` files carry a floating tag somewhere. -| `org:hyperpolymath filename:Justfile "{{PROJECT_NAME}}"` | 33 | The mint's +| `org:hyperpolymath filename:Justfile "bactrian"` | 33 | The mint's own skipped-file class, in 33 `Justfile`s. |=== diff --git a/docs/status/PROOF-STATUS.adoc b/docs/status/PROOF-STATUS.adoc index 351c6344..d02b1f3b 100644 --- a/docs/status/PROOF-STATUS.adoc +++ b/docs/status/PROOF-STATUS.adoc @@ -1,101 +1,69 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell // Template: rsr-template-repo/docs/status/PROOF-STATUS.adoc -// Tracks proof completion. Requirements defined in PROOF-NEEDS.adoc -= Proof Status — BACTRIAN - -== Summary - -[cols="2,1,1,1,1,1", options="header"] -|=== -| Category | Total | Done | In Progress | Blocked | Remaining - -| ABI/FFI (ABI) | 5 | 0 | 0 | 0 | 5 -| Typing (TP) | 2 | 0 | 0 | 0 | 2 -| Invariant (INV) | 0 | 0 | 0 | 0 | 0 -| Security (SEC) | 0 | 0 | 0 | 0 | 0 -| Concurrency (CONC) | 0 | 0 | 0 | 0 | 0 -| Algorithm (ALG) | 0 | 0 | 0 | 0 | 0 -| Domain (DOM) | 0 | 0 | 0 | 0 | 0 -| *Total* | *7* | *0* | *0* | *0* | *7* -|=== - -*Overall*: 0% proven - -== Proofs Done - -// Format: -// | ID | Proof | Prover | File | Date | Verified By | -// | ABI-1 | Non-null pointer proofs | Idris2 | verification/proofs/idris2/ABI/Pointers.idr | 2026-XX-XX | idris2 --check | - -[cols="1,3,1,3,1,2", options="header"] -|=== -| ID | Proof | Prover | File | Date | Verified By - -| — | No proofs completed yet | — | — | — | — -|=== - -== Proofs In Progress - -[cols="1,3,1,2,1,2", options="header"] +// The per-claim proof record. Obligations are in PROOF-NEEDS.adoc. += Proof Status — {{PROJECT}} + +This is the repository's proof-status file in the sense of +`standards/3-practice/PROOF-POLICY.adoc` §8.5: one row per claim, with its status +token, its Proof Witness Grade (PWG) and its recheck legs. The estate census +(hyperpolymath/mathesis) reads this file. A row says only what a receipt or a +gate supports. + +A freshly minted repository has no claims, so the table is empty. That is the +honest state. Do not replace it with a percentage or an "overall" figure: +§8.4 forbids percentages, averages and single scores for proofs. + +== Vocabulary + +* *Status token* (§5): `proven`, `proven-with-postulates`, `tested-only`, + `argued`, `open`. +* *PWG* (§8), always written with its prefix, never as a bare "Grade": +** `PWG-3`: the Agda proof is `proven` under the canonical §2.1 invocation, + `agda --safe --without-K --cubical-compatible`; +** `PWG-2i`: one recheck leg also counts (Rocq or Lean); +** `PWG-2ii`: both legs count; +** `PWG-1`: every counted witness has a current receipt for the exact commit; +** `ungraded`: a theory theorem below `PWG-3`; +** `n/a`: not a theory theorem (a test, a refusal fixture, an assumption, or an + engineering proof in Idris2, SPARK, Creusot or Verus). §8.1 puts these off the + ladder. +* *Recheck legs* (§2): `transported`, `re-proved`, `waived` or `unavailable`, + each with its §2.2 correspondence state, for example `BRIDGE-PENDING` or + `RECONCILED`. A leg counts towards a grade only when it is `RECONCILED`. + +A grade is derived from receipts, not asserted (§8.4). Name the receipt in the +table, and a claim that has none stays `ungraded`. `PWG-3` is not a discharge: +a theorem at `PWG-3` still owes both legs. + +The template's own sample proofs under `verification/proofs/` are boilerplate. +They are never rows here: replace them with this repository's proofs, or delete +them. + +== Claims + +[cols="1,3,1,1,1,1,2",options="header"] |=== -| ID | Proof | Prover | Assignee | Started | Blocker +| ID | Claim (and the artefact that proves or tests it) | Token | PWG | Rocq leg | Lean leg | Receipt -| — | — | — | — | — | — +| — | No claims yet | — | — | — | — | — |=== -== Proofs Blocked +== Trust boundary -[cols="1,3,2,3", options="header"] -|=== -| ID | Proof | Blocked By | Notes +List every axiom, `ASSUMED` boundary specification (third-party code, PROOF-POLICY +§1.1) and recorded exception (§4) here, with the claims that rest on it. Write +"none" when there are none, so an empty section cannot read as an oversight. -| — | — | — | — -|=== +none -== Proofs Remaining - -[cols="1,3,1,1,1,1", options="header"] -|=== -| ID | Proof | Category | Prover | Priority | Est. Effort - -| ABI-1 | Non-null pointer proofs | ABI | Idris2 | P1 | 2h -| ABI-2 | Memory layout correctness | ABI | Idris2 | P1 | 4h -| ABI-3 | Platform type size proofs | ABI | Idris2 | P1 | 2h -| ABI-4 | FFI function return type proofs | ABI | Idris2 | P1 | 2h -| ABI-5 | C ABI compliance | ABI | Idris2 | P1 | 4h -| TP-1 | Core data type well-formedness | TP | Idris2 | P1 | 4h -| TP-2 | Public API type safety | TP | Lean4 | P2 | 4h -|=== - -== Verification Commands +== Verification commands [source,bash] ---- -# Check all Idris2 proofs -just proof-check-idris2 - -# Check all Lean4 proofs -just proof-check-lean4 - -# Check all Agda proofs -just proof-check-agda - -# Check all Coq proofs -just proof-check-coq - -# Run all proof checks -just proof-check-all - -# Scan for dangerous patterns -panic-attack assail --proofs-only +just proof-check-agda # Agda: agda --safe --without-K --cubical-compatible +just proof-check-coq # Rocq recheck legs +just proof-check-lean4 # Lean recheck legs (core only, no Mathlib) +just proof-check-idris2 # Idris2 engineering proofs +just proof-check-all # every prover; fatal if a toolchain is absent ---- - -== Changelog - -[cols="1,3,1", options="header"] -|=== -| Date | Change | By - -| 2026-04-04 | Initial proof status tracking | Template -|=== diff --git a/docs/troubleshooting.adoc b/docs/troubleshooting.adoc index 2e8a3ab4..8c1d1d4d 100644 --- a/docs/troubleshooting.adoc +++ b/docs/troubleshooting.adoc @@ -48,7 +48,7 @@ just log-tail # last N lines of logs and the symptom in plain English. . Linked from the issue: the relevant ADR(s) and any related issues. . For *security*-relevant findings, see - link:./../SECURITY.md[SECURITY.md] — do **not** file public issues. + link:./../.github/SECURITY.md[SECURITY.md] — do **not** file public issues. == Where to look for more help diff --git a/scripts/check-mint-tokens.sh b/scripts/check-mint-tokens.sh index d45489fd..4e16c792 100644 --- a/scripts/check-mint-tokens.sh +++ b/scripts/check-mint-tokens.sh @@ -10,11 +10,11 @@ # A token with no answer is not a reminder, it is a defect that ships. Measured # downstream: a minted Julia repo carried # -# Justfile project := "{{PROJECT_NAME}}" tier := "{{tier}}" -# .envrc PROJECT_NAME="{{PROJECT_NAME}}" RSR_TIER="infrastructure" -# .reuse/dep5 Upstream-Name: {{PROJECT_NAME}} -# Containerfile # Copyright (c) ... ({{OWNER}}) -# devcontainer.json, .devcontainer/Containerfile {{PROJECT_NAME}} +# Justfile project := "bactrian" tier := "{{tier}}" +# .envrc PROJECT_NAME="bactrian" RSR_TIER="infrastructure" +# .reuse/dep5 Upstream-Name: bactrian +# Containerfile # Copyright (c) ... (hyperpolymath) +# devcontainer.json, .devcontainer/Containerfile bactrian # # because the mint had no answer for those tokens IN THOSE FILES, and nothing # checked. The repo's own `check-no-placeholders.sh` would have caught it — in @@ -73,7 +73,7 @@ if [ ! -d "$ROOT/archetypes" ]; then # (.machine_readable/mint-verbatim.txt) and the child's Justfile imports it, # so testing for the recipe never fired: children looked like the template, # every token they carried counted as "the generator will answer this", and - # an unfilled {{PROJECT_NAME}} passed — in the gate and in + # an unfilled bactrian passed — in the gate and in # survey-template-damage.sh, which reads it. # # archetypes/ is the marker because the mint deletes it (repo-init's prune @@ -107,7 +107,7 @@ ANSWERS="" # command substitutions (tests, the mint's pre-write gate), where a PID-named # temp file is shared by the outer and inner shell often enough to hand one of # them a half-written list — measured as an intermittent "the mint cannot -# answer {{PROJECT_NAME}}" on a tree where it demonstrably can. +# answer bactrian" on a tree where it demonstrably can. if [ "$MINTED_TREE" -eq 1 ]; then info "no archetypes/ — minted tree; no token has an answer here" else diff --git a/scripts/survey-template-damage.sh b/scripts/survey-template-damage.sh index 408298d3..dfb55e2f 100755 --- a/scripts/survey-template-damage.sh +++ b/scripts/survey-template-damage.sh @@ -17,7 +17,7 @@ # # Usage: # scripts/survey-template-damage.sh hyperpolymath/A.jl hyperpolymath/B.jl … -# scripts/survey-template-damage.sh --from-search 'org:hyperpolymath filename:Justfile "{{PROJECT_NAME}}"' +# scripts/survey-template-damage.sh --from-search 'org:hyperpolymath filename:Justfile "bactrian"' # options: --keep (leave the clones), --tsv (machine-readable table only) # # Exit: 0 survey completed (whatever it found); 1 could not complete; 2 usage. diff --git a/src/interface/Abi/Foreign.idr b/src/interface/Abi/Foreign.idr index cd537d49..fbf5f9de 100644 --- a/src/interface/Abi/Foreign.idr +++ b/src/interface/Abi/Foreign.idr @@ -2,8 +2,8 @@ -- Copyright (c) Jonathan D.A. Jewell ||| Foreign Function Interface Bridge ||| -||| Raw FFI calls into lib{{project}} (src/interface/ffi/src/main.zig) and their -||| safe wrappers. Every `%foreign "C:,lib{{project}}"` below names a +||| Raw FFI calls into libbactrian (src/interface/ffi/src/main.zig) and their +||| safe wrappers. Every `%foreign "C:,libbactrian"` below names a ||| symbol that main.zig `export fn`s; tests/aspect_tests.sh (Aspect 3) fails ||| if one does not. The symbols and the Result codes follow main.zig; the ||| template once bound rsr_* in librsr, which nothing exported. @@ -20,15 +20,15 @@ import Abi.Layout -------------------------------------------------------------------------------- ||| Raw FFI call to initialize the library (Zig: returns ?*Handle, null on failure) -%foreign "C:{{project}}_init,lib{{project}}" +%foreign "C:bactrian_init,libbactrian" prim__init : PrimIO Bits64 ||| Raw FFI call to free library resources (Zig: accepts null) -%foreign "C:{{project}}_free,lib{{project}}" +%foreign "C:bactrian_free,libbactrian" prim__free : Bits64 -> PrimIO () ||| Raw FFI call: 1 if the handle is initialised, else 0 -%foreign "C:{{project}}_is_initialized,lib{{project}}" +%foreign "C:bactrian_is_initialized,libbactrian" prim__isInitialized : Bits64 -> PrimIO Bits32 ||| Safe wrapper for initialization @@ -60,7 +60,7 @@ isInitialized h = do ||| of the return register is unspecified for an `int` return). It is ||| `Bits32`, not `Int32`, because RefC in Idris2 0.7.0 cannot generate code ||| for an `Int32` foreign return; see Abi.Types.resultCode. -%foreign "C:{{project}}_process,lib{{project}}" +%foreign "C:bactrian_process,libbactrian" prim__process : Bits64 -> Bits32 -> PrimIO Bits32 ||| Safe wrapper. Right () on code 0; Left on any other known code; an @@ -79,11 +79,11 @@ process h input = do -------------------------------------------------------------------------------- ||| Get the last error message, if any (Zig: thread-local, no handle argument) -%foreign "C:{{project}}_last_error,lib{{project}}" +%foreign "C:bactrian_last_error,libbactrian" prim__lastError : PrimIO (Ptr String) ||| Library version string (static storage on the Zig side) -%foreign "C:{{project}}_version,lib{{project}}" +%foreign "C:bactrian_version,libbactrian" prim__version : PrimIO (Ptr String) ||| Detailed error string helper, one line per Result constructor @@ -109,4 +109,4 @@ errorDescription NullPointer = "Null pointer" ||| and is injective (Abi.Types.resultCodeInjective). public export abiSafetyGuarantees : String -abiSafetyGuarantees = "{{project}} ABI: 4 stated safety properties for FFI integration" +abiSafetyGuarantees = "bactrian ABI: 4 stated safety properties for FFI integration" diff --git a/src/interface/Abi/Types.idr b/src/interface/Abi/Types.idr index 4c8c349f..9ec1a391 100644 --- a/src/interface/Abi/Types.idr +++ b/src/interface/Abi/Types.idr @@ -3,7 +3,7 @@ ||| ABI Type Definitions ||| ||| This module defines the Application Binary Interface (ABI) for -||| lib{{project}}. It is the Idris2 side of the seam whose Zig side is +||| libbactrian. It is the Idris2 side of the seam whose Zig side is ||| src/interface/ffi/src/main.zig; tests/aspect_tests.sh (Aspect 3) checks ||| that the two name the same symbols, and `Result` below carries the same ||| integer codes as the Zig `Result` enum, in the same order. diff --git a/src/interface/ffi/src/main.zig b/src/interface/ffi/src/main.zig index c9fc13dc..caac0226 100644 --- a/src/interface/ffi/src/main.zig +++ b/src/interface/ffi/src/main.zig @@ -25,6 +25,16 @@ fn clearError() void { last_error = null; } +/// Duplicate a byte slice as a NUL-terminated buffer across Zig 0.15/0.16/0.17 +/// (`Allocator.dupeZ` was removed in Zig 0.17). +/// The caller owns the returned slice and must free it with `allocator`. +/// Propagates allocation failure. +fn dupeZ(allocator: std.mem.Allocator, bytes: []const u8) ![:0]u8 { + const buf = try allocator.allocSentinel(u8, bytes.len, 0); + @memcpy(buf[0..bytes.len], bytes); + return buf; +} + //============================================================================== // Core Types (must match src/abi/Types.idr) //============================================================================== @@ -110,7 +120,9 @@ export fn bactrian_process(handle: ?*Handle, input: u32) Result { //============================================================================== /// Get a string result (example) -/// Caller must free the returned string +/// Return a NUL-terminated "Example result" owned by the caller; free it with +/// `bactrian_free_string`. Return null and set the thread-local error for a +/// null or uninitialized handle, or allocation failure. Clear the error on success. export fn bactrian_get_string(handle: ?*Handle) ?[*:0]const u8 { const h = handle orelse { setError("Null handle"); @@ -123,7 +135,7 @@ export fn bactrian_get_string(handle: ?*Handle) ?[*:0]const u8 { } // Example: allocate and return a string - const result = h.allocator.dupeZ(u8, "Example result") catch { + const result = dupeZ(h.allocator, "Example result") catch { setError("Failed to allocate string"); return null; }; @@ -180,14 +192,15 @@ export fn bactrian_process_array( // Error Handling //============================================================================== -/// Get the last error message -/// Returns null if no error +/// Get the last error message. +/// Return an allocated NUL-terminated copy of the current thread's error, or +/// null if no error is set or allocation fails. Leave the stored error unchanged. +/// Caller must free a non-null returned string with `bactrian_free_string`. export fn bactrian_last_error() ?[*:0]const u8 { const err = last_error orelse return null; - // Return C string (static storage, no need to free) const allocator = std.heap.c_allocator; - const c_str = allocator.dupeZ(u8, err) catch return null; + const c_str = dupeZ(allocator, err) catch return null; return c_str.ptr; } @@ -258,6 +271,10 @@ test "lifecycle" { defer bactrian_free(handle); try std.testing.expect(bactrian_is_initialized(handle) == 1); + + const str = bactrian_get_string(handle) orelse return error.StringFailed; + defer bactrian_free_string(str); + try std.testing.expectEqualStrings("Example result", std.mem.span(str)); } test "error handling" { @@ -265,6 +282,7 @@ test "error handling" { try std.testing.expectEqual(Result.null_pointer, result); const err = bactrian_last_error(); + defer bactrian_free_string(err); try std.testing.expect(err != null); } diff --git a/tests/aspect_tests.sh b/tests/aspect_tests.sh index 813aad99..a0dade26 100755 --- a/tests/aspect_tests.sh +++ b/tests/aspect_tests.sh @@ -101,7 +101,7 @@ fi # Aspect 3: ABI/FFI contract. The Idris2 side and the Zig side name the same # symbols, the same library and the same Result codes. Text-level: it reads # the two sources, not a built library, and checks names and integer codes, -# not types. Symbol names may still carry the {{project}} token before +# not types. Symbol names may still carry the bactrian token before # `just repo-init`; both sides carry it alike, so they compare equal. # ═══════════════════════════════════════════════════════════════════════ bold "Aspect 3: ABI/FFI contract"