@alma-harness/history
v0.12.0
Published
Atomic idempotent neutral session history import for Alma.
Readme
@alma-harness/history
Bounded, idempotent import of neutral history into Alma sessions. No provider, media fetch, historical tool execution or financial write occurs. Host conversion, source authorization and actual cutover remain separate responsibilities.
Run migrateHistoryImportStore(pool) as the migration principal, grant the runtime
login membership in the configured app role, then construct
new PostgresHistoryImportStore(pool, {statementTimeoutMs: 30000}). The migration
reuses existing session tables and adds three FORCE-RLS metadata tables plus nullable
alma_sessions.history_import_generation. Runtime requires no superuser privileges.
Use trusted schema search paths and the normal scoped pool contract.
const first = await imports.append({
source: {
scope: {org: 'organization', uid: 'user'}, sessionId: 'conversation',
source: 'archive', sourceSessionId: 'old-conversation',
sourceRevision: 'fixed-export-v1', importId: 'migration-1',
},
ordinal: 0, previousChecksum: null, final: false,
entries: [{sourceId: 'message-1', message: {
role: 'user', blocks: [{type: 'text', text: 'Earlier message'}],
meta: {at: '2025-01-01T00:00:00.000Z'},
}}],
});
// Next chunk: same source, ordinal 1, previousChecksum first.checksum.
// Set final only when the entire fixed export has been imported.read(source) returns the latest immutable receipt/checkpoint;
receipt(source, ordinal) reads a prior one. append computes its SHA256; exact
replay returns the original receipt even after content erasure. Changed source,
content, order, predecessor, final flag or reused source entry IDs conflict. Each
chunk has 1–100 messages, at most 1 MiB canonical UTF-8 JSON and depth64. All input
must be plain JSON, with well-formed strings, finite numbers and closed neutral
message/block/meta shapes. Required timestamps are chronological. Tools must have
complete matching exchanges within one chunk; inline media is refused. Rotation
spans cannot exceed preceding imported history or cut a tool exchange. A boolean
boundary flag in entry metadata validates cross-chunk cuts without loading old
content. Sparse/extra array properties and inline data URIs are refused. Roles and ordered content survive.
The target must be absent initially. Stop all writers and maintenance that rewrites history (including tool-traffic expiry), and keep consumers away until a final receipt exists. Live append between chunks conflicts on the counter. The import generation prevents an erased and recreated session from impersonating the old target. There is no online dual write or merge with existing live history. Old readers remain compatible with the nullable additive column; old migration replay does not remove it. Run matching new migration before import writers.
Receipts, descriptors and entry mappings store only source identifiers, hashes, sequence/timestamp metadata and generation. Content has one copy, in the existing session entries. App metadata permissions are SELECT/INSERT; no deletion/overwrite API exists. Session erasure preserves receipts, never recreates data on replay, and blocks new chunks after disappearance or recreation. Whole-scope legacy source reauthorization remains a host watermark/erasure boundary. Do not purge receipts without an explicit future retention contract: doing so ends replay protection.
A committed chunk is atomic with its messages and sequence; replay repairs a lost
acknowledgement. A final receipt proves import completion, not authorization for
production activation. Historical costs/opening balances remain separate; never
manufacture model usage or re-settle imported transcript content.
@alma-harness/history/testing exports InMemoryHistoryImportStore, a contract
reference with inspection/erase/live-append helpers. It is not a second writable
session master or a production migration backend. The shared acceptance suite
runs this reference and the PostgreSQL importer, reading actual imported rows
through PostgresSessionStore. This is the executable consumer; no Prumo scene is
added because it is not a migration tool and its source budget is nearly full.
Historical cost provenance
migrateHistoricalCostStore(pool) installs a separate immutable reporting ledger.
PostgresHistoricalCostStore supports the same scoped pool options; its testing
reference is InMemoryHistoricalCostStore. Neither writes live cost counters,
settlements, audit events or projection outboxes. Importing history never creates
model usage. An opening amount is historical reporting, not live cap seeding.
await costs.append({
scope: {org: 'organization', uid: 'user'}, key: 'archive-before-cutover',
sessionId: 'conversation', source: 'archive', sourceRevision: 'export-v1',
authorityRevision: 'cutover-v1',
from: '2025-01-01T00:00:00.000Z', until: '2025-02-01T00:00:00.000Z',
representation: 'opening', costUsd: 12.5,
});Alternatively use representation: 'itemized' and entries of
{sourceId, at, costUsd, model?} (1–1000), without a top-level amount. Rows sort by
instant/source ID before hashing and summing. USD is finite and nonnegative; model
is only an opaque historical label. Snapshots are closed plain JSON, max1 MiB.
Exact normalized replay preserves the original receipt/time. Changed key content,
overlapping session intervals across any source/representation, and repeated source
IDs in the same scope/source/revision conflict. Intervals are half-open; adjacent
intervals are valid. Partition exports at disjoint boundaries or use one opening
amount and retain an external archive for an indivisible large interval.
get(scope,key) includes the full snapshot. list(scope,{sessionId?,afterKey?,limit?})
returns ASCII-key metadata pages (max100), without item arrays. summary(scope,sessionId)
returns historical USD and coverage/representation counts, without time proration.
Float aggregates follow existing cost conventions. App roles cannot update/delete
receipts or source mappings; content erasure preserves these financial records.
The host must publish a versioned authority manifest mapping legacy session/source IDs to their target and excluding charges owned by native governed settlements. Dashboard totals may add the disjoint historical total once to native itemized costs; root/batch inclusive projections are not additional charges. Live cap continuity needs an explicit host baseline: this ledger never silently seeds it. The host owns export authorization, identity mapping, and cutover; a receipt grants no authority to run a real import or activate a product.
