Artifact 6409b03b70b68645e946d8b97c967e37e7a8a5ff7094213dcde352ced2dbc33f:
- File
docs/context-api-proposal.md
— part of check-in
[11f47eadde]
at
2026-11-18 11:58:22
on branch trunk
— Record S0/S1 qualification groundwork before product code
Contract maps and pinned Pi reference, local C qualification fixtures, MC/DC and Fil-C remote lifecycle tooling, and the context transaction substrate probe. No product harness code yet. (user: dmestas, size: 9322) [annotate] [blame] [check-ins using]
- File docs/design/context-api-proposal.md — part of check-in [d66dc3f8af] at 2026-11-21 11:05:58 on branch docs-reorg — docs: short README; manual, reference, dev, design and archive under docs/; AGENTS.md; docs.sh checks docs against code; changelog.inc built at build time (user: dmestas, size: 9322) [annotate] [blame] [check-ins using]
Context embedding API proposal
Status: proposal only. No public API, context refactor, or production runtime is implemented. The accompanying test proves the storage substrate, not that archive_batch() is composable.
Verified current boundary
Inspected current inputs from /Users/dmestas/projects/context, not the older checkout identity in context-boundary.md. SHA-256 identities include:
src/ctx.c:68006cb411b67ba0d18a36616239c14297904ad115028312ee711d702b2cff2evendor/libfossil/libfossil.c:b93b2fb83cf9e3c3976f2d8a5a40b4362a00c5d242a61879cc477f752f886b8fvendor/libfossil/sqlite3.c:44246eb1b8775c7f4e7f5a07768f183023a2097c7e83f99fc3ea73a193497ab4
Each probe run retains the complete source/schema/build manifest, copied inputs, expanded command arguments, compiler identity, binary hashes, and results under build/qualification/context/; latest-run.txt identifies the newest run. No upstream objects are borrowed.
Current contracts, verified in that source:
main()registersfsl_sqlext_initthrough process-globalsqlite3_auto_extension()before opening context databases (src/ctx.c:9794–9803).CTX_NO_MAINomits that registration; a test must do it explicitly.cmd_init(NULL)selects WAL, installs the state/derived schemas, creates embeddedrepo:me, and records the private repository (110–151). Repository creation/opening belongs before the tested transaction.ctx_open()callsschema_ensure(), which can begin/commit migrations and trigger a derived rebuild (664–707). It is not a side-effect-free connection getter.archive_batch()issues its ownBEGIN IMMEDIATEandCOMMIT(787–978). Calling it inside a host transaction is not supported today.- Embedded repository tables live in the host's
maindatabase. The vendored contract says their work can join the host transaction, using nested savepoints internally; the host connection must outlive the repository contexts. Opening/closing repositories belongs outside transactions (libfossil.c:11718–11803, 12715–12781). Libfossil requires foreign_keys=OFF. - State and derived data are separate (
schema/state.sql,schema/index.sql).rebuild_derived()drops its listed derived objects and reconstructs content; chunk identities can change (src/ctx.c:9698–9739).
Recommended ownership boundary
One host-owned SQLite connection and one host-owned outer transaction. Context would borrow that connection through an opaque, connection-scoped handle; it would neither close the connection nor own the caller's commit. This is a semantic proposal, not a set of new function names or signatures.
- Prepare outside transactions. The host selects the file and durability/busy-timeout policy. Context explicitly validates the connection, performs its own schema preparation, and opens the selected embedded repositories. Preparation must finish before the host starts admitting runtime writes. It must not inspect default HOME/provider configuration, import standing rules, scan transcript directories, or sync as an incidental embedding side effect.
- Compose one bounded write. The host begins the outer transaction, writes its authoritative records, and asks context to append/index explicitly supplied, redacted archive content on that same connection. The context operation does not issue outer
BEGIN,COMMIT, orROLLBACK; internal savepoints must not release the host transaction. It returns structured errors instead ofdie()/exit(). On any failed operation the host explicitly rolls back the whole unit; SQLite statement ABORT alone is insufficient. No model/network/subprocess/human wait occurs inside the write transaction. - Finish at the owner. Only the host commits and publishes a durable receipt. It finalizes statements and releases context/repository handles outside transactions before closing its connection. A failed close is an error, not permission to discard a still-busy handle. The CLI remains an adapter that creates its own connection, invokes the same core, owns its transaction, and preserves existing commands, output, exit status, archive redaction, and explicit maintenance behavior.
This requires deliberate extraction in context itself. Do not copy archive_batch() into the consumer or wrap it in another BEGIN as a workaround.
Migration and rebuild ownership
Context owns migrations/version checks for its state and derived namespaces; the host owns its authoritative runtime schema and receipts. Keep those versions distinct, with an explicit startup ordering and a single maintenance owner. A borrowed-handle attach must not unexpectedly migrate or rebuild inside an application transaction. Newer unsupported versions must fail closed.
Context rebuild must retain its explicit object list and never drop host tables or treat host execution state as reconstructible knowledge. Host identities/checkpoints must not use derived chunk IDs as their sole durable reference. Rebuild, rule import, sync, and directory scanning are explicit maintenance operations, not retrieval/open side effects. Compatibility, old-schema upgrades, and host-record survival across rebuild need upstream tests before API adoption; this probe does not test them.
Retrieval and provenance
Expose bounded typed retrieval results, not CLI text parsing or raw sqlite3_stmt ownership. Preserve current project scoping, ranking, history/as-of filters, and retired-material exclusion (search_run(), src/ctx.c:1155–1218). Results should carry document kind/name, repository identity, immutable artifact/version hash when available, turn or source locator, and the exact returned text. Derived chunk IDs may be diagnostics, not durable provenance. For local mutable documents, pin the content hash and returned text rather than pretending there is a Fossil version.
The host persists the exact retrieval selection/text/hash manifest used by a request. A later reindex or search must not rewrite prior execution inputs. This archive is deliberately lossy/redacted and is not the authoritative provider transcript, execution log, or authorization source. No retrieval API or wire shape is specified by this proposal.
Lifetime and foreign-key risks
- Auto-extension registration is process-global. A production embedding must document a single initialization owner and use per-connection registration where feasible; a component must not reset another component's registrations or call global SQLite shutdown while others are active. The test registers/unregisters only its own extension in a private single-threaded process. It does not qualify repeated global initialization or unloading.
- Context's environment-dependent paths, CLI fatal-error behavior, and
self_path/background capture assumptions need separation from the embedded core. SQLiteTHREADSAFE=1is not proof that arbitrary context/libfossil handles are concurrently usable. Begin with one serialized owner; define cancellation and statement/handle lifetimes before adding threads. - Do not enable foreign keys on the libfossil host connection. The runtime cannot assume SQLite enforces its
REFERENCES/cascades there. The host must explicitly enforce its runtime relationships in the owned write operations and validate them, or revisit this proposed single-connection design before adopting a schema that requires FK enforcement. FK-dependent context maintenance must be explicitly coordinated outside active host transactions; do not silently flip the pragma or hide a second writer behind an API call.
Rejected alternative
Composing existing ctx subprocess calls preserves CLI isolation, but each subprocess owns a separate connection/transaction: it cannot atomically acknowledge a host result and a Fossil archive change. Giving context the outer transaction and passing arbitrary host callbacks adds callback/error/lifetime complexity to solve a problem the host already owns. Neither is recommended for this slice.
Proof and remaining gates
Actual local tests use copied current C, schemas, and Makefile rules, including the bundled SQLite FTS5/math/thread flags and libfossil configuration. A fresh marked temporary HOME and CTX_DB, an empty inherited environment, and private Fossil/XDG configuration paths isolate each run. The probe mutates a real embedded technote, real ctx_capture state, and a host fixture table in one host transaction. It checks successful commit, explicit rollback, a duplicate-key statement failure followed by explicit rollback, and close/reopen persistence. Rollback checks include the stored Fossil artifact count, not just returned text. A deliberate COMMIT-instead-of-ROLLBACK mutant must fail the technote oracle. Temporary databases and configuration directories are removed on success and failure.
Run sh tools/test-context.sh and sh tools/test-context.sh sanitize. The latter checks ASan+UBSan; leak detection is not claimed on macOS. Neither run proves power-loss/crash recovery, multiprocess contention, cross-file atomicity, a public API, archive_batch() composition, CLI-wide regression compatibility, migration/rebuild survival, Fil-C support, or production readiness. Those are proposed follow-up gates, not tests reported as passed here.