# DataReel 7: AGENTS.md and AI guides in one file

Generated by docs/bin/make_ai_docs.py from AGENTS.md and docs/ai/*.md.

========================================================================
FILE: AGENTS.md
========================================================================

# DataReel 7: AI-assisted setup, builds, upgrades, forks and support

This file is for AI-assisted work with DataReel 7, the C++ object
database (OODB) and TLS communications library. It tells an AI agent
(Gemini CLI, Claude Code, GitHub Copilot, Codex and others) how to
assist a site's own developers and system administrators to set up
DataReel, build it and programs that use it, upgrade from older
releases, maintain a fork, and troubleshoot. The agent assists; it does
not replace the developers, the administrators or DataReel support, and
it never acts autonomously (section 0). The people review and approve
every step, and problems the agent cannot solve go to DataReel
(section 7.4). `GEMINI.md` and `CLAUDE.md` in this folder only import
this file.

The task guides with complete programs are in `docs/ai/`, and
`llms-full.txt` has this file and every guide in one file. The full
documentation is `README.txt`, the release notes, `docs/classes/` and
https://datareel.com/clib7/. This file points to them instead of
repeating them. When this file and the code disagree, the code wins:
say so to the person you work for.

DataReel 7.4.1 is the main, fully supported release. DataReel 6.4.2 is
the legacy release: bug fixes and security updates only, no new
features (it has its own `AGENTS.md`).

## Before you use AI assistance

**Review all of your agency's or company's AI usage policies, and get formal
written approval from your management team, in the form of a business use
case and justification, before you use any AI assistance with DataReel.**
AI desktops and command line tools may be used with this guide only in
strict compliance with those policies and that approval.

- **Use only approved enterprise AI models.** An AI agent working on
  source code or a server may process potentially sensitive data: source
  code, database files, configuration files, certificates, logs and
  command output. Use only your agency's or company's enterprise AI
  models that have built-in safeguards against disclosing information
  and that guarantee your internal information will not be used to
  train public models.
- **Warning: public or free AI tools, open source AI models and self-built
  AI models** may expose your information to public learning models or to
  other parties, depending on how the model is hosted, configured and
  licensed. Use them only after a comprehensive review of what information
  might be exposed and what the potential risks are.
- The entire risk of AI-assisted use rests solely with the user. DataReel
  Software Development cannot be held accountable for actions taken,
  commands run, code changed, information exposed or other outcomes of AI
  assistance (see https://datareel.com/terms.php#ai-assisted).
- **No endorsement.** Any mention of a specific AI tool, model or product
  in this guide, such as Gemini, Gemini CLI, Claude Code or GitHub Copilot,
  is a reference only. It is not an endorsement or a recommendation to use
  that product. Product names are trademarks of their respective owners.
- DataReel's AI-assisted guides send nothing to DataReel. Anything given
  to an AI tool goes to that tool's provider, under the provider's terms
  and your organization's policies (https://datareel.com/privacy.php#ai-assisted).

**For the agent:** at the start of a session, ask the person to confirm
that this AI-assisted use is approved under their organization's AI usage
policy and that you are an approved enterprise AI model. If they cannot
confirm it, stop and do not ask for or read any of their code, data files
or system output.

## 0. Human in the loop: the agent never acts on its own

AI-assisted means the agent assists a person; it never acts
autonomously. Every change to code, a build, a server or a database file
is made by a person or explicitly approved by one, one step at a time.

- **Advisory mode is the default.** The agent explains the next step and
  prints the exact command or code change and where it applies. The
  person runs or applies it and pastes the output back. Use this mode
  unless the organization allows the agent to run tools or edit files.
- **If tool execution or file editing is allowed,** each command and each
  change still needs its own explicit approval before it runs. Never use
  auto-approve modes: no Gemini CLI `--yolo` or auto-accept, no Claude
  Code permission bypass (`--dangerously-skip-permissions`, bypass mode),
  no auto-run in other agents.
- **No unattended work:** no scheduled, background, batch or scripted
  runs of changing commands, no loops over servers or database files, and
  no commits, tags or pushes unless the person asks for that exact step.
- **Read-only checks first.** The agent may propose read-only checks
  (section 7.1) before anything else; they are shown and approved the
  same way.

**Works with strict AI policies.** These files contain no code that runs
by itself: `AGENTS.md`, `GEMINI.md`, `CLAUDE.md`, `llms.txt`,
`llms-full.txt` and `docs/ai/` are text. Everything in this guide works
in advisory mode, with no tool execution by the agent.

## 1. Rules for agents (read these first)

DataReel database files hold an application's data, and its TLS classes
protect its network traffic. A wrong step can lose data, make files
unreadable by the programs that use them, or weaken security. Follow
these rules on every task:

1. **Show, then the person runs or approves it.** Before any command that
   changes something (installing packages, `cmake --install`, writing or
   repairing a database file, editing code, committing), show the command
   or the change. In advisory mode the person runs it; otherwise wait for
   an explicit yes for that one step (section 0).
2. **Back up data before changing it.** Copy every database file (`.gxd`
   data files, `.btx` B-tree indexes, `.vix` vector indexes, journals)
   into a dated backup folder before an upgrade, a repair or a test
   against real data. Never delete; move aside. Work on copies when you
   can.
3. **Never change the file format settings of an existing project.**
   `DATAREEL_64BIT_DATABASE` and `DATAREEL_NATIVE_TYPES` must match the
   settings that wrote the files (section 4.3). Changing either one makes
   existing files unreadable by that build.
4. **Stop on any failed check.** If a build, a test or a check fails, or
   the output is not what this guide says to expect, stop and report. Do
   not improvise a fix on production data or a production server.
5. **Never weaken security to make something work.** Do not turn off
   certificate verification (`SetVerifyPeer(false)` is for tests only),
   add plain text protocols, remove length checks, or ignore a checksum
   or CRC error.
6. **Read-only first.** Start every task with read-only checks: the
   version (`version.txt`), the build options in `CMakeCache.txt`,
   `db_debug` and `ix_debug` on copies of the files, `dr_digest`, the
   test results (section 7.1).
7. **No secrets or site data in files you write** (passwords, private
   keys, certificates' keys, host names, addresses, customer data), unless
   the person asks for that file on their own systems.
8. **Keep a log.** List each command you ran or proposed, where, and its
   result, and give it to the person at the end (section 8).

## 2. What DataReel 7 is

DataReel 7 is an object database (OODB) and cross platform
communications toolkit for C++17, for two jobs the C++ standard library
does not cover:

1. **An embedded object database**: block files with free space reuse
   and CRCs (`gxDatabase`), disk B-tree indexes (`gxBtree`), a data file
   plus its indexes opened together (`POD`), persistent objects with
   variable length members (`InfoHog`), crash safe journals
   (`gxdJournal`), vector indexes with exact and HNSW nearest-neighbor
   search (`gxVectorIndex`, 7.4) and object replication (`gxObjRepl`).
2. **TLS communications**: TLS 1.2/1.3 client and server connections
   (`gxsTLSConnection`, `gxsTLSServer`) and HTTPS, SMTP, POP3, FTPS and
   database-block (`gxStream`) protocols on top of them.

For anything else (strings, containers, threads, files, time, JSON,
SQL) use the C++ standard library or a dedicated library (an embedded
SQL database for relational tables). DataReel 7 removed its old string,
list, thread and file classes.

It runs on Linux (RHEL 8, 9 and 10 and compatible systems, GCC 8 or
later) and Windows (Visual Studio 2022 or later, Schannel or OpenSSL).
It is free software under the GNU Lesser General Public License version
3 or later (`LICENSE`), provided as is.

## 3. Setup: download and install a release

Manual: `README.txt` and `docs/ai/building.md`.

1. Download the release from
   https://datareel.com/downloads/datareel7_downloads.php: the source
   (`datareel-7.4.tar.gz` or `datareel-7.4.zip`) or, on Windows, a prebuilt
   static library (`datareel-7.4-windows-x64-schannel.zip`, 64-bit
   database engine, or `-x86-schannel.zip`, 32-bit engine), each with its
   `.sha256sum` file.
2. Check it before unpacking, and stop if it fails:
   `sha256sum -c datareel-7.4.tar.gz.sha256sum` (Linux) or
   `Get-FileHash datareel-7.4.zip -Algorithm SHA256` compared with the
   `.sha256sum` file (Windows PowerShell).
3. Install the build tools: on RHEL `dnf install gcc-c++ cmake
   openssl-devel` (the person runs it, as root or with sudo); on Windows
   Visual Studio 2022 or later with the C++ workload and CMake.
4. Decide the two file format settings once for the project, before any
   data file is written (section 4.3), and write them down with the
   project.
5. Build, test and install as in section 4.1. Install into a prefix the
   person chooses (`/usr/local` by default, or a project folder).

## 4. New builds

### 4.1 Build and test the library

```sh
cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release
cmake --build cmake-build -j
tests/run_tests.sh cmake-build                    # every check must pass
sudo cmake --install cmake-build                  # optional, /usr/local
```

- Windows: `cmake -S . -B cmake-build -G "Visual Studio 17 2022" -A x64`
  then `cmake --build cmake-build --config Release`. Schannel is the
  default TLS backend; `-DDATAREEL_SSL=OPENSSL` selects OpenSSL.
- Without CMake (Linux), `build/makefile` builds `lib/libdatareel.a`;
  copy the compile flags from `env/linux.env`.
- The options, the test script and the examples are in
  `docs/ai/building.md`.

### 4.2 Rules when writing code that uses DataReel

- Include the class header (`gxstls.h`, `gxshttpc.h`, `gxdbase.h`,
  `pod.h`, `infohog.h`, ...). Everything is in
  `namespace datareel`; `using namespace datareel;` is added by the
  headers unless `DATAREEL_NO_GLOBAL_NAMES` is defined.
- Link with CMake: `find_package(DataReel 7 REQUIRED)` and
  `target_link_libraries(app PRIVATE DataReel::datareel)`. The target
  carries required compile definitions; do not compile DataReel
  headers without them (you get "You must define a target platform").
- Return values differ by area. Check each one:
  - Network classes (`Connect`, `Listen`, `Accept`, `Login`, `Get`,
    ...) return `0` on success and `-1` on failure, with the message
    in `Error()`. `ReadLine()` returns `bool`.
  - `gxDatabase`, `gxBtree::Create/Open` and `POD::Open` return
    `gxDatabaseError`;
    `gxDBASE_NO_ERROR` (0) is success. Get text with
    `DatabaseExceptionMessage()` or `gxDatabaseExceptionMessage(err)`.
  - `gxBtree::Insert/Find/Delete/FindFirst/FindNext`, `InfoHog`
    `WriteObject/ReadObject/FindObject/DeleteObject` return non-zero
    (true) on success.
  - `gxStream` functions return `gxSOCKET_NO_ERROR` (0) on success.
- TLS: certificates are verified against the system store and the
  host name by default. For a private CA call `SetCAFile("ca.pem")`.
  Only use `SetVerifyPeer(false)` in tests. There is no plain text
  HTTP, SMTP, POP3 or FTP; do not try to add it. Only telnet and ping
  are plain text, for diagnostics.
- Records and keys are written as raw bytes. Use fixed-size members:
  `char name[N]`, `gxINT32`, `gxUINT32`, `gxINT64`, `gxFLOAT64`,
  `CDate`, `FAU`. Never store pointers, `std::string`, `std::vector`
  or classes with virtual functions in a record or key. `memset` a
  record to zero before filling it so padding bytes are not random.
- Key classes derive from `DatabaseKeyB`, pass the key data address to
  the base constructor, and implement `KeySize()` and
  `CompareKey()` (the CMake build defines `__USE_SINGLE_COMPARE__`).
  Also define `operator==` and `operator>` so the class works without
  that macro.
- `gxDatabase` objects are not copyable and one object must not be
  used from several threads at once without your own mutex.
- Object addresses (`FAU_t`) returned by `Alloc()` stay valid until
  the object is deleted; store them in your index keys.
- `Flush()` does not reach the disk; `Sync()` does. For writes that
  must survive a crash or power loss, put the data file and its
  indexes under one `gxdJournal` (gxdjrnl.h): `Open()` the journal
  before the files, `Attach()` them, `Begin()`/`Commit()` each batch,
  `Close()` the journal before the files. Without it a crash can leave
  part of a batch, and a cached B-tree can lose keys.

### 4.3 File format settings

File layout depends on `DATAREEL_64BIT_DATABASE` (32-bit and 64-bit
engine files are not interchangeable). `DATAREEL_NATIVE_TYPES=OFF`
changes only the in-memory types of the gx integer and float classes:
the library's files and the wire use the same canonical layout with ON
or OFF, on Linux and Windows (7.4). Records you write as raw bytes that
hold gx types differ in size between ON and OFF builds; use `int32_t`
and the other fixed-size types in them. Build the library, its tools
and every program that opens the same files with the same two settings.

### 4.4 Rules when changing DataReel itself

- C++17 minimum (RHEL 8 has GCC 8). Keep the `gx` class names and the
  `datareel` namespace.
- Never change the on-disk format: block and file headers, B-tree
  nodes, `InfoHog` record layout, CRC tables, or the
  `gxDatabaseError` values (removed codes stay as reserved slots).
  DataReel 7 writes byte-identical files to 6.2; keep it that way.
- Treat every length and count read from a file or the network as
  untrusted: check it against the buffer or a limit before use.
- New network code uses `gxsTLSConnection`; do not add plain text
  protocols.
- Build and test before committing:

```sh
cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release
cmake --build cmake-build -j
tests/run_tests.sh cmake-build
# the test matrix (7.4): 64-bit ON (above), 64-bit OFF with the objrepl
# suites, 32-bit ON and OFF build with 0 warnings plus run_tests
cmake -S . -B /tmp/dr-off -DDATAREEL_64BIT_DATABASE=ON -DDATAREEL_NATIVE_TYPES=OFF -DGXREPL_TEST_HOOKS=ON
cmake --build /tmp/dr-off -j && tests/run_tests.sh /tmp/dr-off
```

- If you change a sample in `docs/ai/samples`, or this file, run
  `python3 docs/bin/make_ai_docs.py` to update the guides, `llms.txt`
  and `llms-full.txt`.

## 5. AI-assisted upgrades

### 5.1 What changes, and what does not

- **From 7.0 to 7.3.x:** the API is the same apart from the items in the
  release notes (`RELEASE_NOTES_7.x.txt`). Files written by 7.x and 6.2
  open in 7.4 with the same build settings.
- **From 7.4 betas:** 7.4 beta 5 and later write the library's file
  headers in one layout on every platform. Older-layout files are read
  and written as they are; `utils/gxd_upgrade` converts one data file
  (object addresses change, indexes must be rebuilt from it). Never set
  `GXD_CREATE_LAYOUT` in production. gxrepl is removed in 7.4;
  replication is `gxObjRepl` (`RELEASE_NOTES_7.4.txt`, "NEW IN BETA 5"
  and "UPGRADING TO 7.4 BETA 5").
- **From 6.x:** DataReel 7 removed the 6.x string, list, thread, file and
  plain text network classes and the relational classes (gxRDBMS, 7.1).
  Follow `docs/ai/porting-from-6x.md` class by class. The database files
  are compatible: 7.x reads and writes 6.2 files with the same 32/64-bit
  and native types settings.
- **Every program that links DataReel** must be rebuilt from one tree
  with the same settings: the library, its tools and the applications.

### 5.2 Before the upgrade (read-only)

1. Record the current version, build options and platform: `version.txt`
   or the release notes in use, `CMakeCache.txt` (or the makefile
   flags), the OS and compiler.
2. List the programs that link DataReel and the database files they open.
3. Back up every data, index and journal file (rule 2), with the
   programs stopped so the copies are consistent.
4. On the copies, run `db_debug` and `ix_debug` and record `dr_digest`
   values, so the same checks can be compared after the upgrade.

### 5.3 The upgrade (one step at a time, confirm each)

1. Build and test the new release with the same file format settings
   (section 4.1). Stop if any test fails.
2. For 6.x code, port one module at a time with
   `docs/ai/porting-from-6x.md`; build with warnings on and fix each one.
3. Rebuild every program that links DataReel against the new tree.
4. Run the programs against the copies first and compare `db_debug`,
   `ix_debug` and `dr_digest` with step 5.2.4.
5. Only then switch the real data over, with the person's OK.

### 5.4 Roll back

Stop the programs, put the previous build back and restore the backed up
files from step 5.2.3. Do not open files the new release has written or
converted (`gxd_upgrade`) with the old release; use the backup copies.

## 6. Forks

DataReel is under the GNU Lesser General Public License version 3 or
later. A fork, a vendored copy inside another project, or a modified
build must:

- Keep `LICENSE` and the copyright and license headers in every file,
  and state in the changed files that they were changed and when.
- Provide the source of the modified library to anyone who receives a
  program built with it, and let them relink the program with their own
  build of the library, as the license requires.
- Not present the fork as an official DataReel release: use a different
  name or version suffix (for example `7.4-yourname.1`), and do not use
  the DataReel name or logo in a way that suggests DataReel made or
  supports the fork.

To keep a fork compatible with DataReel files and peers:

- Follow section 4.4: never change the on-disk format, the wire format
  of `gxStream` and the object server, or the error code values.
- Keep the test suite passing (`tests/run_tests.sh`) and add tests for
  each change.
- Record which DataReel release and commit the fork is based on, and
  check each new DataReel release for fixes, security fixes first.
- Report bugs you find in DataReel itself to DataReel (section 7.4)
  instead of carrying a private fix, so every user gets the fix.

## 7. AI-assisted troubleshooting and support

Diagnose read-only first; change nothing until the person agrees on the
cause and the fix (rule 1).

### 7.1 Where to look

| What | Command or file |
| --- | --- |
| Version | `version.txt`, `RELEASE_NOTES_7.4.txt` |
| Known issues and flaky tests | `KNOWN_ISSUES.md` |
| Build options | `cmake-build/CMakeCache.txt` (`DATAREEL_64BIT_DATABASE`, `DATAREEL_NATIVE_TYPES`, `DATAREEL_SSL`) |
| Library self-test | `tests/run_tests.sh <build folder>` |
| Data file check | `db_debug file.gxd` (on a copy) |
| Index file check | `ix_debug file.btx` (on a copy) |
| File contents digest | `dr_digest file.gxd` (compare two copies) |
| Database error text | `gxDatabaseExceptionMessage(err)` in the program's log |
| Network error text | `Error()` on the connection object, in the program's log |
| TLS handshake | `openssl s_client -connect host:port -servername host` |

`docs/ai/troubleshooting-and-support.md` lists common problems, the
checks for each, and the support summary in more detail.

### 7.2 Common problems

- **"You must define a target platform and/or compiler":** the headers
  were compiled without the `DataReel::datareel` target's definitions
  (section 4.2).
- **A file will not open, or reads garbage, after a rebuild:** the file
  format settings differ from the build that wrote the file (section
  4.3), or a record type holds native gx types that changed size.
- **A record or key compares wrong or differs on disk:** a pointer,
  `std::string` or unset padding in the record or key (section 4.2).
- **Keys missing after a crash:** the program wrote without a
  `gxdJournal` or without `Sync()` (section 4.2).
- **TLS connection fails:** certificate verification (the system store,
  `SetCAFile`, the host name), the TLS backend in the build, or the
  server only offering old TLS versions. Do not turn verification off
  (rule 5).
- **Link errors after an upgrade from 6.x:** a removed class is still
  used; see `docs/ai/porting-from-6x.md`.

### 7.3 Stop and escalate at once

Do not try to fix these yourself. Report to the person straight away,
with the summary in 7.4:

- `db_debug` or `ix_debug` reports damage, a CRC or checksum error, or a
  journal that does not recover.
- Any sign of data loss or of two programs writing the same files
  without a lock.
- A possible security problem in DataReel: a crash on a damaged file or
  network input, a length check that can be passed, or TLS accepting a
  certificate it should refuse. Do not post it in a public issue; send it
  privately (7.4).
- Anything that needs a change to the on-disk format, the wire format or
  a rule in section 1.

### 7.4 Support summary

When a problem is not solved, give the person a summary they can send to
their team or to DataReel (https://datareel.com/contact.php). AI-assisted
support ends here: the people take it from this summary.

1. DataReel version (`version.txt`), OS, compiler and the build options
   (32/64-bit engine, native types, TLS backend, static or shared).
2. The `tests/run_tests.sh` result on that build.
3. The `db_debug` / `ix_debug` output from copies of the files involved.
4. The smallest program or steps that show the problem, the error text
   and the log lines around it (times included).
5. What happened, when, what changed before it, and every command or
   change already tried with its result.

Remove host names, addresses and other site data from the summary when
the person asks for that, and never include passwords, private keys or
customer data. Projects maintained by DataReel Software Development
report DataReel issues through DataReel's internal handoff process
instead of patching their own DataReel copy.

DataReel is free software under the GNU Lesser General Public License,
provided as is. Check every command and change an agent proposes before
it runs; the person running it is responsible for the changes made.

## 8. Report back

End every task with: each command run or proposed, where, and its
result; each file changed; the build options used; the test results;
every warning and what was decided; and the backups made and where they
are.

## Map

| Path | What |
|------|------|
| `include/`, `src/` | Library headers and sources |
| `examples/database/` | gxDatabase, gxBtree, POD, InfoHog programs |
| `examples/tls/` | TLS echo, HTTPS, SMTP, POP3, FTPS, gxStream programs |
| `examples/general/` | gxConfig, LogFile, ThreadPool |
| `docs/ai/` | Task guides and their sample programs |
| `docs/classes/` | HTML reference for each class |
| `tests/` | `run_tests.sh`, mock mail/FTPS servers, damaged file test |
| `utils/` | `db_debug`, `ix_debug`, `dr_digest`, `gxd_upgrade` and other file tools |

========================================================================
FILE: docs/ai/tls-comms.md
========================================================================

# TLS communications with DataReel 7

DataReel 7 networking is TLS only (TLS 1.2 and 1.3), over IPv4 and
IPv6, on Linux (OpenSSL 1.1.1 or later) and Windows (Schannel or
OpenSSL 3.x). Telnet and ping are the only plain text protocols.

| Task | Class | Header |
|------|-------|--------|
| Any TLS client or server connection | `gxsTLSConnection` | `gxstls.h` |
| Accept TLS clients | `gxsTLSServer` | `gxstls.h` |
| HTTPS requests | `gxsHTTPClient`, `gxsHTTPMessage` | `gxshttpc.h` |
| HTTPS server messages | `gxsHTTPReadRequest`, `gxsHTTPWriteResponse` | `gxshttp.h` |
| Send mail | `gxsSMTPClient` | `gxsmtp.h` |
| Read mail | `gxsPOP3Client` | `gxspop3.h` |
| Read mail with IMAP (7.4) | `gxsIMAPClient` | `gxsimap.h` |
| File transfer | `gxsFTPClient` (FTPS) | `gxsftp.h` |
| Database blocks client/server | `gxStream` | `gxstream.h` |
| Thread pool for servers | `ThreadPool` | `thrpool.h` |
| URL parsing, percent decoding | `gxsURL` | `gxsurl.h` |
| Base 64 | `gxsBase64Encode`, `gxsBase64Decode` | `gxs_b64.h` |
| Raw TCP/UDP socket | `gxSocket` | `gxsocket.h` |

## Conventions

- Functions return `0` on success and `-1` on failure; the reason is in
  `Error()`. `ReadLine()` and `ReadAll()` return `bool`.
- Set options (`SetTimeout`, `SetCAFile`, `SetVerifyPeer`,
  `SetClientCert`) before `Connect()`.
- The server certificate is checked against the system trust store
  (on Windows, the Windows certificate store) and the host name or IP
  address you connected to. Add a private CA with `SetCAFile()`.
  `SetVerifyPeer(false)` turns checking off: tests only.
- `Connect(host, port)` resolves the name and tries every address,
  IPv6 and IPv4. Numeric addresses such as `::1` and `127.0.0.1` work.
- `implicit_tls = true` (the default) starts TLS immediately. Pass
  `false` to connect in plain text, exchange the protocol's STARTTLS
  command yourself, then call `StartTLS()`.
- Timeouts are in seconds and apply to the connect and to each read.
- A `gxsTLSConnection` is not copyable. Servers create one per client,
  usually in a `std::shared_ptr` handed to a thread pool task.
- Socket library start-up on Windows (WSAStartup) is automatic.
- On Windows (Schannel) a PEM or DER private key goes to the user key
  store, else in memory, else the machine key store, whichever Schannel
  accepts first; tested in a service under LocalService and over a
  key-based SSH logon. See
  "Schannel Private Keys" in README_windows_setup.txt.

## TLS client

```cpp
// docs/ai/samples/tls_client.cpp
// DataReel 7 sample: TLS client that sends lines and prints the replies.
// Works with examples/tls/tls_echo_server.
// Usage: tls_client host port [ca.pem]
#include <cstdlib>
#include <iostream>
#include <string>
#include "gxstls.h"

using namespace datareel;

int main(int argc, char **argv)
{
  if(argc < 3) {
    std::cerr << "Usage: tls_client host port [ca.pem]\n";
    return 1;
  }
  gxsTLSConnection conn;
  conn.SetTimeout(30);                 // Seconds, for connect and each read
  if(argc > 3) conn.SetCAFile(argv[3]); // Trust a private CA as well
  // Certificates are verified against the system store and the host
  // name by default. Connect() returns 0 on success.
  if(conn.Connect(argv[1], std::atoi(argv[2])) != 0) {
    std::cerr << "Connect failed: " << conn.Error() << "\n";
    return 1;
  }
  for(const char *msg : { "hello", "DataReel 7" }) {
    std::string reply;
    if(conn.SendLine(msg) < 0 || !conn.ReadLine(reply)) {
      std::cerr << "I/O failed: " << conn.Error() << "\n";
      return 1;
    }
    std::cout << "Sent \"" << msg << "\", got \"" << reply << "\"\n";
  }
  conn.SendLine("quit");
  conn.Close();
  return 0;
}
```

Other data functions: `Send(buf, n)` writes all bytes,
`ReadSome(buf, n)` returns what is available (up to n),
`Read(str, n)` reads exactly n bytes, `ReadAll(str)` reads until the
peer closes. For a client certificate call
`SetClientCert("client.pem", "client.key")` before `Connect()`.

## TLS server

`gxsTLSServer::Listen()` loads the certificate chain and key and
listens on one dual-stack socket. `Accept()` blocks for the next
client and completes its TLS handshake.

```cpp
// docs/ai/samples/tls_server.cpp
// DataReel 7 sample: multi-threaded TLS line server. Replies to each
// line with the line in upper case. "quit" ends a session and "stop"
// stops the server.
// Usage: tls_server port cert.pem key.pem
#include <atomic>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "gxstls.h"
#include "thrpool.h"

using namespace datareel;

static std::atomic<bool> stopping(false);

static void session(std::shared_ptr<gxsTLSConnection> conn, int port)
{
  std::string line;
  while(conn->ReadLine(line)) { // false on close, timeout or error
    if(line == "quit") break;
    if(line == "stop") {
      stopping = true;
      gxSocket wake; // Wake the blocked Accept() so main() can exit
      wake.Connect("localhost", port, 5);
      break;
    }
    for(char &c : line) c = (char)std::toupper((unsigned char)c);
    if(conn->SendLine(line) < 0) break;
  }
  conn->Close();
}

int main(int argc, char **argv)
{
  if(argc < 4) {
    std::cerr << "Usage: tls_server port cert.pem key.pem\n";
    return 1;
  }
  gxsTLSServer server;
  // Listens on IPv4 and IPv6. Returns 0 on success.
  if(server.Listen(std::atoi(argv[1]), argv[2], argv[3]) != 0) {
    std::cerr << "Listen failed: " << server.Error() << "\n";
    return 1;
  }
  std::cout << "Listening on port " << server.Port() << std::endl;
  ThreadPool pool(8);
  while(!stopping) {
    auto conn = std::make_shared<gxsTLSConnection>();
    conn->SetTimeout(120); // Idle sessions are dropped after two minutes
    // Accept() completes the TLS handshake; a failed handshake only
    // affects that client.
    if(server.Accept(*conn) != 0) continue;
    if(stopping) break;
    pool.Submit(session, conn, server.Port());
  }
  pool.Wait();
  return 0;
}
```

Make a test certificate:

```sh
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \
  -days 30 -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1"
# Clients then use SetCAFile("cert.pem")
```

## HTTPS client

`gxsHTTPClient` opens a new TLS connection per request, follows
redirects, decodes chunked bodies and refuses `http://` URLs. It does
not do HTTP/2, cookies or compression.

```cpp
// docs/ai/samples/https_fetch.cpp
// DataReel 7 sample: HTTPS GET and POST with gxsHTTPClient.
// Usage: https_fetch https://host/path [ca.pem]
#include <iostream>
#include <string>
#include "gxshttpc.h"

using namespace datareel;

int main(int argc, char **argv)
{
  if(argc < 2) {
    std::cerr << "Usage: https_fetch https://host/path [ca.pem]\n";
    return 1;
  }
  gxsHTTPClient client; // https:// only; http:// URLs are refused
  client.SetTimeout(30);
  if(argc > 2) client.SetCAFile(argv[2]);
  client.AddHeader("Accept", "application/json, text/plain, */*");

  gxsHTTPMessage resp;
  // Returns 0 when any response arrived, so check resp.status too.
  // Redirects are followed (5 by default).
  if(client.Get(argv[1], resp) != 0) {
    std::cerr << "GET failed: " << client.Error() << "\n";
    return 1;
  }
  std::cout << "GET " << client.FinalURL() << " -> " << resp.status << " "
	    << resp.reason << ", " << resp.body.size() << " bytes, "
	    << "Content-Type: " << resp.Header("content-type") << "\n";

  // POST a JSON body. Request() sends any other method.
  gxsHTTPMessage post_resp;
  if(client.Post(argv[1], "{\"name\":\"DataReel\"}", "application/json",
		 post_resp) != 0) {
    std::cerr << "POST failed: " << client.Error() << "\n";
    return 1;
  }
  std::cout << "POST -> " << post_resp.status << " " << post_resp.reason
	    << "\n";
  return (resp.status >= 200 && resp.status < 300) ? 0 : 2;
}
```

- `Download(url, file, resp)` streams the body to a file.
- `SetBasicAuth(user, password)` sends basic auth (only to the first
  host in a redirect chain). `AddHeader()` adds headers such as
  `Authorization: Bearer ...` to every request.
- `gxsHTTPMessage` fields: `status`, `reason`, `version`, `headers`
  (vector of name/value pairs), `body`; `Header(name)` looks up a
  header without regard to case.

## HTTPS server

There is no server framework; read a request and write a response on
each accepted `gxsTLSConnection`:

```cpp
#include "gxshttp.h"
#include "gxstls.h"
using namespace datareel;

void handle(gxsTLSConnection &conn)
{
  gxsHTTPMessage req, resp;
  if(gxsHTTPReadRequest(conn, req, 1024*1024) != 0) return; // 1 MB body limit
  resp.status = 200;
  resp.SetHeader("Content-Type", "application/json");
  resp.SetHeader("Connection", "close");
  resp.body = "{\"path\":\"" + req.target + "\"}"; // Escape in real code
  gxsHTTPWriteResponse(conn, resp); // Sets Content-Length
}
```

`examples/tls/https_server.cpp` is a complete static file server with
a thread pool and document root checks.

## Mail and file transfer

All three clients take a `gxsMailSecurity` value:
`gxsMAIL_IMPLICIT_TLS` (TLS from the start: SMTP 465, POP3 995, FTPS
990) or `gxsMAIL_STARTTLS` (STARTTLS, STLS or AUTH TLS after the
greeting: SMTP 587, POP3 110, FTP 21). A server that does not offer TLS
is refused.

```cpp
// docs/ai/samples/send_mail.cpp
// DataReel 7 sample: send a message through a mail server's
// submission port (587) with STARTTLS and a login.
// Usage: send_mail host port user password from to [ca.pem]
#include <cstdlib>
#include <iostream>
#include <string>
#include "gxsmtp.h"

using namespace datareel;

int main(int argc, char **argv)
{
  if(argc < 7) {
    std::cerr << "Usage: send_mail host port user password from to [ca.pem]\n";
    return 1;
  }
  gxsSMTPClient smtp;
  smtp.SetTimeout(30);
  if(argc > 7) smtp.SetCAFile(argv[7]);
  // Port 587 (submission) uses gxsMAIL_STARTTLS; port 465 uses
  // gxsMAIL_IMPLICIT_TLS, the default. A server that does not offer STARTTLS is
  // refused; nothing is ever sent in plain text.
  if(smtp.Connect(argv[1], std::atoi(argv[2]), gxsMAIL_STARTTLS) != 0 ||
     smtp.Login(argv[3], argv[4]) != 0) {
    std::cerr << "SMTP: " << smtp.Error() << "\n";
    return 1;
  }
  if(smtp.SendMessage(argv[5], { argv[6] }, "Test from DataReel 7",
		      "This message was sent over TLS.\n") != 0) {
    std::cerr << "Send failed: " << smtp.Error() << "\n";
    return 1;
  }
  smtp.Quit();
  std::cout << "Sent\n";
  return 0;
}
```

For several recipients, attachments or custom headers use the
low-level calls: `MailFrom()`, `RcptTo()` for each recipient, then
`Data(message)` with complete RFC 5322 headers and body (`smtp_time()`
in `systime.h` makes the Date header, `gxsBase64Encode` encodes
attachments).

POP3:

```cpp
gxsPOP3Client pop3;
if(pop3.Connect("mail.example.com") != 0 ||      // 995, implicit TLS
   pop3.Login("user", "password") != 0) { /* pop3.Error() */ }
int count; long long bytes;
pop3.Stat(count, bytes);
std::string msg;
if(count > 0) pop3.Retr(1, msg);                 // Whole message, dot-unstuffed
pop3.Quit();
```

IMAP (7.4; implicit TLS on 993 or STARTTLS on 143; `ConnectPlain()`
is plain text, for a server on the same host or a test only, and
`Login()` on it is refused unless `AllowPlainLogin()` was called first):

```cpp
gxsIMAPClient imap;
int count = 0;
std::vector<unsigned> unseen;
if(imap.Connect("mail.example.com") != 0 ||      // 993, implicit TLS
   imap.Login("user", "password") != 0 ||
   imap.SelectMailbox("INBOX", count) != 0 ||
   imap.Search("UNSEEN", unseen) != 0) { /* imap.Error() */ }
std::string header, body;
for(unsigned n : unseen) {                       // BODY.PEEK: \Seen is not set
  imap.FetchHeader(n, header);
  imap.FetchBody(n, body);
}
imap.Logout();
```

FTPS (data connections are encrypted with PROT P and reuse the control
connection's TLS session, which most servers require):

```cpp
gxsFTPClient ftp;
long long bytes = 0;
if(ftp.Connect("ftp.example.com") != 0 ||         // 21, AUTH TLS
   ftp.Login("user", "password") != 0) { /* ftp.Error() */ }
ftp.Put("report.pdf", "upload/report.pdf", bytes);
ftp.Get("data/latest.csv", "latest.csv", bytes);
std::string listing;
ftp.List("data", listing);
ftp.Quit();
```

## Database blocks over TLS (gxStream)

`gxStream` sends `gxBlockHeader` framed blocks over a
`gxsTLSConnection`, used to add, request, change and delete database
records on a remote server. Each block's status byte says what it is
(`gxAddRemoteBlock`, `gxRequestBlock`, `gxCloseConnection`, ...). A
server accepts with `server.Accept(stream.Connection())`, then loops on
`ReadHeader()` / `ReadBlock()` and answers with `WriteBlock()` or
`WriteResultBlock()`. Block sizes from the network are limited by
`SetMaxBlockSize()` (64 MB by default). See
`examples/tls/stream_server.cpp` and `stream_client.cpp`.

Database servers use mutual TLS. Use `gxStreamServer` (a
`gxsTLSServer` that requires client certificates): before `Listen()`
call `SetClientCAFile("client_ca.pem")` and allow clients with
`AllowClientFingerprint(sha256)` (from
`openssl x509 -in client.pem -noout -fingerprint -sha256`) and/or
`AllowClientCN(name)`. Without them `Listen()` returns `-1`; only
`AllowAnonymousClients(true)` runs an open server. `Accept(stream)`
closes clients without an allowed certificate, and
`stream.Connection().PeerCN()` / `PeerFingerprint()` say who
connected (escape control characters before logging them). Clients
call `stream.SetClientCert("client.pem", "client.key")` before
`Connect()`. A plain `gxsTLSServer` asks for client certificates only
if `SetClientCAFile()` is set, so HTTPS servers are unchanged.

```cpp
gxStreamServer server;
server.SetClientCAFile("client_ca.pem");
server.AllowClientCN("app-server-1");
if(server.Listen(port, "server.pem", "server.key") != 0) { /* Error() */ }
gxStream stream;
if(server.Accept(stream) == 0) {
  std::cout << "Client " << stream.Connection().PeerCN() << "\n";
}
```

## Raw sockets

`gxSocket` is the IPv4/IPv6 socket under everything above:
`Connect(host, port, timeout)`, `Listen(port)`, `Accept()` (returns a
new `gxSocket`), `Send`, `Recv` (exact count), `RecvSome`, and UDP with
`OpenDatagram()`, `SendTo()`, `RecvFrom()`. Use it only for protocols
that cannot use TLS; attach a connected socket to TLS with
`gxsTLSConnection::AttachClient()` or `AttachServer()`.

## Mistakes to avoid

- Expecting `http://`, port 25 plain SMTP or plain FTP to work: they are
  refused by design.
- Disabling certificate checks to "fix" a test: give the client the CA
  with `SetCAFile()` instead, and put the host name or IP address in
  the certificate's subjectAltName.
- Using one `gxsTLSConnection` from two threads at the same time.
- Calling `AllowAnonymousClients(true)` on a `gxStreamServer` to get
  past the `Listen()` error: give it a client CA and an allow list,
  and give each client its own certificate.
- Treating a `0` return from `gxsHTTPClient::Get()` as HTTP success:
  it means a response arrived; check `resp.status`.

========================================================================
FILE: docs/ai/object-database.md
========================================================================

# The DataReel 7 object database

DataReel's database is an embedded library: your program opens files
directly, there is no server and no SQL (use an embedded SQL database when
you need relational tables). It suits programs that store
their own records locally and need them to survive crashes and
upgrades: configuration and state stores, message and event logs,
catalogs, caches, and data exchanged between programs as files. File
formats have not changed since 2001.

Pick a layer:

| Need | Use | Header |
|------|-----|--------|
| Store and reuse variable size blocks by address | `gxDatabase` | `gxdbase.h` |
| Sorted index of fixed-size keys on disk | `gxBtree` with your `DatabaseKeyB` class | `gxbtree.h` |
| A data file and its indexes opened together | `POD` | `pod.h` |
| Objects with a key and variable length members | `InfoHog<KeyType>` | `infohog.h` |
| Faster repeated reads | `gxDatabaseCache`, `BtreeCache` | `dbfcache.h`, `btcache.h` |
| Nearest neighbor search on float vectors (7.4, in development) | `gxVectorIndex` | `gxvindex.h` |
| Check and repair files | `db_debug`, `ix_debug` utilities | `utils/` |

## Concepts

- A database file (`.gxd` by convention) is a header followed by
  blocks. `Alloc(n)` returns the **object address** (`FAU_t`) of a
  block that holds at least n bytes, reusing deleted blocks first.
  `Write(buf, n, addr)` and `Read(buf, n, addr)` use that address.
  Addresses stay valid until the object is deleted, so indexes store
  them.
- Each block has a header with a status (normal, deleted, removed)
  and, in revision A and later files, an optional CRC
  (`WriteObjectChecksum`, `ReadObjectChecksum`). New files are revision
  E, which also supports file and record locks.
- Records are raw bytes. Use fixed-size types (`char[N]`, `int32_t`,
  `uint32_t`, `int64_t`, `double`, `CDate`, `FAU`), never pointers,
  `std::string` or virtual functions. In the default build
  (`DATAREEL_NATIVE_TYPES=ON`) `gxUINT32` and `gxINT32` are `long`
  types: 8 bytes on 64-bit Linux, 4 on 64-bit Windows and with a
  32-bit compiler, so a record that holds them differs between
  platforms. The library's own headers do not: since 7.4 beta 4 every
  platform writes the 64-bit Linux layout, and reads and writes an
  old 4-byte layout file as it is (`gxd_upgrade` converts one).
  With `DATAREEL_NATIVE_TYPES=OFF` the gx types are fixed-size
  byte-order classes: only their in-memory types change (the library's
  files and the wire keep the canonical layout), but a record of yours
  that holds them has a different size, so prefer `int32_t` and the
  other fixed-size types in records.
- `gxDatabase`, `gxBtree` and `POD` are not copyable. Use
  one object per file per thread, or guard it with a `std::mutex`.
  `LockFile()`/`LockRecord()` coordinate several processes.
- Error codes are `gxDatabaseError`; `gxDBASE_NO_ERROR` is 0.
  `DatabaseExceptionMessage()` (member) or
  `gxDatabaseExceptionMessage(err)` gives the text.

## Records in a block file

```cpp
// docs/ai/samples/record_store.cpp
// DataReel 7 sample: store, read, walk and delete fixed-layout records
// in a gxDatabase block file.
// Usage: record_store [file.gxd]
#include <cstring>
#include <iostream>
#include "gxdbase.h"
#include "gxfloat.h"

using namespace datareel;

// Records are written as raw bytes, so use fixed-size members: char
// arrays and the gx integer and float types. No pointers, std::string
// or virtual functions.
struct Part
{
  char name[32];
  gxINT32 quantity;
  gxFLOAT64 price;
};

static Part make_part(const char *name, long qty, double price)
{
  Part p;
  memset(&p, 0, sizeof(p)); // Zero the padding too
  strncpy(p.name, name, sizeof(p.name) - 1);
  p.quantity = (gxINT32)qty;
  p.price = price;
  return p;
}

int main(int argc, char **argv)
{
  const char *fname = argc > 1 ? argv[1] : "parts.gxd";
  gxDatabase db;
  // Open() and Create() return gxDBASE_NO_ERROR (0) on success
  if(db.Open(fname) != gxDBASE_NO_ERROR && 
     db.Create(fname) != gxDBASE_NO_ERROR) {
    std::cerr << fname << ": " << db.DatabaseExceptionMessage() << "\n";
    return 1;
  }

  // Alloc() returns the address of a new (or reused) block, 0 on error
  Part parts[] = { make_part("bolt", 500, 0.10), make_part("nut", 800, 0.05),
		   make_part("washer", 1200, 0.02) };
  FAU_t nut_addr = 0;
  for(const Part &p : parts) {
    FAU_t addr = db.Alloc(sizeof(Part));
    if(addr == (FAU_t)0 || db.Write(&p, sizeof(Part), addr) != gxDBASE_NO_ERROR) {
      std::cerr << "Write failed: " << db.DatabaseExceptionMessage() << "\n";
      return 1;
    }
    db.WriteObjectChecksum(addr); // Optional CRC for this record
    if(strcmp(p.name, "nut") == 0) nut_addr = addr;
  }

  // Read one record back by its address
  Part p;
  if(db.Read(&p, sizeof(Part), nut_addr) != gxDBASE_NO_ERROR) return 1;
  std::cout << "At " << (long long)nut_addr << ": " << p.name << "\n";

  // Delete it. The block goes on the free list and the next Alloc()
  // of the same size or smaller reuses it.
  db.Delete(nut_addr);

  // Walk every record that is not deleted
  for(FAU_t addr = db.FindFirstObject(); addr != (FAU_t)0; 
      addr = db.FindNextObject(addr)) {
    if(db.ObjectLength(addr) != sizeof(Part)) continue; // Not a Part
    if(db.Read(&p, sizeof(Part), addr) != gxDBASE_NO_ERROR) break;
    std::cout << (long long)addr << " " << p.name << " qty " 
	      << (long)p.quantity << " price " << (double)p.price << "\n";
  }
  db.Close();
  return 0;
}
```

Useful calls: `ObjectLength(addr)`, `UnDelete(addr)`,
`Delete(addr, 1)` (remove permanently), `TotalBlocks()`,
`DeletedBlocks()`, `Flush()`, `Open(name, gxDBASE_READONLY)`.
`FindFirstObject()`, `FindNextObject(addr)`, `FindPrevObject(addr)`
walk the objects in file order, skipping deleted ones.

## Records with an index

A key class derives from `DatabaseKeyB`, keeps its data in one
fixed-size struct, passes that struct's address to the base class,
and implements `KeySize()` and the compare functions. Store the
record's address in the key so a lookup leads to the record. `POD`
opens (or creates) the data file and the index file together; it
needs the key class only as a type sample.

```cpp
// docs/ai/samples/indexed_records.cpp
// DataReel 7 sample: a data file plus a B-tree index (POD) with a
// custom key class. Records are found by name and listed in key order.
// Usage: indexed_records [data.gxd index.btx]
#include <cstring>
#include <iostream>
#include "pod.h"

using namespace datareel;

struct Customer
{
  char name[48];
  char email[64];
  gxINT32 orders;
};

// The index entry: a fixed-size key plus the record's address. Only
// the name is compared, so a lookup by name returns the address.
struct CustomerKeyData
{
  char name[48];
  FAU address;
};

class CustomerKey : public DatabaseKeyB
{
public:
  CustomerKey(const char *name = "", FAU_t addr = 0) : DatabaseKeyB(&data) {
    memset(&data, 0, sizeof(data));
    strncpy(data.name, name, sizeof(data.name) - 1);
    data.address = addr;
  }
  FAU_t Address() const { return (FAU_t)data.address; }
  const char *Name() const { return data.name; }

public: // DatabaseKeyB interface
  size_t KeySize() override { return sizeof(data); }
  // The CMake build defines __USE_SINGLE_COMPARE__, which uses
  // CompareKey(). Defining the dual compare functions as well keeps the
  // class working with either setting.
  int CompareKey(const DatabaseKeyB &key) const {
    return strcmp(data.name, ((const CustomerKeyData *)key.db_key)->name);
  }
  int operator==(const DatabaseKeyB &key) const { return CompareKey(key) == 0; }
  int operator>(const DatabaseKeyB &key) const { return CompareKey(key) > 0; }

private:
  CustomerKeyData data;
};

const BtreeNodeOrder_t ORDER = 31; // Keys per node + 1

static int add(POD &pod, const char *name, const char *email, long orders)
{
  CustomerKey key(name), found;
  if(pod.Index()->Find(key, found)) return -1; // Names are unique
  Customer c;
  memset(&c, 0, sizeof(c));
  strncpy(c.name, name, sizeof(c.name) - 1);
  strncpy(c.email, email, sizeof(c.email) - 1);
  c.orders = (gxINT32)orders;
  gxDatabase *db = pod.OpenDataFile();
  FAU_t addr = db->Alloc(sizeof(c));
  if(addr == (FAU_t)0 || db->Write(&c, sizeof(c), addr) != gxDBASE_NO_ERROR)
    return -1;
  CustomerKey entry(name, addr), compare;
  return pod.Index()->Insert(entry, compare) ? 0 : -1;
}

int main(int argc, char **argv)
{
  const char *dfile = argc > 2 ? argv[1] : "customers.gxd";
  const char *ifile = argc > 2 ? argv[2] : "customers.btx";
  CustomerKey key_type;
  POD pod;
  // Opens both files, creating them if they do not exist
  gxDatabaseError err = pod.Open(dfile, ifile, key_type, ORDER);
  if(err != gxDBASE_NO_ERROR) {
    std::cerr << gxDatabaseExceptionMessage(err) << "\n";
    return 1;
  }
  add(pod, "Wilson Supply", "orders@wilson.example", 12);
  add(pod, "Acme Tools", "buy@acme.example", 40);
  add(pod, "Baker Hardware", "info@baker.example", 7);

  // Look up one record by name. Find() fills in the stored key,
  // including the record address.
  CustomerKey key("Acme Tools"), compare;
  Customer c;
  if(pod.Index()->Find(key, compare) &&
     pod.OpenDataFile()->Read(&c, sizeof(c), key.Address()) == gxDBASE_NO_ERROR) {
    std::cout << "Found " << c.name << " <" << c.email << ">\n";
  }

  // List every record in name order
  CustomerKey k;
  if(pod.Index()->FindFirst(k)) {
    do {
      pod.OpenDataFile()->Read(&c, sizeof(c), k.Address());
      std::cout << "  " << c.name << ", " << (long)c.orders << " orders\n";
    } while(pod.Index()->FindNext(k, compare));
  }

  // Delete: remove the index entry, then the record
  CustomerKey gone("Baker Hardware");
  if(pod.Index()->Find(gone, compare)) {
    FAU_t addr = gone.Address();
    pod.Index()->Delete(gone, compare);
    pod.OpenDataFile()->Delete(addr);
  }
  pod.Close();
  return 0;
}
```

Notes:

- `Find(key, compare)` fills `key` with the stored key when it matches,
  so compare only the fields you search by and read the rest (the
  address) back from `key`.
- `Insert()` does not reject duplicates on its own; `Find()` first if
  keys must be unique.
- The node order (keys per node + 1) is fixed when the index is
  created; reopen with the same order and key size.
- `FindFirst`/`FindNext`/`FindPrev`/`FindLast` iterate in key order.
  `PartialFind()` finds the first key equal to or greater than a
  value, for prefix and range scans.
- An index file can hold several trees, and a `POD` can have several
  index files (`POD::Open` with an array of file names). When an
  index file did not exist and `POD::Open` created it empty,
  `pod.RebuildIndex()` returns true and the program must insert the
  keys again from the data file.
- `gxBtree` can be used alone: `gxBtree btx(key_type, order);
  btx.Create("file.btx")` or `btx.Open("file.btx")`.

## Persistent objects (InfoHog)

`InfoHog<Key>` stores an object made of a key (member 0) plus any
number of variable length members, with the key in a B-tree index.
Good for documents, contacts or settings whose fields change size.

```cpp
// examples/database/infohog/infohog.cpp (license header omitted)
#include "gxdlcode.h"

#include <cstring>
#include <iostream>
#include <string>
#include "infohog.h"

// Fixed-length key. InfoHog keys are stored in the index as raw
// bytes, so they must not hold pointers (no std::string).
struct ContactName
{
  ContactName() { memset(name, 0, sizeof(name)); }
  ContactName(const char *s) {
    memset(name, 0, sizeof(name));
    strncpy(name, s, sizeof(name) - 1);
  }
  int operator==(const ContactName &o) const { return strcmp(name, o.name) == 0; }
  int operator<(const ContactName &o) const { return strcmp(name, o.name) < 0; }
  int operator>(const ContactName &o) const { return strcmp(name, o.name) > 0; }

  char name[64];
};

typedef InfoHog<ContactName> Contact;
typedef InfoHogKey<ContactName> ContactKey;

// Member numbers. Member 0 is always the key.
enum { NAME = 0, EMAIL = 1, PHONE = 2, NOTES = 3, NUM_MEMBERS = 4 };

static void set_text(Contact &c, unsigned member, const std::string &s)
{
  c.SetMember(s.c_str(), (unsigned)s.size() + 1, member); // Keep the null
}

static std::string get_text(Contact &c, unsigned member)
{
  const char *p = (const char *)c.GetMember(member);
  unsigned len = c.GetMemberLen(member);
  if(!p || len == 0) return std::string();
  return std::string(p, strnlen(p, len));
}

static int open_pod(POD &pod, const char *data_file, const char *index_file)
{
  ContactKey key_type;
  gxDatabaseError err = pod.Open(data_file, index_file, key_type,
				 InfoHogNodeOrder, gxDBASE_READWRITE,
				 InfoHogUseIndexFile, InfoHogStaticArea,
				 InfoHogNumTrees);
  if(err != gxDBASE_NO_ERROR) {
    std::cerr << "Cannot open the database: " 
	      << gxDatabaseExceptionMessage(err) << "\n";
    return -1;
  }
  return 0;
}

static int add_contact(POD &pod, const char *name, const char *email,
		       const char *phone, const char *notes)
{
  ContactName key(name);
  Contact c(&pod, key, NUM_MEMBERS);
  set_text(c, EMAIL, email);
  set_text(c, PHONE, phone);
  set_text(c, NOTES, notes);
  if(c.FindObject()) { // Keys are unique
    std::cout << "Not added, " << name << " is already in the database\n";
    return -1;
  }
  if(!c.WriteObject(0)) {
    std::cout << "Could not add " << name << "\n";
    return -1;
  }
  std::cout << "Added " << name << " at address " 
	    << (long long)c.ObjectAddress() << "\n";
  return 0;
}

static int find_contact(POD &pod, const char *name, Contact &c)
{
  ContactName key(name);
  Contact probe(&pod, key, NUM_MEMBERS);
  if(!probe.FindObject()) return -1;
  if(!c.ReadObject(probe.ObjectAddress())) return -1;
  return 0;
}

static void list_contacts(POD &pod)
{
  ContactKey key, compare_key;
  gxBtree *btx = pod.Index();
  std::cout << "Contacts in key order:\n";
  if(!btx->FindFirst(key)) {
    std::cout << "  (none)\n";
    return;
  }
  do {
    Contact c(&pod, NUM_MEMBERS);
    if(c.ReadObject(key.ObjectID())) {
      std::cout << "  " << key.ObjectName().name << " <" 
		<< get_text(c, EMAIL) << "> " << get_text(c, PHONE) << "\n";
    }
  } while(btx->FindNext(key, compare_key));
}

int main(int argc, char **argv)
{
  const char *data_file = argc > 1 ? argv[1] : "contacts.ihd";
  const char *index_file = argc > 2 ? argv[2] : "contacts.ihx";

  POD pod;
  if(open_pod(pod, data_file, index_file) != 0) return 1;

  add_contact(pod, "Carol Smith", "carol@example.com", "555-0103", "Sales");
  add_contact(pod, "Alice Jones", "alice@example.com", "555-0101", "Engineering");
  add_contact(pod, "Bob Brown", "bob@example.com", "555-0102", "Support");
  add_contact(pod, "Alice Jones", "alice2@example.com", "555-0199", "Duplicate");
  list_contacts(pod);

  Contact c(&pod, NUM_MEMBERS);
  if(find_contact(pod, "Bob Brown", c) != 0) {
    std::cerr << "Bob Brown not found\n";
    return 1;
  }
  std::cout << "Found Bob Brown: notes = " << get_text(c, NOTES) << "\n";

  // Change one member in place. The record grows, so InfoHog moves it.
  std::string notes = "Support team lead since 2026";
  if(!c.ChangeMember(notes.c_str(), (unsigned)notes.size() + 1, NOTES)) {
    std::cerr << "ChangeMember failed\n";
    return 1;
  }
  std::cout << "Changed Bob Brown's notes\n";

  ContactName gone("Carol Smith");
  Contact del(&pod, gone, NUM_MEMBERS);
  if(del.FindObject() && del.DeleteObject()) {
    std::cout << "Deleted Carol Smith\n";
  }
  list_contacts(pod);
  pod.Close();

  // Reopen the files to show the changes were saved
  std::cout << "Reopening the database\n";
  POD pod2;
  if(open_pod(pod2, data_file, index_file) != 0) return 1;
  Contact again(&pod2, NUM_MEMBERS);
  if(find_contact(pod2, "Bob Brown", again) != 0) {
    std::cerr << "Bob Brown not found after reopening\n";
    return 1;
  }
  std::cout << "Bob Brown's notes: " << get_text(again, NOTES) << "\n";
  list_contacts(pod2);
  pod2.Close();
  return get_text(again, NOTES) == notes ? 0 : 1;
}
```

## Vectors and nearest neighbor search (7.4)

`gxVectorIndex` keeps float vectors in a `.vix` file, which is a normal
`gxDatabase` file, so it goes on the same journal as its data file.
Each node holds the 64-bit id of its object (usually the object's FAU),
four 32-bit tags for filtering and the vector. `Search` walks an HNSW
graph kept in the same file (sub-millisecond on a million vectors);
`Exact` scans every node. Indexes up to 4096 nodes and filters that pass
fewer than about 5% of the nodes are always searched exactly.

```cpp
gxdJournal j;
j.Open("events.jnl");
gxVectorIndex vix;
if(vix.Open("events.vix", gxDBASE_READWRITE, "anomaly/v1/abc") != gxv_NO_ERROR)
  vix.Create("events.vix", 79, gxvFLOAT32, gxvL2, 16, "anomaly/v1/abc");
j.Attach(vix.Database());
j.Begin();
unsigned tags[4] = { session, kind, 20261111, 0 };
vix.Insert(event_fau, vec, tags);   // same transaction as the event object
j.Commit();

gxvFilter f;
f.Tag(0, session);                  // equal
f.Range(2, 0, 20261110);            // up to the cutoff day: no look-ahead
std::vector<gxvResult> hits;        // id, distance, tags; closest first
vix.Search(query, 20, hits, 64, &f);
```

- One index per vector meaning and version: the spec text is checked on
  `Open`, so vectors from another feature builder are refused.
- After `gxdJournal::Rollback()` call `vix.Reload()`.
- Ties come back ordered by id, so results are repeatable. A node's
  graph level is a hash of its id, so the same inserts in the same
  order build the same graph.
- Searches run while one thread inserts: the insert finds its links
  under the shared lock and holds searches back only to link the node.
- `Update` with a new vector deletes the node and inserts a new one;
  deleted nodes stay in the graph until `Repair()` rebuilds it.
- `gxVectorIndex::Merge("month.vix", day_files, spec)` builds one index
  from many (ids must be unique across them); open it read only.
- Element types: `gxvFLOAT16` (half the memory, recall within about
  0.001 of float32) and `gxvINT8` (a quarter, recall about 0.02 lower;
  lowest for cosine). Distances always use the decoded vector, so
  inserts, `Repair()` and `Merge()` build the same graph. `Get()`
  returns the decoded vector. float16 refuses values above 65504
  (`gxv_OUT_OF_RANGE`).
- A record can carry its vector: `MakeMember(vec, member)` gives
  `MemberSize()` bytes to store as an InfoHog member or a fixed char
  field of a POD record; `InsertMember(record_fau, member, len, tags)`
  puts the same bytes in the index, in the same journal transaction as
  the record. When an InfoHog record grows it moves: call
  `Rename(old_fau, new_fau)`. `MemberMatches()` checks a record against
  its node in a `Verify()` resolver.
- An index made from record members can be rebuilt from the records
  alone: `gxvRebuildFromMembers()` (gxvmember.h) or `utils/vix_rebuild
  --data DATA.gxd --index OUT.vix --member offset:N --tags ...`.
  `vix.LogicalDigest()` (or `vix_rebuild --digest FILE.vix`) hashes the
  live nodes in id order: equal for two indexes that hold the same
  nodes, whatever their graphs.
- Format fields (7.4 phase D): `FeaturesRequired()` /
  `FeaturesOptional()`, `Codec()`, `GraphLayout()`, and
  `TagRange(2, lo, hi)`: the file keeps the range of tag 2 (the day).
- `utils/vix_test` holds the tests (including kill -9 recovery), a
  benchmark (`--bench`) and the graph gate (`--gate 1000000 --type
  f32|f16|i8`).

A complete program: the notes, their vectors, the search and a day
range.

<!-- sample: docs/ai/samples/vector_search.cpp from="#include <cstdio>" -->
```cpp
// docs/ai/samples/vector_search.cpp (license header omitted)
#include <cstdio>
#include <cstring>
#include <iostream>
#include "gxdbase.h"
#include "gxdjrnl.h"
#include "gxvindex.h"

using namespace datareel;

struct Note {              // fixed size: no std::string or pointers in a record
  char text[40];
  unsigned day;            // yyyymmdd
};

int main()
{
  const unsigned DIM = 4;
  gxdJournal j;
  gxDatabase db;
  gxVectorIndex vix;
  j.Open("notes.jnl");                                   // the journal first: it recovers
  if(db.Open("notes.gxd") != gxDBASE_NO_ERROR) db.Create("notes.gxd");
  if(vix.Open("notes.vix", gxDBASE_READWRITE, "notes/v1") != gxv_NO_ERROR)
    vix.Create("notes.vix", DIM, gxvFLOAT32, gxvCOSINE, 16, "notes/v1");
  j.Attach(&db);
  j.Attach(vix.Database());

  const char *texts[5] = { "flush to the open", "reclaim of vwap", "halt resumed", "gap down fill", "vwap hold" };
  const float vecs[5][4] = { { 1, 0, 0, 0 }, { 0, 1, 0.2f, 0 }, { 0, 0, 1, 0 }, { 0.9f, 0.1f, 0, 0 }, { 0, 1, 0, 0.1f } };
  if(vix.Count() == 0) {
    j.Begin();                                           // the note and its node together, or neither
    for(int i = 0; i < 5; i++) {
      Note n;
      memset(&n, 0, sizeof(n));
      strncpy(n.text, texts[i], sizeof(n.text) - 1);
      n.day = 20261111 + i % 3;
      FAU_t a = db.Alloc(sizeof(n));
      db.Write(&n, sizeof(n), a);
      unsigned tags[gxvTagCount] = { 0, 0, n.day, 0 };   // tag 2: the day
      vix.Insert((long long)a, vecs[i], tags);           // id = the note's address
    }
    if(j.Commit() != gxDBASE_NO_ERROR) { std::cout << "commit failed\n"; return 1; }
  }

  const float query[4] = { 0, 1, 0, 0 };
  std::vector<gxvResult> hits;
  vix.Search(query, 3, hits);                            // closest first
  std::cout << "nearest to the query:\n";
  for(auto &h : hits) {
    Note n;
    db.Read(&n, sizeof(n), (FAU_t)h.id);
    std::printf("  %-20s day %u  distance %.3f\n", n.text, n.day, h.distance);
  }

  gxvFilter f;
  f.Range(2, 20261111, 20261111);                        // only 2026-11-11
  vix.Search(query, 3, hits, 64, &f);
  std::cout << "on 2026-11-11 only: " << hits.size() << " note(s)\n";

  j.Close();                                             // checkpoint, then the files
  vix.Close();
  db.Close();
  return 0;
}
```

### Many files as one: vector sets

`gxVectorSet` (gxvset.h) searches many `.vix` files (a day file each, or
partitions) as one, through a small text manifest `<name>.vixset` next
to them. Each line keeps a file's node counts, its tag 2 range and a CRC
of its header.

```cpp
gxVectorSet set;
set.Create("days.vixset", "days", 384, gxvFLOAT16, gxvCOSINE, "notes/v1");
set.AddFile("2026/11/11/notes.vix");          // relative, no "..": checked
gxvSetSearch o;
o.k = 10;
o.day_range = 1; o.day_lo = 20261110; o.day_hi = 20261111;   // other files skipped unopened
o.threads = 4;                                 // the same results for any thread count
std::vector<gxvSetResult> r;                   // each names its file (r[i].file)
set.Search(query, o, r);
```

- A missing file (an archived day) is skipped and counted (`Missing()`);
  `o.strict = 1` makes it an error.
- The live day's writer: `set.AttachOpen("2026/11/15/notes.vix", &vix)`
  searches its open index as it is; `set.Refresh()` writes the new
  counts into the manifest.

### Vector searches over the network

The database object server (gxdbobject.h) answers `VECTOR_INFO` (op 8)
and `VECTOR_SEARCH` (op 7) for a database whose config names its vectors
(`gxObjectDbConfig::vectors`: a `.vixset` or a `.vix`), over gxStream
with mutual TLS. See `examples/oodb/vector_search_service.cpp` for the
request and reply layouts; `utils/dbserver/object_client --vinfo` and
`--vsearch K` ask from the command line. Linux and Windows (7.4);
`object_server ... --stop-file FILE` stops when FILE appears.

### Replicated copies

`gxObjRepl` (gxobjrepl.h, 7.4) replicates objects between two
independent object databases over gxStream with TLS, between Windows and
Linux nodes in both directions: only objects travel, each node keeps its
own file addresses and builds its own B-tree and vector indexes in the
same transaction as the objects. The primary writes with
`Begin()/Put()/Remove()/Commit()` and sends with `Pump()`; the copy runs
`Serve()`. Links between objects travel as ids. After a failover,
`Takeover()` makes the copy the primary at the next epoch and `Rejoin()`
brings the old primary back as a copy, on either platform. Replication
is asynchronous: commits the copy had not received are lost with a
crashed primary. See `docs/classes/database/gxobjrepl.htm` and the
`objrepl` tool (`utils/objrepl/`). gxrepl page shipping and the
journal's ship log were removed in 7.4 beta 5; a copy that loses a
vector index can make it again from its own records (`vix_rebuild`).
7.4.1: a node folder is open in one process; other processes read it
with `gxObjReplReader` (Get, Ids, FindKey, Nearest), which reads whole
commits under the node journal's shared lock (64-bit engine only).
Never open a running node's files with gxDatabase or gxBtree directly:
they can be read mid-batch.

## Checking and repairing files

- `db_debug file.gxd` analyzes a database file, reports damaged
  blocks and can rebuild a damaged file.
- `ix_debug file.btx` checks a B-tree index file.
- `examples/database/defrag` shows first-fit and best-fit reuse of
  deleted blocks.
- The library checks lengths and counts it reads from files, so a
  damaged file returns an error instead of crashing (see
  `tests/damaged_files.cpp`).

## Mistakes to avoid

- Putting `std::string` or pointers in a record or key: the file then
  holds memory addresses. Use `char[N]` or an InfoHog member.
- Opening files with a different `DATAREEL_64BIT_DATABASE` or
  `DATAREEL_NATIVE_TYPES` setting than the one that created them.
- Forgetting to `memset` records and keys: padding bytes then hold
  random memory and identical records differ on disk.
- Deleting a record but not its index entry (or the reverse).
- Implementing only `operator==`/`operator>` in a key class: the CMake
  build uses `CompareKey()`.

========================================================================
FILE: docs/ai/building.md
========================================================================

# Building and linking DataReel 7

## Requirements

- A C++17 compiler: GCC 8 or later (RHEL 8, 9, 10) or Visual Studio
  2022/2026 (64-bit).
- CMake 3.16 or later.
- TLS: OpenSSL 1.1.1 or later on Linux (`openssl-devel`); on Windows
  Schannel (built in, the default) or OpenSSL 3.x.

## Build the library

```sh
# Linux
sudo dnf install gcc-c++ cmake openssl-devel
cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release
cmake --build cmake-build -j
sudo cmake --install cmake-build              # /usr/local
```

```bat
rem Windows, Developer Command Prompt
cmake -S . -B cmake-build -G "Visual Studio 17 2022" -A x64
cmake --build cmake-build --config Release
cmake --install cmake-build --config Release --prefix C:\datareel
rem OpenSSL instead of Schannel:
rem   -DDATAREEL_SSL=OPENSSL -DOPENSSL_ROOT_DIR=C:/openssl64
```

## Options

| Option | Default | Meaning |
|--------|---------|---------|
| `DATAREEL_SSL` | `OPENSSL` (Linux), `SCHANNEL` (Windows) | TLS backend |
| `DATAREEL_64BIT_DATABASE` | `OFF` | 64-bit file addresses (files over 2 GB). Changes the file format. |
| `DATAREEL_NATIVE_TYPES` | `ON` | Native integer/float types in records and file headers. The library's file headers are written in one layout on every platform since 7.4 beta 4 (old 4-byte layout files are read and written as they are; `gxd_upgrade` converts one), but with `ON` native gx types in an application's own records keep their platform's size (`gxUINT32` is 8 bytes on 64-bit Linux, 4 on Windows): use fixed-width types in records that move. `OFF` uses fixed-size byte-order classes instead. Changes the file format. |
| `DATAREEL_GUI` | `CONSOLE` | `WX` shows errors in wxWidgets message boxes |
| `BUILD_SHARED_LIBS` | `OFF` | Shared library (`libdatareel.so.7`, `datareel.dll`) |
| `DATAREEL_BUILD_EXAMPLES` | `ON` | Examples, utilities, tests and the docs/ai samples |

Pick the two file format options once per project and keep them: a
program can only open files written with the same settings.

## Use it from your project

```cmake
cmake_minimum_required(VERSION 3.16)
project(myapp CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(DataReel 7 REQUIRED)         # after cmake --install
# or: add_subdirectory(third_party/datareel)
add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE DataReel::datareel)
```

The `DataReel::datareel` target adds the include directory, the
compile definitions that select the platform and file format, OpenSSL
or the Windows libraries, and threads. Compiling DataReel headers
without those definitions fails with "You must define a target
platform and/or compiler".

Without CMake (Linux), `build/makefile` builds `lib/libdatareel.a`
(`cd build; make; make install`; `make LARGEFILES=1` for the 64-bit
engine). Copy the compile flags from `env/linux.env`.

## Test

```sh
tests/run_tests.sh                       # build in ./cmake-build and run all checks
CMAKE_OPTS="-DDATAREEL_64BIT_DATABASE=ON" tests/run_tests.sh /tmp/dr-b64
CMAKE_OPTS="-DBUILD_SHARED_LIBS=ON" tests/run_tests.sh /tmp/dr-so
```

The script makes a test CA and server certificate, runs the database
examples, the TLS examples against each other, the mail and FTPS
clients against `tests/mock_servers.py` (needs python3), the docs/ai
samples, and `tests/damaged_files`, which opens thousands of damaged
database files.

## Run the examples

Built programs are in `cmake-build/examples/`. Database examples write
their files to the current directory. TLS examples take
`--ca ca.pem` to trust a test CA; see `docs/examples/examples.htm`.

========================================================================
FILE: docs/ai/porting-from-6x.md
========================================================================

# Porting DataReel 6.x code to DataReel 7

DataReel 7 keeps the database and TLS classes and replaces the general
purpose classes with the C++ standard library. Files written by 6.x
open unchanged; most porting work is replacing removed classes.

## Checklist

1. Build with CMake and C++17 (`find_package(DataReel 7)`,
   `DataReel::datareel`). The old nmake, Borland and MinGW makefiles,
   `dll/` and `winslib/` are gone.
2. Keep `DATAREEL_64BIT_DATABASE` and `DATAREEL_NATIVE_TYPES` the same
   as your 6.x build so existing files keep their layout. In the 6.x
   Linux makefile `LARGEFILES=1` meant the 64-bit engine and
   `TYPES_DEFMACS` with `__USE_NATIVE_INT_TYPES__` meant native types.
3. Replace the removed classes (table below).
4. Change network code to TLS (below).
5. Remove includes of headers that no longer exist (`gxstring.h`,
   `ustring.h`, `membuf.h`, `gxlist.h`, `gxbstree.h`, `dfileb.h`,
   `futils.h`, `gxthread.h`, `gxmutex.h`, `gxcond.h`, `gxsema.h`,
   `gxdatagm.h`, `gxsutils.h`, `stdafx.h`, `gxdlincs.h`). `systime.h`
   and `thrpool.h` still exist with new contents.

## Removed classes and replacements

| 6.x | DataReel 7 |
|-----|------------|
| `UString`, `gxString` | `std::string` plus `strutil.h` functions |
| `gxStringw` | `std::wstring` |
| `MemoryBuffer`, `MemoryBlock` | `std::vector<unsigned char>` |
| `gxList`, `gxListB`, `gxBStree` | `std::list`, `std::vector`, `std::set`, `std::map` |
| `DiskFileB`, `futils` | `std::fstream`, `std::filesystem` |
| `SysTime` | `systime.h` functions (`date_time_string()`, `smtp_time()`, `http_time()`, `iso8601_utc()`), `std::chrono` |
| `gxThread` and helpers | `std::thread` |
| `gxMutex`, `gxCondition`, `gxSemaphore` | `std::mutex`, `std::condition_variable`, `std::counting_semaphore` (C++20) |
| `thrPool` | `datareel::ThreadPool` (`thrpool.h`) |
| `gxsHTTPSClient` | `gxsHTTPClient` (HTTPS only) |
| `gxDatagram` | `gxSocket::OpenDatagram()`, `SendTo()`, `RecvFrom()` |
| `gxIP32`, `gxMAC48` | `gxsAddress`, `std::string` |
| `FString` | `char[N]` or `std::array` |
| `gxsHTML`, `gxsXML`, `gxsRSS` | a dedicated parser library |
| `HyperText`, `PostScriptDrv`, report writers | `std::ostream` |
| `Terminal` | ncurses |
| `gxDeviceCache` | none |
| `gxRDBMS` relational tables | An embedded SQL database |

## Strings

`strutil.h` has std::string versions of the gxString members:

```cpp
#include "strutil.h"
using namespace datareel;

std::string s = "  Name: Alice  ";
trim_in_place(s);                          // s.TrimLeadingSpaces(); s.TrimTrailingSpaces();
delete_before_including(s, ": ");          // s.DeleteBeforeIncluding(": ");
std::size_t pos = ifind(s, "ali");         // s.IFind("ali"); npos (not -1) if absent
s = to_upper(s);                           // s.ToUpper();
int n = to_int("42");                      // gxString("42").Atoi()
std::vector<std::string> parts = split("a,b,c", ',');
replace_all(s, "Alice", "Bob");            // s.ReplaceString("Alice", "Bob")
std::string line;
str_append(line, "id=", 42, ' ', 3.5);     // line << "id=" << 42 << ' ' << 3.5;
```

`Find()` results are `std::string::npos` on failure instead of `-1`;
check every `if(pos == -1)` test.

## Memory buffers

```cpp
std::vector<unsigned char> buf;            // MemoryBuffer buf;
buf.assign(p, p + n);                      // buf.Load(p, n);
send(buf.data(), (int)buf.size());         // buf.m_buf(), buf.length()
```

## Threads

```cpp
#include "thrpool.h"
datareel::ThreadPool pool(8);              // thrPool + gxThread subclass
auto result = pool.Submit([](int x) { return x * 2; }, 21);
int v = result.get();                      // 42; exceptions propagate here
pool.Wait();                               // Wait for queued tasks
```

## Configuration and log files

- `gxConfig::Load()` and the write functions return `bool` (true on
  success). `GetStrValue()` returns `const char *`, or null when the
  name is not set.
- `LogFile` no longer derives from `DiskFileB`: `Open(name)` appends,
  `WriteLine(text)` writes a time-stamped line and is thread safe,
  `operator<<` writes text.
- `CDate::c_str()` is now `str()` and returns `std::string`.

## Network code

Plain text protocols were removed. Typical changes:

| 6.x | DataReel 7 |
|-----|------------|
| `gxSocket` server with `remote_socket`, `RemoteRecv`, `RemoteSend` | `gxsTLSServer::Accept()` gives a `gxsTLSConnection` per client |
| `gxSocket` client `Send`/`Recv` | `gxsTLSConnection::Connect()`, `Send()`, `ReadLine()` |
| `gxsHTTPClient` with `http://` | `gxsHTTPClient` with `https://` only |
| `gxsSMTPClient` on port 25 | `gxsSMTPClient::Connect(host, 587, gxsMAIL_STARTTLS)` or port 465 |
| `gxsPOP3Client` on port 110 plain | `Connect(host)` (995) or `Connect(host, 110, gxsMAIL_STARTTLS)` |
| `gxsFTPClient` plain FTP | FTPS: `Connect(host)` (AUTH TLS on 21) |
| `gxStream` over plain `gxSocket` | `gxStream` over TLS with client certificates: servers use `gxStreamServer` and `Accept(stream)` |
| `gxSSL` with SSLv3/TLS 1.0 methods | `gxSSL_TLS` (1.2 and 1.3), `gxSSL_TLSv1_2`, `gxSSL_TLSv1_3` |

Servers now need a certificate and private key. Clients verify the
server certificate; give them your CA with `SetCAFile()`.

## Namespace

All names are in `namespace datareel`. The headers add
`using namespace datareel;` so unqualified 6.x code compiles. Define
`DATAREEL_NO_GLOBAL_NAMES` before including DataReel headers (or in
your build) to keep the global namespace clean and write
`datareel::gxDatabase`.

## Behavior changes in classes that stayed

- `gxDatabase::FindNextObject()`, `FindNextBlock()`, `FindPrevBlock()`
  and `FindPrevObject()` take an object (or block) address and return
  0 at the end. `FindPrevBlock()` no longer skips deleted blocks.
- `gxSSL::MakeRSAPrivateKey()` makes 3072-bit keys by default;
  `MakeDHParms()`, `LoadDHParms()`, `MakeRSAEphKey()` were removed.

========================================================================
FILE: docs/ai/utilities.md
========================================================================

# Text, CSV, single-instance and file utilities (DataReel 7.4)

Small helpers added in 7.4. All are in the `datareel` namespace; the
fragments below show the calls, the complete programs are named after
each section (they are built with the examples and checked by
`tests/run_tests.sh`).

## Terminal control sequences out of text (strutil.h)

`strip_ansi(text, options)` returns the text without ECMA-48 (VT100,
VT220, xterm) control sequences: CSI (`ESC [ ...`, colours, cursor
moves), OSC (titles), DCS/PM/APC strings, two-byte escapes and C0
controls. `AnsiStripper` does the same for text that arrives in pieces
(a serial port, a socket): a sequence split across two `Feed()` calls
is still removed.

```cpp
#include "strutil.h"
std::string clean = datareel::strip_ansi(raw);           // one string

datareel::AnsiStripOptions o;
o.cr_to_newline = true;        // \r alone becomes \n, \r\n becomes \n
o.cursor_to_newline = true;    // cursor moves (CSI H, f, B, E) become \n
datareel::AnsiStripper st(o);
std::string out;
st.Feed(piece1, out); st.Feed(piece2, out);
st.Finish(out);                // the end: an unfinished sequence is dropped
```

Options: `keep_tab` and `keep_newline` (default true), `cr_to_newline`,
`cursor_to_newline`, `c1_8bit` (bytes 0x80-0x9F are C1 controls; off by
default so UTF-8 passes through), `keep_del`. `Removed()` counts the
sequences removed. A C0 control inside a CSI is acted on and the CSI
continues to its final byte, as in ECMA-48.

## CSV files (gxcsv.h)

`gxCSVReader` reads RFC 4180 CSV from a file or a string: quoted
fields with the delimiter, quotes (`""`) and line ends in them, CR LF
or LF rows, a UTF-8 byte order mark skipped. `gxCSVWriter` writes rows
that read back the same.

```cpp
#include "gxcsv.h"
datareel::gxCSVReader r;                     // gxCSVOptions: delimiter, quote, strict,
if(!r.Open("in.csv")) { /* r.ErrorMessage() */ }   // trim_unquoted, skip_empty_rows, crlf, quote_all
r.ReadHeader();                              // the first row: Header(), Column("name")
int qty = r.Column("qty");                   // -1 if there is no such column
std::vector<std::string> row;
while(r.ReadRow(row)) { /* row[qty] */ }
if(r.Error()) { /* strict mode: the line in r.Line() */ }

datareel::gxCSVWriter w;
w.Open("out.csv");                           // or SetOutput(&string)
w.WriteRow({"id", "note"});
w.WriteRow({"7", "two\nlines, quoted"});
w.Close();
```

`gxCSVReader::ParseText(text, rows)` parses a whole string at once;
`gxCSVWriter::FormatRow(fields)` formats one row. Program:
`examples/general/csv_merge.cpp` (joins two files on a key column).

## One instance at a time (gxproclock.h)

`gxProcessLock::Acquire(file)` takes an exclusive lock on a lock file
(flock on POSIX, LockFileEx on Windows) and writes the process id into
it. A second `Acquire()` of the same file, in this process or another,
fails at once and `HolderPid()` names the holder. The system drops the
lock when the holder ends, however it ends, so a stale file never
blocks a restart. It is not inherited by child processes.

```cpp
#include "gxproclock.h"
datareel::gxProcessLock lock;
if(!lock.Acquire("/var/run/myapp.lock")) {
  fprintf(stderr, "%s\n", lock.Error().c_str());   // "... is locked by process N"
  return 2;
}
// ... run; the destructor (or Release()) frees it
```

`gxProcessLock::IsLocked(file, &pid)` checks without taking the lock.
Program: `examples/general/service_example.cpp`, the frame of a
long-running program (a heartbeat, a stop file, SIGTERM/Ctrl+C, POSIX
`--daemon`, and on Windows `--install`/`--service`/`--uninstall` as a
demand-start LocalService service).

## File utilities (utils/)

Back in 7.4, built with the library:

- `hexdump [switches] infile [outfile]`: a file in hex, decimal or as a
  C array; `-r` rebuilds the binary from a hex dump; `-c` and `-C`
  print CRC-32 and CRC-16 checksums.
- `ffind [switches] file`: find (`-F`), replace (`-R"old" -W"new"`) and
  insert strings in text files; the exit code is the match count.
- `txfilter [switches] infile`: keep the printable (or alphabetic,
  alphanumeric, numeric) characters of a text file; UNIX or DOS line
  ends.

Each prints its switches when run with none. See `docs/utils/` for the
full lists.

========================================================================
FILE: docs/ai/troubleshooting-and-support.md
========================================================================

# Troubleshooting and support for DataReel 7

AI-assisted troubleshooting follows the rules in `AGENTS.md`: written
management approval and approved enterprise AI models only ("Before you
use AI assistance"), a person in the loop for every step (section 0),
read-only checks first, and backups of every database file before any
change (section 1). The agent assists; the people decide and run the
changes, and problems the agent cannot solve go to DataReel through the
support summary below.

## Read-only checks

Run these first and keep their output for the support summary. Run the
file tools on copies of the files, with the programs that use them
stopped.

```sh
cat version.txt                                   # DataReel version
grep -E 'DATAREEL_(64BIT_DATABASE|NATIVE_TYPES|SSL)|BUILD_SHARED_LIBS' cmake-build/CMakeCache.txt
tests/run_tests.sh cmake-build                    # library self-test
db_debug copy/file.gxd                            # data file analysis
ix_debug copy/file.btx                            # B-tree index check
dr_digest copy/file.gxd                           # digest to compare two copies
```

## Problems by area

### Building and linking

| Symptom | Check |
|---------|-------|
| "You must define a target platform and/or compiler" | The program compiles DataReel headers without the `DataReel::datareel` target (`find_package(DataReel 7 REQUIRED)`, `target_link_libraries`). |
| Undefined classes after moving from 6.x | The class was removed in 7.0 or 7.1; see `porting-from-6x.md`. |
| `find_package(DataReel)` fails | The library was not installed (`cmake --install`), or `CMAKE_PREFIX_PATH` does not include the install prefix. |
| OpenSSL not found (Linux) | `openssl-devel` is not installed. |
| A test in `run_tests.sh` fails | Stop. Keep the full output for the support summary; do not change the test. |

### Database files

| Symptom | Check |
|---------|-------|
| A file opens with an error or reads wrong data after a rebuild | The build's `DATAREEL_64BIT_DATABASE` and `DATAREEL_NATIVE_TYPES` must match the build that wrote the file (`building.md`). |
| Records differ between Linux and Windows | The record holds native gx types or pointers; use fixed-width types (`object-database.md`). |
| Keys missing or a batch half written after a crash | The program wrote without a `gxdJournal`, or with `Flush()` instead of `Sync()`. |
| `db_debug` reports damaged blocks or a CRC error | Stop and escalate (below). Restore from backup or repair a copy only with the person's OK. |
| An index does not match its data file | Rebuild the index from the data file on a copy, then compare. |
| A file from a 7.4 beta older than beta 5 | It opens as it is; `gxd_upgrade` converts it to the new layout (`RELEASE_NOTES_7.4.txt`). |

### TLS and network

| Symptom | Check |
|---------|-------|
| Certificate verification fails | The server's chain against the system store, or `SetCAFile()` for a private CA; the host name in the certificate. `openssl s_client -connect host:port -servername host` shows the chain. Never turn verification off outside tests. |
| A plain text server (HTTP, SMTP, POP3, FTP) cannot be reached | DataReel 7 is TLS only; the server must offer TLS (or STARTTLS where the class supports it). |
| Windows and Linux behave differently | The TLS backend: Schannel (Windows default) or OpenSSL (`DATAREEL_SSL`). |
| A call returns -1 | Read `Error()` on the same object right after the call. |

## Stop and escalate at once

- Damaged files, CRC or checksum errors, or a journal that does not
  recover.
- Any sign of data loss or of two programs writing the same files
  without a lock.
- A possible security problem in DataReel (a crash on damaged input, a
  length check that can be passed, TLS accepting a certificate it should
  refuse). Report it privately to DataReel, not in a public issue.
- Anything that needs a change to the on-disk or wire format.

## Support summary

When a problem is not solved, give the person a summary they can send to
their team or to DataReel (https://datareel.com/contact.php):

1. DataReel version, OS, compiler and build options (32/64-bit engine,
   native types, TLS backend, static or shared).
2. The `tests/run_tests.sh` result on that build.
3. `db_debug` and `ix_debug` output from copies of the files involved.
4. The smallest program or steps that show the problem, the error text
   and the log lines around it, with times.
5. What happened, when, what changed before it, and everything already
   tried with its result.

Leave out passwords, private keys and customer data, and remove host
names, addresses and other site data when the person asks for that.
Projects maintained by DataReel Software Development report DataReel
issues through DataReel's internal handoff process instead of patching
their own DataReel copy.
