Metadata-Version: 2.4
Name: integral-core
Version: 0.1.1
Summary: Integral Foundation (open core) — substrate without commercial Apps
Author: V75 Inc.
License-Expression: Apache-2.0
Keywords: fastapi,jvspatial,project-management,backend
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: FastAPI
Requires-Python: >=3.11.5
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: uv<1,>=0.13.4
Requires-Dist: filelock<5,>=4.2.1
Requires-Dist: psutil<8,>=6
Requires-Dist: fastapi>=0.100.0
Requires-Dist: anyio<5,>=4
Requires-Dist: uvicorn[standard]>=0.23.0
Requires-Dist: pydantic>=2.0
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: python-multipart>=0.0.6
Requires-Dist: passlib[bcrypt]>=1.7.4
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: PyYAML>=6.0.0
Requires-Dist: Jinja2>=3.0
Requires-Dist: croniter>=2.0.0
Requires-Dist: asyncpg>=0.29.0
Requires-Dist: tzdata>=2024.1
Requires-Dist: jvspatial==0.2.10
Requires-Dist: PyJWT>=2.14.0
Requires-Dist: authlib>=1.9.1
Requires-Dist: joserfc>=1.7.6
Requires-Dist: dnspython>=2.9.2
Requires-Dist: opentelemetry-api<2,>=1.45.2
Requires-Dist: pymongo>=4.18.3
Requires-Dist: httpx>=0.24.0
Requires-Dist: aiohttp<4,>=3.14.4
Requires-Dist: reportlab>=4.0.0
Requires-Dist: mcp[cli]<2,>=1.30.0
Requires-Dist: onnxruntime<2,>=1.24.2
Requires-Dist: tokenizers<1,>=0.22
Requires-Dist: huggingface-hub<2,>=1
Requires-Dist: numpy<3,>=2
Requires-Dist: certifi>=2026.10.19
Requires-Dist: sentry-sdk[fastapi]>=2.0.0
Requires-Dist: pynacl>=1.5.0
Requires-Dist: pydantic-ai-harness[skills]==0.59.0
Requires-Dist: pydantic-ai-slim==2.59.0
Requires-Dist: litellm<1.102,>=1.101.0
Requires-Dist: beautifulsoup4<5,>=4.12
Requires-Dist: soupsieve<5,>=4.0
Requires-Dist: markdownify<2,>=0.13
Requires-Dist: openai>=1.0.0
Requires-Dist: python-magic>=0.4.27
Requires-Dist: pdfplumber>=0.10.0
Requires-Dist: pypdf>=6.21.4
Requires-Dist: python-docx>=1.1.0
Requires-Dist: openpyxl>=3.1.0
Requires-Dist: python-pptx>=0.6.21
Requires-Dist: reportlab>=4.0.0
Requires-Dist: Pillow<14,>=13.0.0
Requires-Dist: mutagen>=1.47.0
Requires-Dist: langdetect>=1.0.9
Requires-Dist: markdown-it-py<5,>=4
Provides-Extra: observability
Requires-Dist: opentelemetry-api<2,>=1.45.2; extra == "observability"
Requires-Dist: opentelemetry-sdk<2,>=1.20; extra == "observability"
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.20; extra == "observability"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: httpx>=0.24.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: flake8-annotations>=3.0.0; extra == "dev"
Requires-Dist: flake8-bugbear>=23.0.0; extra == "dev"
Requires-Dist: flake8-comprehensions>=3.14.0; extra == "dev"
Requires-Dist: flake8-docstrings>=1.7.0; extra == "dev"
Requires-Dist: flake8-simplify>=0.21.0; extra == "dev"
Requires-Dist: pep8-naming>=0.13.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: types-PyYAML>=6.0.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Provides-Extra: test
Requires-Dist: opentelemetry-sdk<2,>=1.20; extra == "test"
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
Requires-Dist: pytest-xdist>=3.5.0; extra == "test"
Requires-Dist: httpx>=0.24.0; extra == "test"
Requires-Dist: asgi-lifespan>=1.0.0; extra == "test"
Dynamic: license-file

# Integral backend

The backend provides the domain-neutral graph substrate, access model, schema and App lifecycle, resident perimeter, and public API. It uses jvspatial with FastAPI; routes, validation schemas, services, Nodes, and Edges follow the repository's object-spatial conventions.

## Local launcher

An installed wheel with the built UI supports `integral up`, `status`, `logs`, `stop`, `backup`, `restore` and `upgrade`. The launcher runs PostgreSQL in an isolated Python 3.12 helper environment and serves the workspace with real auth on loopback. `integral up --profile desktop_single_user` selects the persisted profile for a new managed installation; existing installations remain on their recorded profile and require a reviewed migration to change. See [local installation](../docs/ops/LOCAL_INSTALLATION.md). The Integral One desktop host owns Electron and its installers; Core contains no Electron or commercial App imports.

## Develop

```bash
uv sync --frozen --extra dev --extra test
.venv/bin/python -m app.main
```

Run from this directory with private development settings configured. Python 3.11.5 or later is required (the patched Soup Sieve HTML selector dependency requires this minimum). The source API uses port 4000. The frozen lock is authoritative; do not substitute requirements.txt or unrestricted package-index resolution.

## Navigate

`api/` handles transport, `schemas/` holds typed input/output, `models/` declares graph participants and edges, `services/` owns canonical mutations and lifecycle, and `agentive/` supplies harness bindings, MCP, skills, staging, and work. Domain packages remain behind public facade contracts.

The agentive layer always loads. Default resident binding is Integral AI through Pydantic AI; Integral AI is the only resident harness. Core-only filtering removes domain packages from catalog admission, not the resident layer.

Use the [backend reference](../docs/backend/README.md), [architecture](../docs/product/ARCHITECTURE.md), [invariants](../docs/INVARIANTS.md), and [deployment guide](../docs/ops/DEPLOY.md).

## Search and indexing

PostgreSQL uses durable indexing jobs and local text-only ONNX/pgvector passages.
Canonical writes enqueue work; readiness includes the actual encoder, store and
current-source coverage. `EMBEDDING_STORE_DRIVER=null` selects graph-only reads.
See [declarative indexing and retrieval](../docs/backend/semantic-indexing.md)
for deployment settings, rebuilds, API scope and real-database qualification.
The legacy `backfill_embeddings.py` script fills the older single-vector
adapter and does not populate the passage index.

## Request liveness

Keep file I/O, package validation, schema compilation and document/image
processing off the API event loop. Only pure work belongs in worker threads;
graph operations and transactions remain in their owning task. Reuse one
validated source snapshot per operation, coalesce concurrent reads, and retain
fresh authorization checks. See [I-RUNTIME-01](../docs/INVARIANTS.md#i-runtime-01--bounded-repeated-work).

Package imports read manifests without unpacking arbitrary ZIP contents. Limits
are 50 MiB uploaded/expanded, 4096 ZIP members, 128 packages and 10 MiB per
manifest. Deep or expanded YAML alias structures are rejected before compiler
hashing. These parsing limits do not grant package publication authority.

## jvspatial security compatibility

Metadata pins jvspatial 0.2.10 and pydantic-ai-harness 0.59.0. Runtime dependencies resolve from PyPI. Production OAuth requires its encryption key, and production auth rate limits stay active. Repair duplicate model credentials before creating their unique index and test actual PostgreSQL duplicates.

PostgreSQL account creation and admin/profile/workspace bootstrap serialize
across serving processes and commit together. Ambiguous legacy account emails
or bootstrap profiles require an explicit, data-preserving operator review;
startup never selects or deletes a duplicate. See the
[concurrent-bootstrap recovery procedure](../docs/ops/DEPLOY.md#concurrent-account-bootstrap-and-existing-duplicates).

PostgreSQL token validation coalesces the advisory `last_accessed` timestamp
within one minute. It still locks and checks the current identity row on every
validation, rereads current account authority and checks token revocation. A
pending account disable retains its existing lock fence. Credential/role writes,
explicit saves, expiry and refresh semantics are unchanged. The focused gate is
`tests/contract/test_authentication_current_state_postgres.py`; this optimization
does not cache an authentication or authorization decision.

PostgreSQL token validation coalesces the advisory `last_accessed` timestamp
within one minute. It still locks and checks the current identity row on every
validation, rereads current account authority and checks token revocation. A
pending account disable retains its existing lock fence. Credential/role writes,
explicit saves, expiry and refresh semantics are unchanged. The focused gate is
`tests/contract/test_authentication_current_state_postgres.py`; this optimization
does not cache an authentication or authorization decision.

`make verify` from the repository root is the broad local gate. PR smoke CI is narrower and runs without a developer .env. Database contracts and packaged-wheel checks provide separate evidence.

The broad gate runs the complete default backend suite once under CI conditions
(`TESTING=1`, `DEBUG=false`, no dotenv), including its smoke tests. It uses at
most four xdist workers, grouped by file, and preserves per-test database
isolation. `make verify-ci` runs the smoke subset separately for a shorter
feedback loop; `make verify-pr` also retains the independent contract and
PostgreSQL lanes. Plain `pytest` remains serial.

Use `make test-backend PYTEST_WORKERS=0` for serial debugging. Override
`PYTEST_MAX_WORKERS` to tune the cap after measurement. The root backend and
smoke targets print the slowest 25 test phases and save JUnit timings in
`backend/.pytest_cache/verification/{backend,smoke}.xml` (ignored). These reports
include setup and teardown time; compare identical selections and environments,
and distinguish summed test time from elapsed parallel run time. Do not reduce
coverage or replace real database tests to meet a timing target.

The contract lane uses two workers with per-test work stealing, so a large App
contract file can be shared instead of becoming a serial tail. Set
`CONTRACT_TEST_WORKERS=0` for its serial baseline. `make test-postgres-ci` is
also the CI graph/transaction command: it uses two independent worker databases,
prime/log pools of one to three connections each, and separate JUnit reports
for spikes, contracts, App jobs and authority. Set `POSTGRES_TEST_WORKERS=0`
for serial comparison. Run separate PostgreSQL invocations sequentially on a
shared local service: the fixture recreates its fixed per-worker test databases.
The real encoder/pgvector lane stays serial and separate from these graph tests.

Frontend tests cap workers at the smaller of four and the runner's available
CPUs; the Vitest `--maxWorkers` option supports controlled comparisons. CI runs
`npm run lint:types` once, then `npm run build:assets`. Standalone `npm run build`
continues to check types and build assets together.
`make test-frontend` is shared with CI and writes JUnit timings to ignored
`frontend/node_modules/.cache/verification/frontend.xml`. CI retains that
report alongside the contract and PostgreSQL artifacts and prints the available
CPU/worker budget.

Successful database operations, including slow calls, do not emit log records.
Metrics and slow-call counters remain available; failed operations emit
structured ERROR records from jvspatial.


### Managed desktop owner profile

`integral up --profile desktop_single_user` creates a new installation for one
OS user. Profile changes require a reviewed migration; use a fresh home for a
new desktop installation. The runtime passes the installation identity,
controller secret and exact web origin as controlled startup settings. They
must never come from request headers, package manifests or browser detection.

Core atomically creates the owner AuthUser, rooted User and private workspace
on PostgreSQL at startup and refuses incompatible stores. Electron main obtains
signed owner sessions through the possession-protected `/api/auth/local-session`
endpoint. Browser Origin/fetch headers are refused on that endpoint; ordinary
signup/password login and additional users are closed in this profile.
`/api/meta/deployment` publishes read-only feature capabilities. HTTP/WS Host and
Origin checks, canonical policy and grant services enforce the same restrictions
on collaboration/public links/ownership transfer. Server defaults are retained.

The private `integral-apps/` directory is discoverable independently of the
single-owner restriction. Commercial entitlements, approval requirements,
package trust and App data export retain their existing generic contracts.
See `docs/INVARIANTS.md` I-DESKTOP-01 and the desktop engineering evidence under
`tasks/phase-one/evidence/` in the repository root. Licensing clearance and native
installer release qualification are separate gates.

### Desktop runtime qualification

Prepare portable resident assets with `.ci/bundle_resident_harness.sh` from the
repository root before building the Core wheel, following `RELEASING.md`. The
desktop bundler requires `desktop_assets_available` and desktop contract version
1. Its ready probe waits for completed startup and registered audit storage;
root `/health` alone does not qualify a desktop runtime.

### Governed-read performance qualification

The scale fixture in `tests/test_scale_query_benchmark.py` uses an isolated
PostgreSQL test database, independent 50,000/100,000 Entry populations with
containment edges, and a known
record oracle. Run it separately from competing test suites with
`INTEGRAL_TEST_DB=postgres`, `INTEGRAL_TEST_POSTGRES_DSN` pointing to a disposable
service, and `INTEGRAL_RUN_SLOW_TESTS=1`. Select it explicitly with
`pytest tests/test_scale_query_benchmark.py -m slow -s`; the default marker
selection excludes slow tests. It fingerprints the runtime sources,
configuration and fixture so edits during a run invalidate its evidence.
Selective lookup, record pages, governed pages, counts and digests collect 20
samples per cell; keyword lookup collects five. These are regression signals,
not hosted release p95 qualification. A mathematically impossible passing cell
fails early without presenting partial observations as a passing percentile.
The 50K budgets remain fixed; 100K uses separate linear-work diagnostic ceilings.
Mixed-permission checks cover exclusions, direct Entry grants, cross-workspace
denial and live revocation through services, governed queries, SDK, MCP, HTTP and
resident result projection. They do not qualify a hosted model conversation.
The optional disabled-pushdown comparator runs independently and cannot alter
the native cells. Missing request measurements fail the query-budget test.

Counts use fresh authority metadata rather than presentation payloads. Keyword
candidates can be narrowed before hydration; the canonical matcher and graph
admission still decide results. The bounded Unicode candidate derivation is
coalesced and offloaded from asynchronous request handling. It introduces no
embedding dependency and does not replace ranked hybrid search.

Direct Entry grants participate in workspace-wide reads and rollups even when
the parent Track is unreadable. Those rollups use a neutral source label and
omit Track navigation, keeping private parent names out of the result.

Core's session-mode PostgreSQL graph connections use the standard startup
option `plan_cache_mode=force_custom_plan` to avoid repeated parameterized-read
latency cliffs across uneven populations. This trades planning CPU for stable
execution latency; qualify it on the deployment workload. Set
`INTEGRAL_POSTGRES_PLAN_CACHE_MODE=auto` to restore PostgreSQL's adaptive choice.
Explicit DSN `options` or `plan_cache_mode` take precedence, including options
unrelated to planning. Transaction-pooler mode keeps its existing driver behavior
and receives no additional session startup option.

## Event worker

Run `integral worker events` beside the API to deliver durable audit facts and committed chat-message invalidations to each API process. See [the worker contract](../docs/backend/event-worker.md) for configuration, recovery and performance qualification.

### Link preview outbound connections

The authenticated link-preview endpoint follows at most five redirects. Each
HTTP or HTTPS connection resolves and validates all destination addresses, then
connects directly to a validated numeric address. Private, loopback, link-local,
mixed public/private, empty and malformed answers are refused. HTTPS keeps the
original hostname for SNI and certificate verification. Link previews do not
modify the process-wide DNS resolver or use environment HTTP proxies; deployments
that require an outbound proxy must leave previews unavailable until a proxy with
an equivalent destination-validation contract is supported. Operator-trusted
internal MCP/model hosts do not grant link-preview access to private addresses.
This change requires no stored-data migration.


## Saved signature recovery

Core's personal signature vault stores and roots a replacement before retiring
its previous attachment. PostgreSQL serializes replacements/deletes for one
profile and commits the graph swap and file-cleanup intent together; an aborted
transaction retains the original signature. Local development stores serialize
writes but do not claim PostgreSQL rollback or distributed ordering.

`integral worker events` retries retired signature-file cleanup after commit.
A live or restored attachment prevents deletion; provider failures retain pending
intent. Cleanup has a bounded pass budget and never removes the replacement's
file. Keep the worker running, preserve backups and reconcile stale cleanup facts
before an operator restores a retired attachment. Conflicting current signature
edges require review; Core does not arbitrarily delete or merge them. Additive
cleanup-status indexing participates in the existing reviewed storage-upgrade
plan; follow the [offline migration and recovery guide](../docs/ops/NATIVE-STORAGE-UPGRADES.md)
for managed stores rather than resetting data. An uncommitted new binary can
remain after an outer caller aborts; reconcile unreferenced uploads from a backup
copy rather than deleting files by filename alone.
