Learning Core (developer)
Internals and extension seams. For operating a deployment see Learning Core (admin); for the feature itself see Learning Core.Compatibility target
Bundled extension. Fork-base compatibility is expressed by the package SemVer and theforkBase
marker in dist/build-info.json, not by an openclaw peer range - bundled extensions carry no
openclaw peer dependency.
The Postgres backend uses a lazy require("pg") mirroring core’s own pool construction, so no
runtime dependency is added to the extension package. A host without pg installed simply cannot
resolve to the Postgres backend.
Module map
A schema name is validated at both SQL interpolation boundaries, not only in the DDL:
resolveDomainStorage checks it in core, learning-schema.ts checks it again when it builds the
DDL, and the PostgresLessonStore constructor checks it a third time. That last one matters
because a caller can construct the store directly and never touch the DDL path, so DDL-only
validation would be bypassable.
Placement resolution lives in core
Backend selection lives in core and is exported from the plugin SDK:DomainStoragePlacement is a discriminated union:
domain; the
default Postgres schema is derived as plugin_<domain with dashes replaced by underscores>.
The LessonStore contract
One interface, two SQL implementations, one conformance suite. Members:
invalidateLesson({ id, now, reason?, sessionId? }) ends a lesson’s validity (sets
invalidAt) without writing a successor. It is idempotent: an already-invalid lesson is
returned unchanged. Inside a claim, a consolidation delete verdict without text applies the
same invalidation through applyVerdict (effect invalidate), in the transaction that
finalizes the candidate. Claim, budget, and distill operations are available on both SQL
backends; an unopened store reports store_unavailable rather than serving a file store.
The operator-review writers share the same locking discipline:
rateLesson({ id, rating, now })holds the same effect lock asinvalidateLessonand, in one transaction, writes the rating and the audit row (lesson.endorsedforscore: 1,lesson.retiredfor-1). A -1 on an active lesson also retires it withinvalidationReason: "operator: <note|retired>". Endorsing a retired lesson is a domain error.reviseLesson({ predecessorId, successor, actor, now })supersedes in one transaction (the supersede effect locks held) and appends thelesson.revisedaudit row carrying the successor id.listLessonExemplars({ limit })projects rated or operator-authored lessons to compact{ verdict: "good" | "bad", text, note? }exemplars, newest update first. The consolidation pass injects them into the judge prompt as feedback; see Judge v2.
types.ts: LessonOrigin (producer
consolidation | promote | operator, time, rationale, model, prompt version, analysis job id,
actor), LessonRating, EvidenceQuote (a redacted cited message with entryId, seq,
sender), and LessonExemplar. ExtractionCandidate carries the capture window
(CaptureMessage[]) and the anchor index; excerpt remains the anchor text sliced to 500
characters for ranking, promote, and UI compatibility.
Candidates live in learning_records with record_type='candidate'. listLessons must not
return them. searchLessons returns lessons only.
What not to do:
describeBackend() returns { backend, capability }, surfaced by learning.overview.
The backend stays sqlite or postgres; an outage does not switch the implementation.
Adding a member means adding it to both SQL implementations, the legacy read-through wrapper,
and the conformance suite.
Record lifecycle
lesson-record.ts is the only place that decides lifecycle shape:
withLessonDefaultsstamps a new record with the current defaults.applyLegacyLessonDefaultsforward-migrates a pre-C0 record that predates these fields.isLessonActiveevaluatesvalid_fromandinvalid_atagainst a suppliednow. Callers pass the clock in; the function does not read it.
supersedeLesson writes the successor, links supersedes_id, and
closes the predecessor’s validity window. Nothing is removed. getLessonChain walks the links.
This is exposed through the learning tool, so the path has a production caller and is not
test-only code.
Backend selection and failures
createLessonStore memoises by resolved location: SQLite databases by path, Postgres pools by
URL. index.ts builds a store at three call sites, so without memoisation the same file would be
opened three times and the same database pooled three times.
Neither reads nor writes fall back to files. The failure surfaces differ by backend:
- SQLite can fail at open. The factory logs the cause and returns an unavailable SQL store:
data operations and claims report retryable
store_unavailable,substrate()is undefined, anddescribeBackend()still identifies SQLite. - Postgres does not connect at construction. A rejecting operation propagates its error; the store remains SQL-backed and the passes re-probe it on subsequent work.
Fence-and-scope gate
LearningGate (learning-gate.ts) is the single place a learning entry point gets its scope:
resolve({ operation, access, agentId?, workspaceId?, workspaceDir? })enforces, for writers (access: "write"),store_unavailablewhen SQL is configured but its substrate is missing, thenrepair_pendingbeforerepaired_at. A payloadworkspaceIdmust then equal the agent’s local canonical id, and the local id must equal the recordedcanonical:<agentId>row (scope_mismatch). All of that runs before anything is recorded. With noagentIdit uses the default agent; it never guesses a workspace.- Only a
writethat passed every check records a missing row (scopes.claim), and only for an agent this gateway configures (listAgentIds). Core resolves any other id to a default path, so an unconfigured agent with no recorded row fails closed withagent_unconfigured(LEARNING_SCOPE_UNCONFIGURED). Its reads and writes are refused, and nothing is recorded. access: "read"skips the fence (reads beforerepaired_atstay allowed).readandpreview(dry runs) usescopes.peek, which compares against the recorded row and never records.scopeRunnable(scope)is the non-recording predicate for fan-outs. The maintenance pass, the startup sweep, and the idle trigger enqueue a scope only when it is its agent’s canonical scope on this process. With no row recorded yet, the agent must also be configured here.mismatchedAgents()lists agents whose recorded id is not this process’s. Cross-agent operator reads exclude their rows and report them asmismatchedAgents.
produce, the learning tool, learning.decideProposal, the
agent_end sidecar, context.collect, session-end capture, and the operator read RPCs all go
through it. recordCanonicalScope runs under the fence lock.
A canonical row is recorded in two places only. The coordinator records one for each configured
agent while the fence is unrepaired (fence install). Otherwise the agent’s first write records
it. Phase 4 records nothing and re-keys only agents that have a row. The pre-F rows of an agent
that no repairing gateway configured stay under their legacy key.
The first write of a gateway that configures such an agent records the row. It then calls
rekeyAgentBatch until none are left. Each call is one bounded transaction (200 rows) under the
fence lock, and it runs only after repaired_at. A claim before repaired_at (the coordinator
of a configuring gateway that starts mid-repair) records the row but is not remembered by
LearningScopeResolver, so the agent’s next write re-runs the re-key idempotently. When
runUpgradeFence sees repaired_at, it also runs rekeyRecordedAgents (every recorded agent’s
rekeyAgentBatch loop); a coordinator that starts after repaired_at runs it once too, in case
the repairing process stopped in between. It moves the rows with phase 4’s moveRecord
collision rules:
- Lessons merge.
- Candidates keep the more final status.
- Proposals and audit rows keep both copies, the moved one under a scope-derived id.
Reading transcript text
extractMessageTextParts is the seam that has bitten hardest. Production entries are
StoredConversationEntry, which has no content field - text lives in contentText and
contentBlocks. An extractor that reads only content yields zero candidates on every real
session while the claim path still acks processed, so the failure is completely silent.
Two rules follow:
- Fixtures must use the real
StoredConversationEntryshape. A{ role, content }fixture is a shape that never occurs in production and will pass while the code is dead. - Text arriving from storage carries a
[<from> <host> <timestamp>]prefix, trailing space included. Correction patterns must account for it; a bare^-anchored regex can never match.
Passes
Six built-in task passes.registerTaskPass takes the bare id; the backbone namespaces
it as <pluginId>.<passId>. Effective (namespaced) ids are stable — do not rename:
TaskPass shape is { id, stage?, priority, scope, costClass, timeoutMs?, run }. There is no
handler field. run may return { successors } (a TaskPassResult); the dispatcher inserts
them in the completion transaction. produce returns reconcile-skills (<fingerprint>:reconcile)
whenever its work item’s lineage has a lesson effect, plus a continuation
(<agent>:<workspace>:cont:<utcDay>:<spent>) or a next-day carry
(<agent>:<workspace>:carry:<nextUtcDay>); distill’s continuation is a successor too.
Triggers and the producer bucket
src/triggers.ts holds the session-end handler and the agent_idle hook. The session-end
fingerprint is <agentId>:<workspaceId>:<sessionId>; the idle one is
<agentId>:<workspaceId>:idle:<trigger>:<idleSinceMs+idleForMs>, one per scope with pending
candidates. The handler takes no claim while the SQL store fails a live round-trip or the upgrade
fence is not repaired, captures with insertCandidateIfAbsent, then enqueues produce or runs
promote inline per the route table, and only then acks. It defers a claim
(api.deferSessionWork, attempt-neutral) instead of failing it when the store or recovery
admission fails after the claim, or when consolidation owns today’s bucket. Store, enqueue and
busy-candidate deferrals retry after 60 seconds; scope or configuration deferrals retry after 24
hours, and a bucket owned by consolidation defers until the next UTC midnight. A
session_not_visible owner row (the StorageReadAccessError with
retryable: true) defers every 60 seconds while the claim is younger than 10 minutes measured
from createdAt, then fails retryable into the normal attempt budget; a
session_foreign_owner row is not-owned and acks non-retryable straight to dlq.
Every applyVerdict finalization is owner-fenced on the bucket <agentId>:<utcDay>: a verdict
with a reservation uses its charged day, anything else the database day. Inside the transaction
(BEGIN IMMEDIATE on SQLite, pg_advisory_xact_lock on the bucket key on Postgres) it
compare-and-sets the owner:<agentId>:<utcDay> row, sets its has_effect flag, writes the
per-item effect:<producerTaskId>:<producerFingerprint> row, and stamps the candidate’s
producer, producerTaskId, producerFingerprint, and producerBucket. A mismatching producer
gets the domain error LEARNING_PRODUCER_CONFLICT and changes nothing. produce stamps the
namespaced task id learning-core.produce and the work item’s trigger fingerprint, so a retry
finds its earlier effects even after midnight; the session-end inline promote uses
learning-core.inline-promote and <agentId>:<workspaceId>:<sessionId>.
The SQL-only surface behind this lives on LessonStore.substrate() (learning-substrate.ts;
undefined when the store could not open): the fence record and batches, canonical scope rows, bucket owner and
effect reads, keyset scope pages (listScopesWithPendingCandidates, distill, applied proposals),
and retention. Its procedures are generators over one SQL dialect kit (learning-sql.ts), driven
synchronously inside SQLite’s BEGIN IMMEDIATE and asynchronously on one pinned Postgres client.
Promote rules
runPromotePass is the deterministic producer. Its rules, in order:
- Stand down while consolidation is runnable. When
consolidationRunnableis true, promote makes no candidate-state change at all, not even the untagged skip.previewPromotePass(dry run) reportsconsolidation_runnable. - Skip consolidation’s buckets. On SQL stores, candidates whose agent’s current UTC bucket
consolidation already owns are left pending (
ownedByConsolidationin the summary). - Skip untagged candidates. A candidate tagged only
untaggedis finalized asskipped, so bland sessions do not pile up. - Group and threshold. Other candidates become draft lessons and are grouped by lesson id,
workspace, and agent. A group is merged only when the accumulated lesson (existing lesson plus
drafts) clears
minConfidenceandminOccurrencesWithCorrection(corrections) orminOccurrences(others), plus two distinct sessions whenrequireDistinctSessionsis on. Groups below the threshold stay pending (belowThreshold). - Claim the whole group. On SQL every candidate of a group is claimed first; a partially
claimed group waits for the next run. A candidate held by another live run makes the run fail
with the retryable
candidates busyerror after it finishes the rest. - Owner fence. Each finalization goes through
applyVerdictwith producerpromote; aproducer_conflictstands the run down with its claims released and nothing applied.
Judge v2
The consolidation judge’s system prompt is pinned byJUDGE_PROMPT_VERSION
(judge-v2:<first 12 hex chars of its SHA-256>), so a lesson’s origin.promptVersion names the
exact prompt that produced it. buildJudgeInput emits
{ window, anchor, tags, similarLessons, examples }: the candidate’s capture window (or, for a
pre-v2 candidate without one, a single-message window built from excerpt), up to
JUDGE_SIMILAR_K (5) similar active lessons, and up to JUDGE_EXEMPLARS_MAX (6) operator
exemplars from listLessonExemplars. The consolidation pass loads the exemplars once per run.
rankSimilarLessons scores active lessons by distinctive-token overlap with the candidate excerpt
and shows the top JUDGE_SIMILAR_K (5). Lessons with no shared token still fill any free slots,
and ties go to the newest lesson (the ranking pool is read in created_at order), so a
contradicting lesson that shares no words with the candidate can reach the judge.
validateJudgeVerdict(value, allowedLessonIds, window) keeps the base checks (action enum,
confidence in [0, 1], reason string, lessonId in allowedLessonIds) and adds the v2 rules:
add/update: non-emptytextof at mostJUDGE_TEXT_MAX_CHARS(400) characters,kindinJUDGE_KINDS(correction,preference,procedure,failure), andsourceIndexes— a non-empty integer array with every index inside the window and at least one pointing at ausermessage.delete: the samesourceIndexesrule;kindis required whenevertextis given.noop:rejectCategoryinJUDGE_REJECT_CATEGORIES(fact,one_off,automated,transient_failure,already_known,no_signal).
{ ok: false, error }, which classifies as invalid and is struck against
the candidate by the existing failure mechanism. Judge calls are capped at JUDGE_MAX_OUTPUT_TOKENS
(8,192).
On an applied verdict the effect layer (consolidation-effects.ts) writes origin
(producer: "consolidation", the redacted judge reason as rationale, the
${provider}/${model} from the analysis result, the prompt version, and the analysis job id),
sets the lesson kind from the verdict instead of the candidate tags, and stores the cited
messages as evidence[].quotes — the first three cited window messages as EvidenceQuote
entries (text sliced to 500), the primary quote being the first user-role one. The invalidate
path stores the redacted judge reason as invalidationReason. promote marks its lessons
origin.producer: "promote".
Consolidation and produce execution
runConsolidationPass accepts RunConsolidationPassParams, including optional
capPreflight?: { agentId: string; utcDay: string }. When present, the pass pre-flights the daily
budget against store.readBudgetUsage({ pass: "consolidation", agentId }):
- Cap preflight. If
usage.utcDay === preflight.utcDayandusage.spent >= maxCallsPerAgentPerDay, the run stands down before judging: it makes no model call, claims no candidates for judging, and writes nolearning_budgetreservation row. The run recordscapExhausted: trueinConsolidationRunSummary, setsbudgetSkipped = selected.length, and immediately runs the deterministic expiry sweep (expireUnsampled, finalizing untagged candidates asnot_sampled_expired). Ifpreflight.utcDayis not today, the gate stays off and per-candidate reservation remains the authority. The standalonelearning-core.consolidationpass provides nocapPreflight. - Deterministic candidate selection.
pickCandidatespartitions candidates deterministically: correction and contradiction candidates rank ahead of plain failures, followed by remaining tagged candidates, then untagged candidates. Each group is sorted newest first (endedAtdescending), so the oldest untagged candidates are the ones that expire. - Produce integration.
ProduceBodies.consolidationreceives{ producerTaskId, producerFingerprint, budgetDay, onReport }, wherebudgetDayis the lineage’s pinned reservation day, else today; the plugin’s produce body forwards it ascapPreflight.utcDay. A capped produce run recordsitems.capExhausted: true; when it finalized nothing it also recordsproducerReason: "cap_exhausted", which thetasks.runEventsallowlist insrc/gateway/server-methods/tasks-run-events.tssurfaces. With claimable candidates left, the run queues the usual next-day carry.
Distill eligibility
listDistillCandidates decides eligibility in SQL: only procedure or failure lessons with at
least 2 occurrences, or a +1 rating, or origin.producer: "operator", are selected.
Single-occurrence, unrated lessons of any other kind are never distilled.
Candidate claims and the budget ledger
consolidation and promote never apply a candidate without a claim. The order is:
claimCandidate → renewClaim → consumeBudget → model call → renewClaim → applyVerdict.
claimCandidateis a compare-and-set frompendingwith no unexpired claim. The lease is the call timeout plus 30 s, judged on the database clock.applyVerdict,recordCandidateFailure,renewClaim, andreleaseClaimall checkstatus = 'pending'and the sameclaimId. A stale claimant getsstaleand changes nothing.applyVerdictwrites the lesson effect and finalizes the candidate in one transaction. A replay of the same claim returnsalready_applied. A supersede whose predecessor already has a different successor is refused.consumeBudgetandrefundBudgetrun in one transaction each (BEGIN IMMEDIATEon SQLite,pg_advisory_xact_lockon Postgres). Denied consumes are recorded, so a retried reservation id always returns its first decision. A refund credits the day the reservation charged.- Claims, capture, budgets, lessons, proposals, and audit writes all require SQL. No operation is replayed on a file fallback when the database fails.
- Both producers key the producer bucket by the candidate row’s agent (the claim handle’s
agentId,bucketAgentId).applyVerdictrefuses any otherownerBucket, and an agent-less row is released rather than finalized. - Before the upgrade fence’s
repaired_at, every SQL learning writer throws the retryableLEARNING_REPAIR_PENDING; the fence batches live inupgrade-fence.tsandupgrade-fence-sql.ts. - Fence phases 2 and 3 read the legacy source recorded at install (
meta:legacy-source: files relative to the plugin log dir, each with its size and SHA-256). The cursor stores a relative file and an offset in that source. A process whoselegacySourceMatchesis false stands by (fence_source_mismatch,onSourceMismatch), andfenceStepitself refuses a step whosesourceDigestis not the recorded one or whosenextis not afterfrom.
pnpm test:pg. The script starts a Docker
postgres:16 container unless OPENCLAW_DATABASE_URL is set.
Apply writes under resolveManagedSkillsDir() → $OPENCLAW_STATE_DIR/skills or
~/.openclaw/skills. The protocol is hash-verified tmp + fsync + rename. After a successful
rename, a later decision-write failure must not delete the file; reconcile repairs desiredState.
searchLessons(query, identity, k) uses FTS5 (sqlite), search_tsv + GIN (postgres), or a
substring scan when optional search DDL is skipped. Hyphenated FTS5 queries are
tokenized because hyphen is FTS NOT.
Gateway and tool seams
Ten gateway methods are registered inindex.ts: learning.overview, learning.listLessons,
learning.searchLessons, learning.inspectLesson, learning.listProposals,
learning.inspectProposal, learning.decideProposal, learning.decideProposals,
learning.reviseLesson, and learning.rateLesson. The read path goes through the
store, not the raw log. This matters: leaving the read path on the JSONL log while capture moved
to SQL would show an empty list while capture silently succeeded.
The three review RPCs (gateway-lesson-review.ts) resolve one lesson the same way
inspectProposal does: params.agentId narrows to that agent’s verified scope, a cross-agent
read hides mismatched agents’ rows, and an id that resolves to more than one visible scope is
refused as ambiguous. learning.inspectLesson needs the read scope and returns the lesson detail
(origin, rating, invalidation reason, evidence with quotes), the revision chain, and the
proposals built from the lesson. learning.reviseLesson (text ≤400, optional kind, optional
note ≤500) and learning.rateLesson (score: 1 | -1, optional note) need the approvals
scope; the write gates the lesson’s own scope exactly like decide, then calls
store.reviseLesson / store.rateLesson. The audit actor comes from operatorActor
(gateway-actor.ts): the client display name plus the paired device id when one is present.
learning.listLessons rows carry producer and rating so the UI can badge operator edits and
endorsements.
learning.decideProposal looks a proposal up with an empty scope deliberately, so the lookup spans
every workspace and the proposal’s own scope comes back in the result. It then gates that scope
(scope_mismatch unless it is the proposal agent’s verified scope) and builds a scoped store from
it for the write. learning.decideProposals keeps the pre-fence contract: ids are decided in
order and the batch stops at the first failure with UNAVAILABLE failed to decide, whose
details name the failing id, its gate reason, and the decided and notAttempted ids.
learning.listLessons reads the optional LessonStore.legacyWindowTruncated() (the legacy
read-through implements it) and reports truncated when the pre-repair legacy window was cut.
learning.searchLessons filters mismatched agents after the store’s top-k, so it over-fetches
(x4 per round, at most 1,000 candidates) until k visible hits survive.
The learning tool is registered per invocation with the caller’s scope and owner flag. Every
action is refused unless senderIsOwner is true.
Glance widget
createLearningGlanceWidget registers a glance widget (id learning, title Learning,
refreshMs: 300_000) via api.registerGlanceWidget. Its render calls the same
computeLearningOverview aggregate as learning.overview with no scope filter, and returns three
lines — pending proposals, total lessons, applied proposals — pulled by glass clients through
glance.widgets.list (ADR 0107). It never mutates the store.
Capture path
Learning Core is a session consumer.onSessionWorkAvailable filters to session.end, then loops
claimSessionWork until the queue drains. When mode is off, the handler acknowledges without
persisting. Otherwise it builds the capture window (buildCaptureWindow,
capture-window.ts) from the claimed entries: user and assistant entries only -
isAutomated: true drops heartbeat, cron and subagent turns, and a legacy undefined counts as
human - each text envelope-stripped (user messages), redacted, and sliced to
CAPTURE_MESSAGE_MAX_CHARS (800). The anchor is the last user message matching isCorrection,
else the last user message; the window holds at most CAPTURE_WINDOW_MAX_MESSAGES (12) messages
ending one message past the anchor and is trimmed to CAPTURE_WINDOW_MAX_CHARS (4,000) by
dropping the oldest non-anchor messages. When no user message remains the runner returns none,
the claim is acked without a candidate, and no produce pass is enqueued - automation-only
sessions capture nothing. When a window exists the runner writes an ExtractionCandidate
carrying it (window, anchor, excerpt = the anchor text sliced to 500 characters, tags)
and acks processed. It must not call upsertLesson / mergeLesson. On a processing failure
the catch block logs api.logger.warn (message, error code, claim and session IDs) before
acking the claim as failed/retryable — a throwing ackSessionWork must never mask the real
error.
Core namespaces consumer ids as <agentId>:<pluginId>:<effectKind>, with an unscoped
<pluginId>:<effectKind> fallback and an optional /<subCursor> suffix. Anything that counts
or looks up claims must match all those shapes - an equality against a bare learning-core
matches nothing.
When mode is assist, register also listens for context.collect and prepends
ctx:{sessionKey}:lessons.active with up to maxLessonsForPrompt active lessons
(collectActiveLessons, assist-collect.ts). Do not import context-engine from this plugin.
-
Trigger gate. Heartbeat and cron turns (
isAutomatedTrigger) return before the session check, so automated turns never inject lessons and never read the lesson store. -
Host OS. A lesson may carry
hostOs("linux","darwin"or"win32", theprocess.platformvalue). The consolidation judge sets it only when the lesson names one system’s commands, paths or service managers; a rewrite without it clears it. Lessons scoped to another OS are filtered out before ranking, so they never use amaxLessonsForPromptslot. Untagged lessons inject on every host. -
Wrapper. The lessons reach the model as one block, each lesson on a dash (
-) line under the sharedASSIST_LESSONS_HEADER, which marks them advisory and subordinate to the current user message, the workspace instructions and the operator’s rules:
Blocking the agent loop
register is synchronous today. Do not add synchronous blocking I/O (fs.readFileSync,
execSync) inside it — that stalls gateway startup. Pass run functions are async and must not
block the event loop on LLM or disk work without await.
Do not do this:
"learning-core.promote") throws PLUGIN_REGISTER_ERROR at Gateway boot
(Plugin task pass id must not contain "."). Register the bare id (promote); the backbone
stores the effective id learning-core.promote.
Do this instead:
Testing
The conformance suites’ live-Postgres legs,
lesson-store-conformance.pg.integration.test.ts and
bounded-store-reads.pg.integration.test.ts, run only in pnpm test:pg. The default lanes do not
collect them, and without that lane’s database they report as skipped (describe.skipIf) rather
than passing. The conformance suite carries a mutation self-check so a suite that cannot fail is
itself a failure.
Live golden set. consolidation-judge.live.test.ts judges ten synthetic windows against the
real configured tier and asserts each fixture’s expected action, kind, or reject category. It is
collected only by the live config and skipped unless OPENCLAW_LIVE_TEST=1 and
OPENCLAW_LIVE_LEARNING_BASE_URL are set; pnpm test:live already sets OPENCLAW_LIVE_TEST=1:
OPENCLAW_LIVE_LEARNING_MODEL defaults to low; OPENCLAW_LIVE_LEARNING_API_KEY, when set, is
sent as a bearer token. The fixtures are synthetic; never point the test at a real transcript
store.
Running the Postgres store without a Postgres server
lesson-store-postgres.test-helpers.ts provides createInMemoryPgPool(), a PgPoolLike double
covering the six statement shapes PostgresLessonStore emits. It keeps the fidelity the store
depends on - JSONB decoded on read, the four-column primary key, transaction visibility, and an
error rather than an empty result when a table was never created - and throws on any statement it
does not recognise, so a store that grows a new statement shape fails loudly instead of passing
against a silent no-op.
The conformance suite runs the Postgres store twice: against this double on every host, and against
a live server in pnpm test:pg. The double is not a substitute for the live leg, which remains the
authority on real dialect behaviour.
The reachability suite exists because unit coverage of the changed function proves the unit, not
that it is reached. It drives the real claim entry point and asserts the symptom - one candidate
row per claim, zero lessons - rather than an internal return value.
Run the extension’s tests with the standard battery; there is no separate learning-core lane. Its
*.pg.integration.test.ts suites run only with pnpm test:pg.
Adding a backend
- Implement
LessonStore. - Add the dialect to
learning-schema.tsif it is SQL, keeping identifier validation in that module. - Add the backend to the union in
src/config/storage/domain-storage.tsand toSessionStorageBackendKind, so selection stays in one place. - Add it to
BACKENDSin the conformance suite and make the suite pass unmodified. - Surface open-time and operation failures without changing the authoritative backend.