Metadata-Version: 2.4
Name: leadflow
Version: 1.1.3
Summary: FoundrySuite - local-first AI lead generation, sales pipeline and double-entry accounting
License: Proprietary
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.136.1
Requires-Dist: uvicorn>=0.47
Requires-Dist: sqlalchemy>=2.0.49
Requires-Dist: pydantic>=2.13.4
Requires-Dist: email-validator>=2.3.0
Requires-Dist: httpx>=0.28.1
Requires-Dist: cryptography>=44
Requires-Dist: python-multipart>=0.0.31
Requires-Dist: jinja2>=3.1.6
Requires-Dist: numpy>=1.26
Requires-Dist: py-lead-generation>=1.0.1
Requires-Dist: playwright>=1.44
Requires-Dist: starlette>=1.3.1
Provides-Extra: llm
Requires-Dist: llama-cpp-python>=0.3.35; extra == "llm"
Provides-Extra: embeddings
Requires-Dist: sentence-transformers>=3.0; extra == "embeddings"
Requires-Dist: torch>=2.2; extra == "embeddings"
Provides-Extra: ocr
Requires-Dist: rapidocr-onnxruntime>=1.3.19; extra == "ocr"
Requires-Dist: pypdf>=4.0; extra == "ocr"
Requires-Dist: pypdfium2>=4.0; extra == "ocr"
Provides-Extra: discovery
Requires-Dist: ddgs>=9.0; extra == "discovery"
Provides-Extra: parse
Requires-Dist: beautifulsoup4>=4.12; extra == "parse"
Requires-Dist: lxml>=5.3.0; extra == "parse"
Provides-Extra: desktop
Requires-Dist: pywebview>=5.0; extra == "desktop"

# FoundrySuite

Local-first AI lead generation, sales pipeline, and double-entry bookkeeping.

FoundrySuite runs entirely on your own computer. There is no account to create, no
subscription, and no data leaving the machine: the language model, the document
reader, the search index and the database are all local. The only things that
can reach the internet are your own web research, when you ask it to look a
company up, and the one-off download of about 5.7 GB of AI weights — which is
never fetched without asking. That download offers a box per model, so you can
take the language model, the OCR pair, or both off the list, and point at a
model file of your own instead. Opting out is remembered as a setting in your
own data directory, never as a record of you, and is undone from Settings →
Model files or with `leadflow models --opt-out none`.

---

## Install

**Windows** — double-click `install.bat` once, then `Launch FoundrySuite.bat`.
**macOS** — double-click `Launch FoundrySuite.command` (it installs on first run).
**Linux** — run `./install.sh`, then `./Launch FoundrySuite.sh`.

The installer creates a private Python environment inside the FoundrySuite folder.
Nothing is installed system-wide. It takes a few minutes the first time and
nothing at all afterwards.

Check your machine any time with:

```
leadflow doctor
```

It reports honestly what is installed and what is not. Optional components
(semantic search, the scanned-document reader) can be missing; FoundrySuite starts
without them and says which feature is unavailable rather than pretending.

## Run

Double-click the launcher, or:

```
leadflow
```

A browser opens at <http://127.0.0.1:24317>. Create an account on the first
screen — that is the whole setup.

Your data lives in the OS-standard per-user directory
(`~/.local/share/foundrysuite` on Linux, `~/Library/Application Support/
FoundrySuite` on macOS, `%LOCALAPPDATA%\FoundrySuite` on Windows): the SQLite
database, your uploaded files, and logs. Copying that folder is a complete
backup. A `.portable` marker beside the app opts into bundle-local `data/`
instead (see `leadflow/config.py:user_data_dir()`).

On a single machine that address is right, and nothing needs configuring: the
browser talks to `127.0.0.1`, which never leaves the computer. To reach FoundrySuite
from other machines — an office, or staff working from home — read
[Deploying FoundrySuite safely](docs/DEPLOYMENT.md) first.

---

## What it does

### Finding leads
Describe who you sell to. FoundrySuite searches for companies that match, reads
their websites, and pulls out what it can actually verify — industry, headcount,
location, contact details, the technologies they run. Every value carries the URL
it came from.

Duplicate companies are recognised by domain, so the same organization never
appears twice no matter how many searches surface it.

### Knowing which leads are worth your time
Scoring is deterministic: a set of criteria you control, evaluated against real
facts, producing the same number every time with a written explanation of where
every point came from. The local model produces a second, independent opinion
beside it. Neither one changes a lead's status — that stays your decision.

### Acting on them
The model reads the research and drafts outreach, suggests the next concrete
step, and summarises what happened. Everything it produces is a draft for you to
edit. There is no send button, because sending mail is your call, not the
software's.

### Keeping books
A real double-entry ledger is the authoritative record. Invoices, bills, payments
and expenses generate journal entries; the ledger is what is actually true.

- Every posted entry balances to the cent. The engine refuses to post one that does not.
- Posted entries are immutable. A mistake is corrected with a reversing entry and a new one, so the history of what you believed and when stays intact.
- Money is stored as integer minor units, never as a floating-point number, so totals never drift.
- Closed accounting periods reject postings. Reopening one is an audited action.
- Trial balance, balance sheet, income statement and cash flow are all derived from the same ledger and always agree.
- Accounts receivable and accounts payable are real subledgers: an invoice and a payment against it change the balance, and over-applying a payment is refused.

### Reading documents
Drop in a PDF or a scan. Text is extracted locally — an embedded text layer
first, then a local vision model, then a local OCR engine as a fallback. The
model then reads it: what kind of document it is, what it says, and the fields
printed on it, ready to file against an invoice, a bill or an expense.

---

## How it is put together

```
leadflow/
  config.py          settings, model discovery, paths
  core/              errors, security, normalisation, pagination, logging
  db/                SQLAlchemy models (50 tables), migrations, seed data
  ai/                in-process model runtime, grammar-constrained contracts
  embeddings/        local semantic search
  documents/         content-addressed storage, OCR engine, structuring
  web/               SSRF-safe fetcher, robots.txt, HTML extraction
  discovery/         search-engine providers
  enrichment/        website enrichment providers
  services/          CRM, leads, scoring, pipeline, campaigns, search, auth
  accounting/        journal engine, periods, chart, ledger, subledgers,
                     banking, expenses, reports, audit
  jobs/              database-backed queue, worker, handlers
  api/               FastAPI app, dependencies, routes
  webapp/            the interface (vanilla ES modules, no build step)
```

**The model runs in-process.** `llama-cpp-python` loads Granite 4.2 directly
into the application when it starts. There is no inference server to install,
start, or leave running, and no port for it to occupy.

**Structured output is grammar-constrained.** Every AI operation declares a
Pydantic contract, and that contract is compiled to a GBNF grammar the sampler
must satisfy. The model cannot return malformed JSON, because the grammar makes
that unrepresentable.

**Deterministic where it must be.** The model qualifies, summarises and drafts.
It does not score, post, approve, or decide. Anything that affects money or a
customer's fate is computed by rules and confirmed by a person.

**Every fact has a provenance.** Automated data never overwrites something a
human typed, at any confidence. The merge policy is four rules, and the UI shows
you which rule applied and lets you correct the value.

**Outbound web requests are untrusted input.** Every URL is resolved and checked
against private address space on every redirect hop, robots.txt is respected, and
fetched page content is treated as data — never as instructions.

---

## Security

**The local database is the authority.** AI proposes, deterministic rules
validate, and only an authorized workflow posts. A posted journal entry always
balances — debits equal credits, to the cent — and a posted entry is never
edited. A mistake is corrected with a reversing entry and a new one, because
the history of what was believed when is itself part of the record.

**Sessions are HttpOnly, SameSite, CSRF-checked, and tenant-bound.** The
workspace is read from the session row and never from a URL or a request body,
so asking for another organization's records by changing an identifier is not a
mistake the code is willing to make. State-changing requests need a CSRF token
that is checked inside the authentication dependency, so a new route cannot
forget the check by not remembering to add it.

**HTTPS is the default for anything reachable from the network.** On a single
machine, plain HTTP to `127.0.0.1` is correct — there is no wire to intercept.
The moment FoundrySuite is bound to a network interface, HTTPS becomes mandatory:
the session cookie is marked `Secure`, plaintext requests are redirected with a
307 that keeps the method and the session intact, HSTS is sent, and if none of
that is configured, **FoundrySuite refuses to start** and says why. It can be
overridden with `LEADFLOW_ALLOW_INSECURE_LAN=1`, which prints a warning on every
launch — the insecure state is reachable on purpose, never by accident.

**A VPN is an additional boundary, not a substitute.** A VPN decides who can
reach the host; TLS decides what they can read once they have. A VPN user
connected to a plaintext FoundrySuite is still sending a session cookie in clear
text, and anything on the same LAN can reach the port without the VPN at all.
Use both. See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md).

**Getting past the front door is the other half of being safe to expose.**
TLS protects traffic that is already authenticated. On a machine you control
that is enough; on a machine half a dozen people can reach, it is not. So
creating an account is open — the first account on a machine registers with
no code, which is what keeps "download, double-click, type your email"
working for someone who will never read a deployment guide, and so does the
second, which gets a workspace of its own and sees nothing of anybody else's.
**A code is how somebody joins a team**, and on a shared machine it is what
the operator can require before anybody may register at all. A code that is
offered is always redeemed, so a mistyped one is refused rather than quietly
ignored, and a refused attempt leaves nothing behind: every rejection of a
code that was *given* returns the same message, so nobody can probe for codes
that exist.

Codes grant **access, not entitlement**. A team invitation adds a person to
your workspace; a machine invitation lets someone new set up their own first
workspace. Neither creates a license or a seat, and FoundrySuite has no seat
counting — configure the installation however you like. Codes are shown once
and only a hash is stored, so a lost code cannot be recovered; issue a new one.

**Signing in is throttled by the server, per address and per account.** Wrong
passwords trigger a lockout that doubles on each further attempt, and the
limiter's bucket is chosen from the route being called — a client cannot put
itself in a roomier one. Keying on the address *and* the account together, not
the address alone, is deliberate: throttling a whole office by IP means one
person's typo locks out their colleagues. The lockout lives in memory and
disappears when the process stops, because a lockout that outlived a restart
would be a way to keep a legitimate owner out of their own machine.

**The API surface is closed to the anonymous.** `/api/docs` and
`/api/openapi.json` require a signed-in session, filesystem paths in
`/api/system/config` are returned to owners only, and each machine carries a
random install ID recording the version it was created with — a support and
billing handle for a per-workstation sale, not a license, and it gates
nothing.

`leadflow doctor` reports the transport posture, the access policy and the
install identity it actually resolved, rather than assuming the ones you
intended.

---

## Staying up to date

FoundrySuite never phones home on its own: there is no background update
check, no timer, and no telemetry. An update is fetched and applied only when
you explicitly choose it, from **Settings → System Updates**. Two paths exist:

- **Check for Updates** — downloads a signed `.fspatch` patch from the release
  manifest, verifies its Ed25519 signature and SHA-256 hashes, backs up the
  database, applies the patch, and prompts you to restart.
- **Apply Offline Update (.fspatch)** — uploads a `.fspatch` file you obtained
  elsewhere (browser download, USB) and runs the exact same verification,
  backup, and atomic-apply pipeline without touching the network.

Every applied update is rolled back automatically if any file operation fails,
and a pre-update database backup is kept under `<data_dir>/backups/`. The
release and patch tooling is `scripts/build_update_patch.py`; the operational
guide is `docs/UPDATES_AND_PATCHING.md`.

## Command line

| Command | What it does |
|---|---|
| `leadflow` | Start the app and open a browser |
| `leadflow doctor` | Report what is installed and what is missing |
| `leadflow worker` | Run the background worker on its own |
| `leadflow backup` | Write a consistent copy of the database now |
| `leadflow create-account EMAIL` | Create an account without a browser |
| `leadflow reset-password EMAIL` | Set a new password |
| `leadflow reset` | Delete the database and start over |

Every command takes `--help`.

---

## Tests

```
python3 -m pytest tests/ -q
```

The suite runs against a real migrated SQLite database and the real services.
No mocks, no fake model responses, no asserted-on-placeholder tests — a test
that passes because it agreed with a stub is worse than no test at all.

---

## Requirements

Python 3.11 or newer, about 4 GB of free disk space, and 8 GB of RAM minimum
(16 GB recommended for comfortable local inference). No GPU is required; the
model runs on the CPU.
