diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index d0f0f36..3b36ea5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -35,7 +35,7 @@ body: id: version attributes: label: Version or commit - placeholder: v0.4.0, or the short commit SHA + placeholder: v0.6.0, or the short commit SHA validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 2ed8023..13c7204 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -4,7 +4,7 @@ ## Checklist -- [ ] `npm run ci` passes locally (validate, coverage, lint, type-check, test, build, examples). +- [ ] `npm run ci` passes locally (validate, coverage, lint, type-check, test, build, examples, eval self-check). - [ ] New or changed behaviour has a test in `test/`. - [ ] If the ontology changed: `npm run validate` reports 0 errors, and `ontology/periodic-table.schema.json` still describes the shape. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca6116f..1dc359c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,11 +16,11 @@ jobs: timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v5 with: - node-version: 22 + node-version-file: .nvmrc cache: npm - run: npm ci @@ -57,11 +57,11 @@ jobs: timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v5 with: - node-version: 22 + node-version-file: .nvmrc cache: npm - run: npm ci diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6031453 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,95 @@ +# Changelog + +All notable changes to this project are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- A runtime package root entry point (`src/index.ts`) exporting the ontology + loader, schema validator, composition prompts, and core types. The root used + to resolve to `atoms/core.ts`, which is types only and compiled to `export {}`, + so importing the package by name yielded an empty namespace. +- `engines.node` (`>=20.6.0`) and `.nvmrc`, which CI now reads, so the supported + Node version is declared once instead of repeated in both workflow jobs. +- A packaging test that fails when an entry point resolves outside `files`, and a + public-API test that asserts the root entry actually exports runtime symbols. + +### Changed + +- `npm run ci` now runs the evaluation self-check, matching the GitHub Actions + workflow and the README's "everything CI runs" claim. +- CI uses `actions/checkout@v5` and `actions/setup-node@v5`, which run on the + supported action runtime instead of the deprecated Node 20 one. + +## [0.6.0] - 2026-10-22 + +### Added + +- Behaviour tests for all 35 object atoms. One data-driven suite checks metadata + against the ontology, declares every `PropertyDef` the factory writes, fills + required fields, applies documented defaults, and round-trips optional inputs. +- `test/atom-test-coverage.test.ts`, a guard that fails when an atom module is + imported by no test. It is a floor, not proof of assertion quality, but it + catches entire untested families. +- `test/project.test.ts`, which fails when package, lockfile, ontology, and + citation versions drift; when the atom count in the README badge, package + description, or citation disagrees with the ontology; when the shipped version + has no dated CHANGELOG entry; or when a test file is missing from the README + inventory. + +### Changed + +- Bumped the version to 0.6.0 in `package.json`, `package-lock.json`, + `ontology/periodic-table.json`, and `CITATION.cff`. +- README test inventory now lists every test file, and the status section reports + that all six families have behaviour tests. +- The published package now includes `docs/`, `CHANGELOG.md`, and `CITATION.cff`, + so the documentation links in the README resolve for npm consumers. +- Corrected `docs/CONTRIBUTING.md`, which claimed `npm run coverage` would show a + drop when an atom has no test. Coverage measures implementations; the new + import guard measures test presence. + +### Fixed + +- The ontology declared version 0.4.0 while the package and citation declared + 0.5.0. A consistency test now prevents the drift. +- `createSubscription` declared `cancelAt` in `SubscriptionProperties` but did + not accept or set it. It now does. +- `createMessage` declared `readBy` in `MessageProperties` but did not accept or + set it. It now does. +- The abstract in `CITATION.cff` still claimed composition was "more reliable and + token-efficient", contradicting the withdrawn 39% result. The claim is gone. + +## [0.5.0] - 2026-10-16 + +### Added + +- Test coverage for all 8 intelligence atoms (Search, Summarize, Classify, Recommend, Analyze, Extract, Generate, Prompt) +- Test coverage for all 25 properties atoms (Status, Text, Number, Date, DateTime, Currency, Enum, Boolean, ID, Owner, Priority, CreatedAt, UpdatedAt, Score, Percent, Duration, Count, JSON, Address, AI, StartDate, EndDate, Email, Phone, URL) +- Test coverage for 11 previously untested actions atoms (Create/Update/Delete/View, Notify/Message/Assign, Search/Filter/Sort/Export) +- Test coverage for 4 previously untested interfaces atoms (Calendar, Chart, Detail, Form) +- Test coverage for 3 previously untested rules atoms (Audit, Permission, Policy) +- `test:coverage` npm script for running tests with coverage reporting + +### Changed + +- Updated README Roadmap to reflect current 100% reference implementation coverage +- Bumped version to 0.5.0 in package.json and CITATION.cff + +### Fixed + +- Corrected the stale Roadmap section in README that contradicted the Status section + +## [0.4.0] - 2026-08-21 + +### Added + +- 115 atoms across 6 families (ontology established in 0.2.0) +- Composition system prompt and plan schema +- Evaluation harness with baseline vs composition comparison +- Reference implementations for 90 of 115 atoms (25 missing: 14 actions, 9 interfaces, 2 rules) +- CI pipeline with validation, coverage, linting, and type-checking diff --git a/CITATION.cff b/CITATION.cff index d9abe28..7340b46 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,8 +2,8 @@ cff-version: 1.2.0 message: "If you use this work in research, please cite it as below." title: "Software Periodic Table: A Finite Ontology of Recurring Application Elements for Compositional Code Generation" type: software -version: 0.4.0 -date-released: 2026-08-21 +version: 0.6.0 +date-released: 2026-10-22 license: MIT authors: @@ -19,4 +19,4 @@ keywords: - periodic-table - reusability -abstract: "A curated ontology of 115 recurring software elements across six families (Objects, Properties, Actions, Interfaces, Intelligence, Rules), with typed reference implementations and a composition framework for LLM-based coding agents. The core thesis is that most application software can be expressed as compositions of a finite set of curated atoms, and that composition from such a library is more reliable and token-efficient than regenerating equivalent patterns on every task." +abstract: "A curated ontology of 115 recurring software elements across six families (Objects, Properties, Actions, Interfaces, Intelligence, Rules), with typed reference implementations, behaviour tests, and a composition framework for LLM-based coding agents. The core thesis is that most application software can be expressed as compositions of a finite set of curated atoms. The repository ships an evaluation harness for testing that thesis against a generation baseline; it scores ground-truth recall and acceptance criteria, and makes no measured claim that composition outperforms generation." diff --git a/README.md b/README.md index ec9b663..67340cb 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ software-periodic-table/ │ ├── intelligence/ # Intelligence atoms: model-backed primitives │ └── rules/ # Rule atoms: permission.ts, trigger.ts, action.ts ├── src/ # Shared infrastructure +│ ├── index.ts # Package root: loader, schema validator, prompts, types │ ├── ontology.ts # Loader, name/symbol indexes, family ranges │ └── jsonschema.ts # Dependency-free JSON Schema subset validator ├── composer/ # Composition layer & agent prompts @@ -111,6 +112,9 @@ software-periodic-table/ ## Quick Start +Node 20.6 or newer is required. `.nvmrc` pins the version CI uses, so +`nvm use` selects a matching runtime. + ```bash # Install dependencies npm ci @@ -126,22 +130,43 @@ npm run check npm run lint npm test +# Tests with coverage reporting +npm run test:coverage + # Run the composition examples npm run example # Task + Kanban board npm run example:crm # CRM contact management npm run example:product # Product catalog + AI Search/Recommend npm run example:invoice # Invoice dashboard + Filter/Export/Chart -# Everything CI runs, in one command +# Everything CI runs, in one command (includes the evaluation self-check) npm run ci -# Evaluation harness self-check (no API key needed) +# Evaluation harness self-check on its own (no API key needed) npm run eval # Real baseline vs composition (requires OPENAI_API_KEY or LLM_API_KEY) OPENAI_API_KEY=sk-... npm run eval ``` +## Package Entry Points + +Installing the package exposes the shared infrastructure at the root and each +atom at its own subpath: + +```ts +import { loadOntology, validateSchema } from 'software-periodic-table'; +import { COMPOSITION_SYSTEM_PROMPT } from 'software-periodic-table/composer'; +import { createTask, TaskMeta } from 'software-periodic-table/atoms/objects/task.js'; + +const ontology = loadOntology(); +const errors = validateSchema(ontology, { type: 'object' }); +``` + +The root entry point is the ontology loader, schema validator, composition +prompts, and the shared types from `atoms/core.ts`. Prefer the per-atom subpaths +when you only need one atom. + ## Tests The ontology is a data artifact that agents consume, so its invariants are @@ -156,7 +181,21 @@ enforced by tests rather than by convention: v0.5.0 (the `notes` characters in `planOverlap`, the acceptance fall-through, the cross-family name collision) plus consistency between each scenario's acceptance criteria and its ground truth. -- `test/atoms.test.ts` — behaviour of the atom implementations. +- `test/atoms.test.ts` — behaviour of the core atom implementations. +- `test/atoms-new.test.ts` — behaviour of the atoms added alongside the lifecycle, + scheduling, data, board, grid, list, map, timeline, tree, card, and schedule work. +- `test/atoms-untested.test.ts` — behaviour of the atoms that previously had no + tests, across the intelligence, properties, actions, interfaces, and rules + families. +- `test/objects.test.ts` — all 35 object atoms: metadata matches the ontology, + every declared property is materialized, required fields and defaults hold, and + optional inputs round-trip. +- `test/atom-test-coverage.test.ts` — fails if an atom module is imported by no + test, so a future family cannot ship untested. +- `test/project.test.ts` — fails when versions, atom counts, the CHANGELOG entry, + or the README test inventory drift from the shipped code. +- `test/public-api.test.ts` — the loader, schema entry point, prompt builder, and + an atom are reachable through the paths a package consumer uses. Run with `npm test`. No test framework dependency; `node:test` and `tsx` only. @@ -190,12 +229,14 @@ See `docs/AGENT_USAGE.md` for a detailed walkthrough of both patterns, including ## Status -The ontology (115 elements) is stable. **Every element has a tested reference +The ontology (115 elements) is stable. **Every element has a reference implementation — 115 of 115 (100%)**, across all six families (run `npm run -coverage` for the live report). `test/ontology.test.ts` fails if any atom loses its -implementation, because a symbol with no implementation is a hole in the claim that -the table is composable end to end. The composition system prompt, examples, and -evaluation harness are functional and unit-tested. +coverage` for the live report). Behaviour tests cover all six families, including +all 35 object atoms; `test/atom-test-coverage.test.ts` fails if any atom module is +imported by no test. `test/ontology.test.ts` fails if any atom loses its +implementation, because a symbol with no implementation is a hole in the claim +that the table is composable end to end. The composition system prompt, examples, +and evaluation harness are functional and unit-tested. **No empirical claim is made yet.** An earlier version of this README reported a 39% token saving from composition. That figure is withdrawn and the metric is @@ -238,11 +279,9 @@ against the feature requests, and collect empirical results. ## Roadmap -- **Near term:** Expand reference implementations to cover all 115 elements. Remaining families: Actions (13 missing), Interfaces (7 missing), Rules (1 missing). -- **Medium term:** Run a corrected LLM evaluation, publish the results with the - raw JSON, and collect community-contributed atoms. +- **Near term:** Run a corrected LLM evaluation, publish the results with the raw JSON, and collect community-contributed atoms. +- **Medium term:** Develop domain packs for common verticals (CRM, healthcare, fintech). - **Long term:** Port the ontology to additional languages (Python, Rust, Go). - Develop domain packs for common verticals. ## Contributing @@ -271,7 +310,8 @@ npm run ci ``` That runs the validator, the coverage report, lint, type-checking across all -three tsconfig projects, the test suite, a build, and every example. +three tsconfig projects, the test suite, a build, every example, and the +evaluation self-check — the same steps as the GitHub Actions workflow. ### Governance diff --git a/atoms/objects/message.ts b/atoms/objects/message.ts index 1829520..de81dc2 100644 --- a/atoms/objects/message.ts +++ b/atoms/objects/message.ts @@ -40,6 +40,7 @@ export function createMessage(input: { channel?: Message['properties']['channel']; threadId?: string; recipientIds?: string[]; + readBy?: string[]; sentAt?: string; }): Message { return { @@ -52,6 +53,7 @@ export function createMessage(input: { channel: input.channel ?? 'in_app', threadId: input.threadId, recipientIds: input.recipientIds, + readBy: input.readBy, sentAt: input.sentAt ?? new Date().toISOString(), }, }; diff --git a/atoms/objects/subscription.ts b/atoms/objects/subscription.ts index feaba32..872afa9 100644 --- a/atoms/objects/subscription.ts +++ b/atoms/objects/subscription.ts @@ -49,6 +49,7 @@ export function createSubscription(input: { billingInterval?: Subscription['properties']['billingInterval']; startDate?: string; renewalDate?: string; + cancelAt?: string; }): Subscription { const now = new Date().toISOString(); return { @@ -62,6 +63,7 @@ export function createSubscription(input: { billingInterval: input.billingInterval ?? 'monthly', startDate: input.startDate ?? now.slice(0, 10), renewalDate: input.renewalDate, + cancelAt: input.cancelAt, createdAt: now, updatedAt: now, }, diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index d8eac7a..b3344df 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -33,8 +33,10 @@ Five names each exist in two families — `Email`, `Message`, `Search`, `Trigger 4. Prefer pure data + small functions. Avoid framework-specific code in the core atoms. 5. Add a test. `npm test` covers the validator, the schema validator, the eval metrics, and the atom implementations. A new atom without a test is - incomplete — the coverage report counts implementation files, and - `npm run coverage` will show the drop. + incomplete: `test/atom-test-coverage.test.ts` fails if the module is never + imported by a test, and the contribution is expected to assert behaviour, not + merely import it. `npm run coverage` is a different check — it measures + whether an implementation exists, not whether it is tested. 6. Keep the public surface minimal and well-typed. ## The Invariants the Validator Enforces @@ -100,5 +102,5 @@ npm run ci ``` This runs validation, the coverage report, lint, type-checking across all three -tsconfig projects, the test suite, a build, and every example. The PR template -repeats this checklist. +tsconfig projects, the test suite, a build, every example, and the evaluation +self-check. The PR template repeats this checklist. diff --git a/ontology/periodic-table.json b/ontology/periodic-table.json index c3c0090..9e724e9 100644 --- a/ontology/periodic-table.json +++ b/ontology/periodic-table.json @@ -1,5 +1,5 @@ { - "version": "0.4.0", + "version": "0.6.0", "description": "Canonical Periodic Table of Software Elements. Finite building blocks for compositional application development and LLM code generation.", "families": [ { diff --git a/package-lock.json b/package-lock.json index d8fe3a9..f48f2cb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,18 +1,21 @@ { "name": "software-periodic-table", - "version": "0.1.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "software-periodic-table", - "version": "0.1.0", + "version": "0.6.0", "license": "MIT", "devDependencies": { "@biomejs/biome": "^2.5.4", "@types/node": "^22.0.0", "tsx": "^4.19.0", "typescript": "^5.6.0" + }, + "engines": { + "node": ">=20.6.0" } }, "node_modules/@biomejs/biome": { diff --git a/package.json b/package.json index b1eaeae..7d540e8 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,11 @@ { "name": "software-periodic-table", - "version": "0.4.0", + "version": "0.6.0", "description": "A finite ontology of 115 recurring software elements and a composition framework for LLM-based coding agents", "type": "module", + "engines": { + "node": ">=20.6.0" + }, "scripts": { "build": "tsc", "example": "tsx examples/task-board.ts", @@ -16,9 +19,10 @@ "search": "tsx scripts/search.ts", "check": "tsc --noEmit && tsc -p tsconfig.test.json && tsc -p tsconfig.examples.json", "test": "node --import tsx --test test/*.test.ts", + "test:coverage": "node --import tsx --test --experimental-test-coverage test/*.test.ts", "format": "biome check --write", "lint": "biome check", - "ci": "npm run validate && npm run coverage && npm run lint && npm run check && npm test && npm run build && npm run examples:check", + "ci": "npm run validate && npm run coverage && npm run lint && npm run check && npm test && npm run build && npm run examples:check && npm run eval", "examples:check": "tsx examples/task-board.ts > /dev/null && tsx examples/crm-contacts.ts > /dev/null && tsx examples/product-catalog.ts > /dev/null && tsx examples/invoice-dashboard.ts > /dev/null && echo 'all examples ran'" }, "keywords": [ @@ -35,27 +39,34 @@ "type": "git", "url": "https://github.com/nulllabtests/software-periodic-table" }, + "bugs": { + "url": "https://github.com/nulllabtests/software-periodic-table/issues" + }, + "homepage": "https://github.com/nulllabtests/software-periodic-table#readme", "devDependencies": { "@biomejs/biome": "^2.5.4", "@types/node": "^22.0.0", "tsx": "^4.19.0", "typescript": "^5.6.0" }, - "main": "./dist/atoms/core.js", - "types": "./dist/atoms/core.d.ts", + "main": "./dist/src/index.js", + "types": "./dist/src/index.d.ts", "files": [ "dist", "ontology", "atoms", "composer", "src", + "docs", + "CHANGELOG.md", + "CITATION.cff", "README.md", "LICENSE" ], "exports": { ".": { - "types": "./dist/atoms/core.d.ts", - "default": "./dist/atoms/core.js" + "types": "./dist/src/index.d.ts", + "default": "./dist/src/index.js" }, "./loader": { "types": "./dist/src/ontology.d.ts", diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..c737ece --- /dev/null +++ b/src/index.ts @@ -0,0 +1,18 @@ +/** + * Package root entry point. + * + * The package previously advertised `atoms/core.ts` as its `main`, but that + * module contains only types and compiles to `export {}`. Importing the package + * by name therefore yielded an empty namespace. This module gives the root a + * real runtime surface while re-exporting the same core types, so existing + * `import type { Atom } from 'software-periodic-table'` statements keep working. + * + * Consumers that want a single atom should keep using the per-atom subpaths + * (`software-periodic-table/atoms/objects/task.js`); this root is the shared + * infrastructure: ontology loading, schema validation, and composition prompts. + */ + +export * from '../atoms/core.js'; +export * from '../composer/prompt.js'; +export * from './jsonschema.js'; +export * from './ontology.js'; diff --git a/test/atom-test-coverage.test.ts b/test/atom-test-coverage.test.ts new file mode 100644 index 0000000..73adee5 --- /dev/null +++ b/test/atom-test-coverage.test.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** Every hand-written atom module, as a repo-relative path without `.ts`. */ +function atomModules(dir: string, found: string[] = []): string[] { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + atomModules(full, found); + } else if (entry.name.endsWith('.ts') && entry.name !== 'core.ts') { + found.push(path.relative(path.join(ROOT, 'atoms'), full).replace(/\.ts$/, '').split(path.sep).join('/')); + } + } + return found; +} + +/** Atom modules imported by at least one test file. */ +function testedModules(): Set { + const imported = new Set(); + const testDir = path.join(ROOT, 'test'); + for (const file of fs.readdirSync(testDir).filter((name) => name.endsWith('.test.ts'))) { + const source = fs.readFileSync(path.join(testDir, file), 'utf8'); + for (const match of source.matchAll(/from\s+'\.\.\/atoms\/([^']+)\.js'/g)) { + if (match[1]) imported.add(match[1]); + } + } + return imported; +} + +describe('atom test coverage', () => { + it('imports every atom module from at least one test', () => { + // This is a floor, not proof of useful assertions: a module can be imported + // and never exercised. It does catch the failure mode that existed before + // v0.6.0, where all 35 object atoms had no test at all. + const modules = atomModules(path.join(ROOT, 'atoms')); + const imported = testedModules(); + const untested = modules.filter((module) => !imported.has(module)).sort(); + + assert.deepEqual(untested, [], `atom modules with no test import:\n ${untested.join('\n ')}`); + }); + + it('finds the atom files it is meant to guard', () => { + assert.equal(atomModules(path.join(ROOT, 'atoms')).length, 94); + }); +}); diff --git a/test/atoms-untested.test.ts b/test/atoms-untested.test.ts new file mode 100644 index 0000000..d57a10b --- /dev/null +++ b/test/atoms-untested.test.ts @@ -0,0 +1,581 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { + CreateMeta, + createAction, + DeleteMeta, + deleteAction, + executeInMemory, + UpdateMeta, + updateAction, + ViewMeta, + viewAction, +} from '../atoms/actions/crud.js'; +import { AssignMeta, assignAction, MessageMeta, NotifyMeta, notifyAction } from '../atoms/actions/notify.js'; +import { + ExportMeta, + exportAction, + FilterMeta, + filterAction, + SearchMeta as SearchActionMeta, + SortMeta, + searchAction, + sortAction, +} from '../atoms/actions/search-filter.js'; +import { AnalyzeMeta, createAnalyze } from '../atoms/intelligence/analyze.js'; +import { ClassifyMeta, createClassify } from '../atoms/intelligence/classify.js'; +import { createExtract, ExtractMeta } from '../atoms/intelligence/extract.js'; +import { createGenerate, GenerateMeta } from '../atoms/intelligence/generate.js'; +import { createPrompt, PromptMeta } from '../atoms/intelligence/prompt.js'; +import { createRecommend, RecommendMeta } from '../atoms/intelligence/recommend.js'; +import { createSearch, SearchMeta } from '../atoms/intelligence/search.js'; +import { createSummarize, SummarizeMeta } from '../atoms/intelligence/summarize.js'; +import { CalendarMeta, defineCalendar, materializeCalendar } from '../atoms/interfaces/calendar.js'; +import { ChartMeta, defineChart, materializeChart } from '../atoms/interfaces/chart.js'; +import { DetailMeta, defineDetail, materializeDetail } from '../atoms/interfaces/detail.js'; +import { defineForm, FormMeta, materializeForm } from '../atoms/interfaces/form.js'; +import { AddressMeta, formatAddress } from '../atoms/properties/address.js'; +import { AiFieldMeta, isAiGenerated, markAiGenerated } from '../atoms/properties/ai-field.js'; +import { BooleanMeta, parseBoolean } from '../atoms/properties/boolean.js'; +import { CountMeta, isValidCount } from '../atoms/properties/count.js'; +import { CommonCurrencies, CurrencyMeta } from '../atoms/properties/currency.js'; +import { DateMeta, DateTimeMeta, formatDate, formatDateTime } from '../atoms/properties/date.js'; +import { EndDateMeta, isValidRange, rangeDurationMs, StartDateMeta } from '../atoms/properties/date-range.js'; +import { DurationMeta, daysToMs, formatDuration, hoursToMs, minutesToMs } from '../atoms/properties/duration.js'; +import { EmailMeta, isValidEmail, normalizeEmail } from '../atoms/properties/email.js'; +import { assertEnumValue, EnumMeta } from '../atoms/properties/enum-field.js'; +import { generateId, IdMeta } from '../atoms/properties/id.js'; +import { JsonMeta, parseJson } from '../atoms/properties/json.js'; +import { clampNumber, NumberMeta, roundTo } from '../atoms/properties/number.js'; +import { OwnerMeta } from '../atoms/properties/owner.js'; +import { clampPercent, formatPercent, PercentMeta } from '../atoms/properties/percent.js'; +import { normalizePhone, PhoneMeta } from '../atoms/properties/phone.js'; +import { CommonPriorityValues, PriorityMeta } from '../atoms/properties/priority.js'; +import { normalizeScore, ScoreMeta } from '../atoms/properties/score.js'; +import { assertValidStatus, CommonStatusVocabularies, StatusMeta } from '../atoms/properties/status.js'; +import { isEmptyText, TextMeta, truncateText } from '../atoms/properties/text.js'; +import { CreatedAtMeta, initTimestamps, touchTimestamps, UpdatedAtMeta } from '../atoms/properties/timestamps.js'; +import { isValidUrl, UrlMeta } from '../atoms/properties/url.js'; +import { AuditMeta, createAuditEntry, diffObjects } from '../atoms/rules/audit.js'; +import { can, defaultTaskPermissions, PermissionMeta } from '../atoms/rules/permission.js'; +import { createPolicy, evaluatePolicy, PolicyMeta } from '../atoms/rules/policy.js'; + +describe('Intelligence atoms', () => { + it('Search (Sr) creates a search request', () => { + assert.equal(SearchMeta.symbol, 'Sr'); + assert.equal(SearchMeta.family, 'intelligence'); + const req = createSearch({ query: 'test', objectType: 'Task', limit: 10 }); + assert.equal(req.query, 'test'); + assert.equal(req.objectType, 'Task'); + assert.equal(req.limit, 10); + }); + + it('Summarize (Sm) creates a summarize request', () => { + assert.equal(SummarizeMeta.symbol, 'Sm'); + assert.equal(SummarizeMeta.family, 'intelligence'); + const req = createSummarize({ content: 'long text', maxLength: 100, format: 'bullets' }); + assert.equal(req.content, 'long text'); + assert.equal(req.maxLength, 100); + assert.equal(req.format, 'bullets'); + }); + + it('Classify (Cs) creates a classify request', () => { + assert.equal(ClassifyMeta.symbol, 'Cs'); + assert.equal(ClassifyMeta.family, 'intelligence'); + const req = createClassify({ input: 'text', categories: ['a', 'b'], multiLabel: true }); + assert.equal(req.input, 'text'); + assert.deepEqual(req.categories, ['a', 'b']); + assert.equal(req.multiLabel, true); + }); + + it('Recommend (Rc) creates a recommend request', () => { + assert.equal(RecommendMeta.symbol, 'Rc'); + assert.equal(RecommendMeta.family, 'intelligence'); + const req = createRecommend({ itemId: '1', objectType: 'Product', strategy: 'similar', maxResults: 5 }); + assert.equal(req.itemId, '1'); + assert.equal(req.objectType, 'Product'); + assert.equal(req.strategy, 'similar'); + assert.equal(req.maxResults, 5); + }); + + it('Analyze (An) creates an analyze request', () => { + assert.equal(AnalyzeMeta.symbol, 'An'); + assert.equal(AnalyzeMeta.family, 'intelligence'); + const req = createAnalyze({ data: [1, 2, 3], metrics: ['sum', 'avg'], groupBy: 'category' }); + assert.deepEqual(req.data, [1, 2, 3]); + assert.deepEqual(req.metrics, ['sum', 'avg']); + assert.equal(req.groupBy, 'category'); + }); + + it('Extract (Ec) creates an extract request', () => { + assert.equal(ExtractMeta.symbol, 'Ec'); + assert.equal(ExtractMeta.family, 'intelligence'); + const req = createExtract({ source: 'text', schema: { name: 'string' }, sourceType: 'text' }); + assert.equal(req.source, 'text'); + assert.deepEqual(req.schema, { name: 'string' }); + assert.equal(req.sourceType, 'text'); + }); + + it('Generate (Gn) creates a generate request', () => { + assert.equal(GenerateMeta.symbol, 'Gn'); + assert.equal(GenerateMeta.family, 'intelligence'); + const req = createGenerate({ prompt: 'write code', format: 'code', temperature: 0.7, maxTokens: 1000 }); + assert.equal(req.prompt, 'write code'); + assert.equal(req.format, 'code'); + assert.equal(req.temperature, 0.7); + assert.equal(req.maxTokens, 1000); + }); + + it('Prompt (Pt) creates a prompt request', () => { + assert.equal(PromptMeta.symbol, 'Pt'); + assert.equal(PromptMeta.family, 'intelligence'); + const req = createPrompt({ + messages: [{ role: 'user', content: 'hello' }], + model: 'gpt-4o', + temperature: 0.5, + }); + assert.equal(req.messages.length, 1); + assert.equal(req.messages[0]?.content, 'hello'); + assert.equal(req.model, 'gpt-4o'); + assert.equal(req.temperature, 0.5); + }); +}); + +describe('Properties atoms', () => { + it('Status (Ss) validates status values', () => { + assert.equal(StatusMeta.symbol, 'Ss'); + assert.equal(StatusMeta.family, 'properties'); + assertValidStatus('active', CommonStatusVocabularies.user); + assert.throws(() => assertValidStatus('invalid', CommonStatusVocabularies.user), /Invalid status/); + }); + + it('Text (Tx) checks emptiness and truncates', () => { + assert.equal(TextMeta.symbol, 'Tx'); + assert.equal(TextMeta.family, 'properties'); + assert.equal(isEmptyText(''), true); + assert.equal(isEmptyText(' '), true); + assert.equal(isEmptyText('hello'), false); + assert.equal(truncateText('hello', 10), 'hello'); + assert.equal(truncateText('hello world', 5), 'hell…'); + }); + + it('Number (Nm) clamps and rounds', () => { + assert.equal(NumberMeta.symbol, 'Nm'); + assert.equal(NumberMeta.family, 'properties'); + assert.equal(clampNumber(5, 0, 10), 5); + assert.equal(clampNumber(-5, 0, 10), 0); + assert.equal(clampNumber(15, 0, 10), 10); + assert.equal(roundTo(Math.PI, 2), 3.14); + assert.equal(roundTo(Math.PI, 0), 3); + }); + + it('Date (Dt) and DateTime (Dm) format dates', () => { + assert.equal(DateMeta.symbol, 'Dt'); + assert.equal(DateTimeMeta.symbol, 'Dm'); + const date = new Date('2024-01-15T10:30:00Z'); + assert.equal(formatDate(date), '2024-01-15'); + assert.equal(formatDateTime(date), '2024-01-15T10:30:00.000Z'); + }); + + it('Currency (Cu) exposes common currencies', () => { + assert.equal(CurrencyMeta.symbol, 'Cu'); + assert.equal(CurrencyMeta.family, 'properties'); + assert.ok(CommonCurrencies.includes('USD')); + assert.ok(CommonCurrencies.includes('EUR')); + }); + + it('Enum (En) validates enum values', () => { + assert.equal(EnumMeta.symbol, 'En'); + assert.equal(EnumMeta.family, 'properties'); + assertEnumValue('active', ['active', 'inactive']); + assert.throws(() => assertEnumValue('invalid', ['active', 'inactive']), /Invalid value/); + }); + + it('Boolean (Bl) parses boolean values', () => { + assert.equal(BooleanMeta.symbol, 'Bl'); + assert.equal(BooleanMeta.family, 'properties'); + assert.equal(parseBoolean(true), true); + assert.equal(parseBoolean(false), false); + assert.equal(parseBoolean('true'), true); + assert.equal(parseBoolean('yes'), true); + assert.equal(parseBoolean('on'), true); + assert.equal(parseBoolean('1'), true); + assert.equal(parseBoolean('false'), false); + assert.equal(parseBoolean('no'), false); + assert.equal(parseBoolean('off'), false); + assert.equal(parseBoolean('0'), false); + assert.equal(parseBoolean(1), true); + assert.equal(parseBoolean(0), false); + assert.throws(() => parseBoolean('maybe'), /Cannot parse/); + }); + + it('ID (Id) generates unique identifiers', () => { + assert.equal(IdMeta.symbol, 'Id'); + assert.equal(IdMeta.family, 'properties'); + const id1 = generateId(); + const id2 = generateId(); + assert.notEqual(id1, id2); + assert.ok(id1.length > 0); + const prefixed = generateId('usr'); + assert.ok(prefixed.startsWith('usr_')); + }); + + it('Owner (Ow) defines owner references', () => { + assert.equal(OwnerMeta.symbol, 'Ow'); + assert.equal(OwnerMeta.family, 'properties'); + }); + + it('Priority (Py) defines common priority values', () => { + assert.equal(PriorityMeta.symbol, 'Py'); + assert.equal(PriorityMeta.family, 'properties'); + assert.deepEqual([...CommonPriorityValues], ['low', 'medium', 'high', 'urgent']); + }); + + it('CreatedAt (Ca) and UpdatedAt (Ua) manage timestamps', () => { + assert.equal(CreatedAtMeta.symbol, 'Ca'); + assert.equal(UpdatedAtMeta.symbol, 'Ua'); + const now = new Date('2024-01-01T00:00:00Z'); + const ts = initTimestamps(now); + assert.equal(ts.createdAt, '2024-01-01T00:00:00.000Z'); + assert.equal(ts.updatedAt, '2024-01-01T00:00:00.000Z'); + + const later = new Date('2024-01-02T00:00:00Z'); + const touched = touchTimestamps(ts, later); + assert.equal(touched.createdAt, '2024-01-01T00:00:00.000Z'); + assert.equal(touched.updatedAt, '2024-01-02T00:00:00.000Z'); + }); + + it('Score (Sk) normalizes scores', () => { + assert.equal(ScoreMeta.symbol, 'Sk'); + assert.equal(ScoreMeta.family, 'properties'); + assert.equal(normalizeScore(50, 0, 100), 0.5); + assert.equal(normalizeScore(0, 0, 100), 0); + assert.equal(normalizeScore(100, 0, 100), 1); + assert.equal(normalizeScore(150, 0, 100), 1); + assert.equal(normalizeScore(-10, 0, 100), 0); + }); + + it('Percent (Pc) clamps and formats percentages', () => { + assert.equal(PercentMeta.symbol, 'Pc'); + assert.equal(PercentMeta.family, 'properties'); + assert.equal(clampPercent(50), 50); + assert.equal(clampPercent(-10), 0); + assert.equal(clampPercent(110), 100); + assert.equal(formatPercent(50), '50%'); + assert.equal(formatPercent(50.5, 1), '50.5%'); + }); + + it('Duration (Du) converts and formats durations', () => { + assert.equal(DurationMeta.symbol, 'Du'); + assert.equal(DurationMeta.family, 'properties'); + assert.equal(minutesToMs(1), 60_000); + assert.equal(hoursToMs(1), 3_600_000); + assert.equal(daysToMs(1), 86_400_000); + assert.equal(formatDuration(0), '0m'); + assert.equal(formatDuration(60_000), '1m'); + assert.equal(formatDuration(3_600_000), '1h'); + assert.equal(formatDuration(86_400_000), '1d'); + assert.equal(formatDuration(90_061_000), '1d 1h 1m 1s'); + assert.throws(() => formatDuration(-1), /cannot be negative/); + }); + + it('Count (Cn) validates counts', () => { + assert.equal(CountMeta.symbol, 'Cn'); + assert.equal(CountMeta.family, 'properties'); + assert.equal(isValidCount(0), true); + assert.equal(isValidCount(5), true); + assert.equal(isValidCount(-1), false); + assert.equal(isValidCount(1.5), false); + }); + + it('JSON (Js) parses JSON safely', () => { + assert.equal(JsonMeta.symbol, 'Js'); + assert.equal(JsonMeta.family, 'properties'); + assert.deepEqual(parseJson('{"a":1}'), { a: 1 }); + assert.deepEqual(parseJson('[1,2,3]'), [1, 2, 3]); + assert.equal(parseJson('invalid'), undefined); + assert.equal(parseJson(''), undefined); + }); + + it('Address (Ad) formats addresses', () => { + assert.equal(AddressMeta.symbol, 'Ad'); + assert.equal(AddressMeta.family, 'properties'); + const addr = { line1: '123 Main St', city: 'Springfield', region: 'IL', postalCode: '62701', country: 'US' }; + assert.equal(formatAddress(addr), '123 Main St, Springfield, IL, 62701, US'); + assert.equal(formatAddress({ line1: '123 Main St' }), '123 Main St'); + }); + + it('AI (Ai) marks and detects AI-generated fields', () => { + assert.equal(AiFieldMeta.symbol, 'Ai'); + assert.equal(AiFieldMeta.family, 'properties'); + const field = markAiGenerated('summary text', { model: 'gpt-4o', confidence: 0.95 }); + assert.equal(field.value, 'summary text'); + assert.equal(field.model, 'gpt-4o'); + assert.equal(field.confidence, 0.95); + assert.ok(typeof field.generatedAt === 'string'); + assert.equal(isAiGenerated(field), true); + assert.equal(isAiGenerated({ value: 'text' }), false); + assert.equal(isAiGenerated(null), false); + assert.equal(isAiGenerated('string'), false); + }); + + it('StartDate (Sd) and EndDate (Ed) validate ranges', () => { + assert.equal(StartDateMeta.symbol, 'Sd'); + assert.equal(EndDateMeta.symbol, 'Ed'); + const validRange = { start: '2024-01-01T00:00:00Z', end: '2024-01-02T00:00:00Z' }; + assert.equal(isValidRange(validRange), true); + assert.equal(rangeDurationMs(validRange), 86_400_000); + + const invalidRange = { start: '2024-01-02T00:00:00Z', end: '2024-01-01T00:00:00Z' }; + assert.equal(isValidRange(invalidRange), false); + assert.equal(rangeDurationMs(invalidRange), 0); + }); + + it('Email (Ea) validates and normalizes emails', () => { + assert.equal(EmailMeta.symbol, 'Ea'); + assert.equal(EmailMeta.family, 'properties'); + assert.equal(isValidEmail('test@example.com'), true); + assert.equal(isValidEmail('invalid'), false); + assert.equal(isValidEmail('test@'), false); + assert.equal(isValidEmail('@example.com'), false); + assert.equal(normalizeEmail(' Test@Example.COM '), 'test@example.com'); + }); + + it('Phone (Ph) normalizes phone numbers', () => { + assert.equal(PhoneMeta.symbol, 'Ph'); + assert.equal(PhoneMeta.family, 'properties'); + assert.equal(normalizePhone('+1 (555) 123-4567'), '+15551234567'); + assert.equal(normalizePhone('555-123-4567'), '5551234567'); + assert.equal(normalizePhone(' +44 20 7946 0958 '), '+442079460958'); + }); + + it('URL (Ur) validates URLs', () => { + assert.equal(UrlMeta.symbol, 'Ur'); + assert.equal(UrlMeta.family, 'properties'); + assert.equal(isValidUrl('https://example.com'), true); + assert.equal(isValidUrl('http://localhost:3000'), true); + assert.equal(isValidUrl('not-a-url'), false); + assert.equal(isValidUrl(''), false); + }); +}); + +describe('Actions atoms', () => { + it('Create (Cr), Update (Up), Delete (De), View (Vw) build action requests', () => { + assert.equal(CreateMeta.symbol, 'Cr'); + assert.equal(UpdateMeta.symbol, 'Up'); + assert.equal(DeleteMeta.symbol, 'De'); + assert.equal(ViewMeta.symbol, 'Vw'); + + const create = createAction('Task', { title: 'New' }, 'u1'); + assert.equal(create.action, 'Create'); + assert.equal(create.targetType, 'Task'); + assert.equal(create.actorId, 'u1'); + + const update = updateAction('Task', 't1', { title: 'Updated' }, 'u1'); + assert.equal(update.action, 'Update'); + assert.equal(update.targetId, 't1'); + + const del = deleteAction('Task', 't1', 'u1'); + assert.equal(del.action, 'Delete'); + assert.equal(del.targetId, 't1'); + + const view = viewAction('Task', 't1', 'u1'); + assert.equal(view.action, 'View'); + assert.equal(view.targetId, 't1'); + }); + + it('executeInMemory performs CRUD operations', () => { + const store = new Map>(); + + const created = executeInMemory(store, createAction('Task', { title: 'Test' })); + assert.equal(created.success, true); + const id = (created.data as Record).id as string; + assert.ok(id); + + const viewed = executeInMemory(store, viewAction('Task', id)); + assert.equal(viewed.success, true); + assert.equal((viewed.data as Record).title, 'Test'); + + const updated = executeInMemory(store, updateAction('Task', id, { title: 'Updated' })); + assert.equal(updated.success, true); + assert.equal((updated.data as Record).title, 'Updated'); + + const deleted = executeInMemory(store, deleteAction('Task', id)); + assert.equal(deleted.success, true); + + const notFound = executeInMemory(store, viewAction('Task', id)); + assert.equal(notFound.success, false); + }); + + it('Notify (No), Message (Mg), Assign (As) build action requests', () => { + assert.equal(NotifyMeta.symbol, 'No'); + assert.equal(MessageMeta.symbol, 'Mg'); + assert.equal(AssignMeta.symbol, 'As'); + + const notify = notifyAction('User', 'u1', 'Hello', 'email', 'admin'); + assert.equal(notify.action, 'Notify'); + assert.equal(notify.targetType, 'User'); + assert.equal(notify.targetId, 'u1'); + assert.equal((notify.payload as Record).message, 'Hello'); + assert.equal((notify.payload as Record).channel, 'email'); + + const assign = assignAction('Task', 't1', 'u1', 'admin'); + assert.equal(assign.action, 'Assign'); + assert.equal((assign.payload as Record).assigneeId, 'u1'); + }); + + it('Search (Se), Filter (Fi), Sort (So), Export (Ex) build action requests', () => { + assert.equal(SearchActionMeta.symbol, 'Se'); + assert.equal(FilterMeta.symbol, 'Fi'); + assert.equal(SortMeta.symbol, 'So'); + assert.equal(ExportMeta.symbol, 'Ex'); + + const search = searchAction('Task', 'test', { status: 'active' }, 'u1'); + assert.equal(search.action, 'Search'); + assert.equal((search.payload as Record).query, 'test'); + + const filter = filterAction('Task', { status: 'active' }, 'u1'); + assert.equal(filter.action, 'Filter'); + + const sort = sortAction('Task', 'name', 'desc', 'u1'); + assert.equal(sort.action, 'Sort'); + assert.equal((sort.payload as Record).direction, 'desc'); + + const exp = exportAction('Task', 'csv', { status: 'active' }, 'u1'); + assert.equal(exp.action, 'Export'); + assert.equal((exp.payload as Record).format, 'csv'); + }); +}); + +describe('Interfaces atoms', () => { + it('Calendar (Ce) defines and materializes calendar views', () => { + assert.equal(CalendarMeta.symbol, 'Ce'); + assert.equal(CalendarMeta.family, 'interfaces'); + const spec = defineCalendar({ objectType: 'Event', dateField: 'start', titleField: 'title' }); + assert.equal(spec.kind, 'Calendar'); + assert.equal(spec.objectType, 'Event'); + + const { events } = materializeCalendar(spec, [ + { id: '1', title: 'Meeting', start: '2024-01-15T10:00:00Z' }, + { id: '2', title: 'Lunch', start: '2024-01-15T12:00:00Z' }, + ]); + assert.equal(events.length, 2); + assert.equal(events[0]?.title, 'Meeting'); + assert.equal(events[0]?.start, '2024-01-15T10:00:00Z'); + }); + + it('Chart (Ch) defines and materializes chart views', () => { + assert.equal(ChartMeta.symbol, 'Ch'); + assert.equal(ChartMeta.family, 'interfaces'); + const spec = defineChart({ + objectType: 'Invoice', + chartType: 'bar', + series: [{ label: 'Amount', key: 'amount' }], + xAxisKey: 'month', + }); + assert.equal(spec.kind, 'Chart'); + assert.equal(spec.chartType, 'bar'); + + const { data, meta } = materializeChart(spec, [ + { month: 'Jan', amount: 100 }, + { month: 'Feb', amount: 200 }, + ]); + assert.equal(data.length, 2); + assert.equal(meta.count, 2); + }); + + it('Detail (Di) defines and materializes detail views', () => { + assert.equal(DetailMeta.symbol, 'Di'); + assert.equal(DetailMeta.family, 'interfaces'); + const spec = defineDetail({ + objectType: 'Task', + sections: [{ title: 'Overview', fields: [{ key: 'title', label: 'Title' }] }], + }); + assert.equal(spec.kind, 'Detail'); + assert.equal(spec.sections.length, 1); + + const { sections, data } = materializeDetail(spec, { title: 'Test Task' }); + assert.equal(sections.length, 1); + assert.equal(data.title, 'Test Task'); + }); + + it('Form (Fm) defines and materializes form views', () => { + assert.equal(FormMeta.symbol, 'Fm'); + assert.equal(FormMeta.family, 'interfaces'); + const spec = defineForm({ + objectType: 'Task', + fields: [{ key: 'title', label: 'Title', type: 'text', required: true }], + }); + assert.equal(spec.kind, 'Form'); + assert.equal(spec.objectType, 'Task'); + assert.equal(spec.submitLabel, 'Save'); + assert.equal(spec.cancelLabel, 'Cancel'); + assert.equal(spec.layout, 'vertical'); + assert.deepEqual(spec.actions, ['Create', 'Update']); + + const { fields, values, spec: outSpec } = materializeForm(spec); + assert.equal(fields.length, 1); + assert.deepEqual(values, {}); + assert.equal(outSpec, spec); + + const withData = materializeForm(spec, { title: 'Test' }); + assert.deepEqual(withData.values, { title: 'Test' }); + }); +}); + +describe('Rules atoms', () => { + it('Audit (Au) creates audit entries and diffs objects', () => { + assert.equal(AuditMeta.symbol, 'Au'); + assert.equal(AuditMeta.family, 'rules'); + const entry = createAuditEntry({ + id: 'a1', + actorId: 'u1', + action: 'Update', + objectType: 'Task', + objectId: 't1', + changes: { title: { from: 'Old', to: 'New' } }, + }); + assert.equal(entry.id, 'a1'); + assert.equal(entry.actorId, 'u1'); + assert.equal(entry.action, 'Update'); + assert.ok(typeof entry.timestamp === 'string'); + + const diff = diffObjects({ a: 1, b: 2 }, { a: 1, b: 3, c: 4 }); + assert.deepEqual(diff, { b: { from: 2, to: 3 }, c: { from: undefined, to: 4 } }); + }); + + it('Permission (Pn) checks permissions', () => { + assert.equal(PermissionMeta.symbol, 'Pn'); + assert.equal(PermissionMeta.family, 'rules'); + assert.equal(can(defaultTaskPermissions, 'admin', 'Create', 'Task'), true); + assert.equal(can(defaultTaskPermissions, 'admin', 'Delete', 'Task'), true); + assert.equal(can(defaultTaskPermissions, 'member', 'Create', 'Task'), true); + assert.equal(can(defaultTaskPermissions, 'member', 'Delete', 'Task'), false); + assert.equal(can(defaultTaskPermissions, 'viewer', 'View', 'Task'), true); + assert.equal(can(defaultTaskPermissions, 'viewer', 'Create', 'Task'), false); + }); + + it('Policy (Po) creates and evaluates policies', () => { + assert.equal(PolicyMeta.symbol, 'Po'); + assert.equal(PolicyMeta.family, 'rules'); + const policy = createPolicy({ + id: 'pol1', + name: 'Task Policy', + statements: [ + { id: 's1', name: 'Deny delete', effect: 'deny', actions: ['Delete'], resources: ['Task'] }, + { id: 's2', name: 'Allow all', effect: 'allow', actions: ['*'], resources: ['*'] }, + ], + }); + // first-match semantics: the deny statement is listed first so it wins + assert.equal(policy.enabled, true); + assert.equal(policy.statements.length, 2); + + const result1 = evaluatePolicy(policy, 'Create', 'Task'); + assert.equal(result1.allowed, true); + assert.equal(result1.matchedStatement, 'Allow all'); + + const result2 = evaluatePolicy(policy, 'Delete', 'Task'); + assert.equal(result2.allowed, false); + assert.equal(result2.matchedStatement, 'Deny delete'); + }); +}); diff --git a/test/objects.test.ts b/test/objects.test.ts new file mode 100644 index 0000000..ad3573c --- /dev/null +++ b/test/objects.test.ts @@ -0,0 +1,585 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import type { AtomMeta, ObjectAtom, PropertyDef } from '../atoms/core.js'; +import { AccountMeta, AccountProperties, createAccount } from '../atoms/objects/account.js'; +import { ActivityMeta, ActivityProperties, createActivity } from '../atoms/objects/activity.js'; +import { CallMeta, CallProperties, createCall } from '../atoms/objects/call.js'; +import { CampaignMeta, CampaignProperties, createCampaign } from '../atoms/objects/campaign.js'; +import { CompanyMeta, CompanyProperties, createCompany } from '../atoms/objects/company.js'; +import { ContactMeta, ContactProperties, createContact } from '../atoms/objects/contact.js'; +import { createDeal, DealMeta, DealProperties } from '../atoms/objects/deal.js'; +import { createDoc, DocMeta, DocProperties } from '../atoms/objects/doc.js'; +import { createEmail, EmailMeta, EmailProperties } from '../atoms/objects/email.js'; +import { createEvent, EventMeta, EventProperties } from '../atoms/objects/event.js'; +import { createFile, FileMeta, FileProperties } from '../atoms/objects/file.js'; +import { createInvoice, InvoiceMeta, InvoiceProperties } from '../atoms/objects/invoice.js'; +import { createLead, LeadMeta, LeadProperties } from '../atoms/objects/lead.js'; +import { createLocation, LocationMeta, LocationProperties } from '../atoms/objects/location.js'; +import { createMeeting, MeetingMeta, MeetingProperties } from '../atoms/objects/meeting.js'; +import { createMessage, MessageMeta, MessageProperties } from '../atoms/objects/message.js'; +import { createNote, NoteMeta, NoteProperties } from '../atoms/objects/note.js'; +import { createOpportunity, OpportunityMeta, OpportunityProperties } from '../atoms/objects/opportunity.js'; +import { createPayment, PaymentMeta, PaymentProperties } from '../atoms/objects/payment.js'; +import { createPerson, PersonMeta, PersonProperties } from '../atoms/objects/person.js'; +import { createPlan, PlanMeta, PlanProperties } from '../atoms/objects/plan.js'; +import { createPrice, PriceMeta, PriceProperties } from '../atoms/objects/price.js'; +import { createProduct, ProductMeta, ProductProperties } from '../atoms/objects/product.js'; +import { createProject, ProjectMeta, ProjectProperties } from '../atoms/objects/project.js'; +import { createRole, RoleMeta, RoleProperties } from '../atoms/objects/role.js'; +import { createService, ServiceMeta, ServiceProperties } from '../atoms/objects/service.js'; +import { createSubscription, SubscriptionMeta, SubscriptionProperties } from '../atoms/objects/subscription.js'; +import { createSubtask, SubtaskMeta, SubtaskProperties } from '../atoms/objects/subtask.js'; +import { createTag, TagMeta, TagProperties } from '../atoms/objects/tag.js'; +import { createTask, TaskMeta, TaskProperties } from '../atoms/objects/task.js'; +import { createTeam, TeamMeta, TeamProperties } from '../atoms/objects/team.js'; +import { createTemplate, TemplateMeta, TemplateProperties } from '../atoms/objects/template.js'; +import { createUser, UserMeta, UserProperties } from '../atoms/objects/user.js'; +import { createVendor, VendorMeta, VendorProperties } from '../atoms/objects/vendor.js'; +import { createWorkflow, WorkflowMeta, WorkflowProperties } from '../atoms/objects/workflow.js'; +import { loadOntology } from '../src/ontology.js'; + +interface ObjectCase { + symbol: string; + meta: AtomMeta; + properties: PropertyDef[]; + create: (input: Record) => ObjectAtom; + /** Smallest valid input: only the fields the factory requires. */ + input: Record; + /** Optional fields, supplied to prove the factory does not drop them. */ + extra: Record; + /** Values the factory must supply when the caller omits the field. */ + defaults: Record; +} + +/** + * Register one object atom with a minimal input, optional inputs to round-trip, + * and the defaults it promises. Keeping this generic is what lets a single set + * of assertions cover all 35 object atoms instead of 35 near-identical tests. + */ +function objectCase( + meta: AtomMeta, + properties: PropertyDef[], + create: (input: I) => ObjectAtom, + input: I, + extra: Record, + defaults: Record, +): ObjectCase { + return { + symbol: meta.symbol, + meta, + properties, + create: (raw) => create(raw as unknown as I), + input: { ...input } as Record, + extra, + defaults, + }; +} + +const objectCases: ObjectCase[] = [ + objectCase( + CompanyMeta, + CompanyProperties, + createCompany, + { id: 'co_1', name: 'Acme' }, + { industry: 'Software', website: 'https://acme.test', phone: '+1-555-0100', address: '1 Main St', status: 'lead' }, + { status: 'active' }, + ), + objectCase( + PersonMeta, + PersonProperties, + createPerson, + { id: 'pe_1', firstName: 'Ada', lastName: 'Lovelace', email: 'ada@example.test' }, + { phone: '+1-555-0101', title: 'Engineer', companyId: 'co_1' }, + {}, + ), + objectCase( + ContactMeta, + ContactProperties, + createContact, + { id: 'ct_1', firstName: 'Grace', lastName: 'Hopper' }, + { email: 'grace@example.test', phone: '+1-555-0102', companyId: 'co_1', role: 'CTO', status: 'lead' }, + { status: 'active' }, + ), + objectCase( + LeadMeta, + LeadProperties, + createLead, + { id: 'ld_1', name: 'Linus', email: 'linus@example.test' }, + { phone: '+1-555-0103', company: 'Kernel Co', source: 'referral', owner: 'us_1', score: 87 }, + { source: 'web', status: 'new' }, + ), + objectCase( + DealMeta, + DealProperties, + createDeal, + { id: 'dl_1', title: 'Enterprise', amount: 12_000 }, + { + currency: 'EUR', + stage: 'proposal', + owner: 'us_1', + accountId: 'ac_1', + contactId: 'ct_1', + expectedCloseDate: '2026-12-01', + probability: 60, + }, + { stage: 'prospecting' }, + ), + objectCase( + AccountMeta, + AccountProperties, + createAccount, + { id: 'ac_1', name: 'Acme' }, + { + type: 'partner', + industry: 'Software', + website: 'https://acme.test', + phone: '+1-555-0100', + billingAddress: '1 Main St', + owner: 'us_1', + }, + { type: 'customer', status: 'active' }, + ), + objectCase( + UserMeta, + UserProperties, + createUser, + { id: 'us_1', email: 'user@example.test', name: 'Test User' }, + { role: 'admin' }, + { status: 'active' }, + ), + objectCase( + TeamMeta, + TeamProperties, + createTeam, + { id: 'tm_1', name: 'Core' }, + { description: 'Platform team', memberIds: ['us_1'], owner: 'us_1' }, + {}, + ), + objectCase( + RoleMeta, + RoleProperties, + createRole, + { id: 'ro_1', name: 'Admin' }, + { description: 'Administrators', permissions: ['task:read'], isSystem: true }, + {}, + ), + objectCase( + OpportunityMeta, + OpportunityProperties, + createOpportunity, + { id: 'op_1', title: 'Expansion', value: 5_000 }, + { + currency: 'EUR', + stage: 'proposal', + owner: 'us_1', + accountId: 'ac_1', + source: 'inbound', + closeDate: '2026-12-31', + }, + { stage: 'discovery' }, + ), + objectCase( + ProductMeta, + ProductProperties, + createProduct, + { id: 'pr_1', name: 'Widget', price: 19.99 }, + { + description: 'A widget', + currency: 'EUR', + category: 'hardware', + status: 'inactive', + imageUrl: 'https://acme.test/widget.png', + tags: ['new'], + }, + { currency: 'USD', status: 'active' }, + ), + objectCase( + ServiceMeta, + ServiceProperties, + createService, + { id: 'sv_1', name: 'Installation' }, + { description: 'On-site install', category: 'field', price: 100, currency: 'EUR', durationMinutes: 90 }, + { status: 'active' }, + ), + objectCase( + ProjectMeta, + ProjectProperties, + createProject, + { id: 'pj_1', name: 'Launch' }, + { + description: 'Q4 launch', + status: 'active', + priority: 'high', + owner: 'us_1', + startDate: '2026-11-01', + endDate: '2026-12-01', + budget: 5_000, + }, + { status: 'planning' }, + ), + objectCase( + TaskMeta, + TaskProperties, + createTask, + { id: 'tk_1', title: 'Write tests' }, + { + description: 'Cover the object family', + status: 'in_progress', + priority: 'urgent', + owner: 'us_1', + projectId: 'pj_1', + dueDate: '2026-11-01', + }, + { status: 'todo', priority: 'medium' }, + ), + objectCase( + SubtaskMeta, + SubtaskProperties, + createSubtask, + { id: 'st_1', title: 'Review', parentTaskId: 'tk_1' }, + { assignee: 'us_1', dueDate: '2026-11-01' }, + { status: 'todo' }, + ), + objectCase( + DocMeta, + DocProperties, + createDoc, + { id: 'dc_1', title: 'Spec' }, + { body: '# Spec', format: 'html', authorId: 'us_1', folderId: 'dc_0' }, + { format: 'markdown', status: 'draft' }, + ), + objectCase( + FileMeta, + FileProperties, + createFile, + { id: 'fl_1', name: 'a.pdf', mimeType: 'application/pdf', sizeBytes: 1024, storageKey: 's3://bucket/a' }, + { uploadedBy: 'us_1', parentId: 'fl_0', metadata: { pages: 2 } }, + {}, + ), + objectCase( + NoteMeta, + NoteProperties, + createNote, + { id: 'nt_1', body: 'Note' }, + { authorId: 'us_1', entityType: 'Task', entityId: 'tk_1', pinned: true }, + {}, + ), + objectCase( + EventMeta, + EventProperties, + createEvent, + { id: 'ev_1', title: 'Launch', startsAt: '2026-11-01T10:00:00.000Z' }, + { + endsAt: '2026-11-01T11:00:00.000Z', + type: 'deadline', + calendarId: 'cal_1', + attendeeIds: ['us_1'], + location: 'HQ', + }, + { type: 'appointment' }, + ), + objectCase( + MeetingMeta, + MeetingProperties, + createMeeting, + { id: 'mt_1', title: 'Standup', startsAt: '2026-11-01T09:00:00.000Z' }, + { + endsAt: '2026-11-01T09:15:00.000Z', + organizerId: 'us_1', + attendeeIds: ['us_2'], + location: 'Room 1', + conferenceUrl: 'https://meet.test/1', + agenda: 'Status', + }, + { status: 'scheduled' }, + ), + objectCase( + InvoiceMeta, + InvoiceProperties, + createInvoice, + { + id: 'in_1', + number: 'INV-1', + customerName: 'Acme', + amount: 100, + issueDate: '2026-10-01', + dueDate: '2026-10-31', + }, + { + customerId: 'ac_1', + currency: 'EUR', + status: 'sent', + paidAt: '2026-10-15T12:00:00.000Z', + notes: 'Thanks', + }, + { currency: 'USD', status: 'draft' }, + ), + objectCase( + PaymentMeta, + PaymentProperties, + createPayment, + { id: 'pm_1', amount: 100 }, + { + currency: 'EUR', + method: 'bank_transfer', + invoiceId: 'in_1', + customerId: 'ac_1', + receivedAt: '2026-10-15T12:00:00.000Z', + reference: 'REF-1', + }, + { method: 'card', status: 'pending' }, + ), + objectCase( + SubscriptionMeta, + SubscriptionProperties, + createSubscription, + { id: 'su_1', customerId: 'ac_1', planId: 'pl_1' }, + { + billingInterval: 'yearly', + startDate: '2026-01-01', + renewalDate: '2027-01-01', + cancelAt: '2026-12-01T00:00:00.000Z', + }, + { status: 'active', billingInterval: 'monthly' }, + ), + objectCase( + PlanMeta, + PlanProperties, + createPlan, + { id: 'pl_1', name: 'Pro', price: 49 }, + { description: 'Pro tier', currency: 'EUR', interval: 'yearly', features: ['a'], limits: { seats: 10 } }, + { interval: 'monthly', status: 'active' }, + ), + objectCase( + PriceMeta, + PriceProperties, + createPrice, + { id: 'px_1', amount: 49, currency: 'USD', objectType: 'Plan', objectId: 'pl_1' }, + { tier: 'sale', validFrom: '2026-01-01', validTo: '2026-12-31' }, + { tier: 'list' }, + ), + objectCase( + CampaignMeta, + CampaignProperties, + createCampaign, + { id: 'cp_1', name: 'Promo' }, + { + description: 'Launch promo', + type: 'social', + owner: 'us_1', + budget: 1_000, + startsAt: '2026-11-01T00:00:00.000Z', + endsAt: '2026-11-30T00:00:00.000Z', + }, + { type: 'email', status: 'draft' }, + ), + objectCase( + MessageMeta, + MessageProperties, + createMessage, + { id: 'ms_1', body: 'Hi', senderId: 'us_1' }, + { + channel: 'sms', + threadId: 'th_1', + recipientIds: ['us_2'], + readBy: ['us_2'], + sentAt: '2026-11-01T10:00:00.000Z', + }, + { channel: 'in_app' }, + ), + objectCase( + EmailMeta, + EmailProperties, + createEmail, + { id: 'em_1', to: 'a@example.test', from: 'b@example.test', subject: 'Hi' }, + { + body: 'Hello', + cc: ['c@example.test'], + bcc: ['d@example.test'], + attachments: ['f.pdf'], + status: 'sent', + sentAt: '2026-11-01T10:00:00.000Z', + }, + { status: 'draft' }, + ), + objectCase( + CallMeta, + CallProperties, + createCall, + { id: 'cl_1' }, + { + participantIds: ['us_1', 'us_2'], + direction: 'inbound', + kind: 'video', + startedAt: '2026-11-01T10:00:00.000Z', + endedAt: '2026-11-01T10:02:00.000Z', + durationSeconds: 120, + recordingUrl: 'https://rec.test/1', + summary: 'Sync', + }, + { direction: 'outbound', kind: 'voice' }, + ), + objectCase( + ActivityMeta, + ActivityProperties, + createActivity, + { id: 'ay_1', type: 'call', subject: 'Intro' }, + { + description: 'Intro call', + contactId: 'ct_1', + performedBy: 'us_1', + performedAt: '2026-11-01T10:00:00.000Z', + }, + {}, + ), + objectCase( + WorkflowMeta, + WorkflowProperties, + createWorkflow, + { id: 'wf_1', name: 'Onboarding', steps: [{ action: 'notify' }] }, + { description: 'Onboard a user', trigger: { on: 'create' }, version: 3 }, + { status: 'draft', version: 1 }, + ), + objectCase( + TemplateMeta, + TemplateProperties, + createTemplate, + { id: 'tp_1', name: 'Welcome', entityType: 'Email', content: { body: 'Hi' } }, + { description: 'Welcome email', variables: ['name'], isSystem: true }, + {}, + ), + objectCase( + TagMeta, + TagProperties, + createTag, + { id: 'tg_1', name: 'urgent' }, + { color: '#ff0000', entityType: 'Task' }, + {}, + ), + objectCase( + LocationMeta, + LocationProperties, + createLocation, + { id: 'lc_1', name: 'HQ' }, + { + address: '1 Main St', + latitude: 1.5, + longitude: -2.5, + city: 'Springfield', + country: 'US', + timezone: 'America/New_York', + }, + {}, + ), + objectCase( + VendorMeta, + VendorProperties, + createVendor, + { id: 'vn_1', name: 'Supplier' }, + { + contactName: 'Sam', + email: 'sam@supplier.test', + phone: '+1-555-0104', + website: 'https://supplier.test', + paymentTerms: 'net30', + }, + { status: 'active' }, + ), +]; + +const ontology = loadOntology(); + +/** Fail with the element and field in the message, not just "expected true". */ +function assertMatchesType(def: PropertyDef, value: unknown, label: string): void { + if (value === undefined) return; + switch (def.type) { + case 'string': + case 'date': + case 'datetime': + case 'id': + case 'reference': + assert.equal(typeof value, 'string', `${label} is not a string`); + break; + case 'number': + case 'currency': + assert.equal(typeof value, 'number', `${label} is not a number`); + assert.ok(Number.isFinite(value as number), `${label} is not finite`); + break; + case 'boolean': + assert.equal(typeof value, 'boolean', `${label} is not a boolean`); + break; + case 'enum': + assert.ok( + def.enumValues?.includes(value as string), + `${label} = ${String(value)} is not in ${def.enumValues?.join(', ')}`, + ); + break; + case 'json': + assert.ok(typeof value === 'object' && value !== null, `${label} is not an object`); + break; + } +} + +describe('object atoms', () => { + it('registers every object element in the ontology', () => { + const declared = ontology.elements.filter((element) => element.family === 'objects'); + assert.equal(objectCases.length, declared.length); + assert.deepEqual(objectCases.map((c) => c.symbol).sort(), declared.map((element) => element.symbol).sort()); + }); + + it('declares metadata that matches the ontology', () => { + for (const testCase of objectCases) { + const element = ontology.elements.find((candidate) => candidate.symbol === testCase.symbol); + assert.ok(element, `${testCase.symbol} is not in the ontology`); + assert.equal(testCase.meta.id, element.id, `${testCase.symbol} id`); + assert.equal(testCase.meta.symbol, element.symbol, `${testCase.symbol} symbol`); + assert.equal(testCase.meta.name, element.name, `${testCase.symbol} name`); + assert.equal(testCase.meta.family, 'objects', `${testCase.symbol} family`); + assert.ok(testCase.meta.description.length > 0, `${testCase.symbol} description`); + } + }); + + for (const testCase of objectCases) { + describe(`${testCase.meta.name} (${testCase.symbol})`, () => { + it('materializes every declared property and nothing undeclared', () => { + const created = testCase.create(testCase.input); + const declared = new Set(testCase.properties.map((def) => def.key)); + + for (const def of testCase.properties) { + assert.ok( + Object.hasOwn(created.properties, def.key), + `${testCase.symbol} declares ${def.key} but the factory does not set it`, + ); + assertMatchesType(def, created.properties[def.key], `${testCase.symbol}.${def.key}`); + } + + const undeclared = Object.keys(created.properties).filter((key) => !declared.has(key)); + assert.deepEqual(undeclared, [], `${testCase.symbol} writes properties it never declares`); + }); + + it('fills required properties and applies defaults', () => { + const created = testCase.create(testCase.input); + assert.equal(created.meta, testCase.meta); + assert.equal(created.id, testCase.input.id); + + for (const def of testCase.properties.filter((property) => property.required)) { + const value = created.properties[def.key]; + assert.notEqual(value, undefined, `${testCase.symbol}.${def.key} is required but unset`); + assert.notEqual(value, null, `${testCase.symbol}.${def.key} is required but null`); + } + + for (const [key, expected] of Object.entries(testCase.defaults)) { + assert.deepEqual(created.properties[key], expected, `${testCase.symbol}.${key} default`); + } + }); + + it('round-trips optional inputs instead of dropping them', () => { + const input = { ...testCase.input, ...testCase.extra }; + const created = testCase.create(input); + for (const [key, value] of Object.entries(input)) { + assert.deepEqual(created.properties[key], value, `${testCase.symbol}.${key} was not copied through`); + } + }); + }); + } +}); diff --git a/test/project.test.ts b/test/project.test.ts new file mode 100644 index 0000000..21ac1a7 --- /dev/null +++ b/test/project.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { loadOntology } from '../src/ontology.js'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +function read(relativePath: string): string { + return fs.readFileSync(path.join(ROOT, relativePath), 'utf8'); +} + +const ontology = loadOntology(); +const pkg = JSON.parse(read('package.json')) as { + version: string; + description: string; + files: string[]; + main: string; + types: string; + engines?: Record; + exports: Record; +}; +const lock = JSON.parse(read('package-lock.json')) as { + version: string; + packages: Record; +}; +const citation = read('CITATION.cff'); +const changelog = read('CHANGELOG.md'); +const readme = read('README.md'); + +describe('project metadata stays in sync', () => { + it('uses one version across package.json, package-lock.json, the ontology, and CITATION.cff', () => { + const citationVersion = citation.match(/^version:\s*(\S+)\s*$/m)?.[1]; + assert.ok(citationVersion, 'CITATION.cff has no version field'); + assert.equal(ontology.version, pkg.version, 'ontology version differs from package.json'); + assert.equal(citationVersion, pkg.version, 'CITATION.cff version differs from package.json'); + assert.equal(lock.version, pkg.version, 'package-lock.json version differs from package.json'); + assert.equal(lock.packages['']?.version, pkg.version, 'package-lock.json root package version differs'); + }); + + it('has a dated CHANGELOG entry for the shipped version', () => { + const escaped = pkg.version.replace(/\./g, '\\.'); + const entry = changelog.match(new RegExp(`^## \\[${escaped}\\] - (\\S+)\\s*$`, 'm')); + assert.ok(entry, `CHANGELOG.md has no entry for ${pkg.version}`); + + const released = citation.match(/^date-released:\s*(\S+)\s*$/m)?.[1]; + assert.equal(released, entry[1], 'CITATION.cff date-released differs from the CHANGELOG date'); + }); + + it('quotes the same atom count in the package, README badge, and citation', () => { + const badgeCount = readme.match(/atoms-(\d+)-/)?.[1]; + const packageCount = pkg.description.match(/(\d+) recurring software elements/)?.[1]; + const citationCount = citation.match(/(\d+) recurring software elements/)?.[1]; + + assert.equal(ontology.elements.length, 115); + assert.equal(Number(badgeCount), ontology.elements.length, 'README atoms badge'); + assert.equal(Number(packageCount), ontology.elements.length, 'package.json description'); + assert.equal(Number(citationCount), ontology.elements.length, 'CITATION.cff abstract'); + }); + + it('does not repeat the withdrawn token-efficiency claim in citation metadata', () => { + assert.doesNotMatch(citation, /token-efficient/i); + }); + + it('ships every file its entry points reference', () => { + // npm always includes package.json regardless of `files`. + const shipped = new Set(pkg.files); + const targets = new Set([pkg.main, pkg.types]); + for (const target of Object.values(pkg.exports)) { + const value = (target as { default?: string })?.default ?? (target as string); + if (typeof value === 'string' && !value.includes('*')) targets.add(value); + } + + for (const target of targets) { + if (target === './package.json') continue; + const topLevel = target.replace(/^\.\//, '').split('/')[0]; + assert.ok(topLevel, `${target} is not a relative path`); + assert.ok(shipped.has(topLevel), `${target} is not covered by package.json "files"`); + } + + assert.ok(pkg.engines?.node, 'package.json does not declare a supported Node range'); + }); + + it('lists every test file in the README test inventory', () => { + const testFiles = fs + .readdirSync(path.join(ROOT, 'test')) + .filter((name) => name.endsWith('.test.ts')) + .sort(); + + for (const file of testFiles) { + assert.ok(readme.includes(`test/${file}`), `README test inventory is missing test/${file}`); + } + }); +}); diff --git a/test/public-api.test.ts b/test/public-api.test.ts index bb6e821..957c6ab 100644 --- a/test/public-api.test.ts +++ b/test/public-api.test.ts @@ -5,6 +5,7 @@ import { describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import { KanbanMeta, type KanbanSpec, materializeKanban } from '../atoms/interfaces/kanban.js'; import { formatTableSummary } from '../composer/prompt.js'; +import * as packageRoot from '../src/index.js'; import { validateSchema } from '../src/jsonschema.js'; import { buildNameIndex, loadOntology, loadOntologySchema, symbolIndex } from '../src/ontology.js'; @@ -51,6 +52,17 @@ describe('public API surface', () => { assert.match(summary, /Pn \(Permission\)/); }); + it('exposes a runtime API at the package root', () => { + // The root export used to be `atoms/core.ts`, which is types only and + // compiles to `export {}`. A consumer importing the package by name got an + // empty namespace, so assert the root entry actually does something. + assert.equal(typeof packageRoot.loadOntology, 'function'); + assert.equal(typeof packageRoot.validateSchema, 'function'); + assert.equal(typeof packageRoot.formatTableSummary, 'function'); + assert.ok(packageRoot.COMPOSITION_SYSTEM_PROMPT.length > 0); + assert.equal(packageRoot.loadOntology().elements.length, 115); + }); + it('exposes atoms with their metadata and behaviour', () => { assert.equal(KanbanMeta.symbol, 'Kb'); assert.equal(KanbanMeta.family, 'interfaces');