A user model that remembers what was refused, beside an agent that can confirm what it inferred

xopc

A local-first TypeScript personal assistant whose memory is a SQLite user model: scoped, evidence-linked assertions and work knowledge with status, validity windows and hashed suppressions.

LicenceMIT; packages/image-providers declares Apache-2.0
Size395,225 lines of non-test TypeScript in src and 211,440 in web; the memory is src/user-model (2,853), src/user-context (3,223), src/memory-learning (1,366), src/knowledge-memory (765), src/memory-maintenance (467), the context builder and three memory tools (1,065), and the memory tables of a 4,204-line schema.sql
Activity4,710 commits on main from 3 February to 2 December 2026, almost all from one author account; 13 contributor entries including bots; latest release v0.0.527 on 2 December 2026
Tests13,133 lines opening an it or test call in 2,249 test files, on an in-memory node:sqlite database; CI runs the suite in four shards; none run for this reading

Carries 6 of 7 rubric mechanisms. Most systems here carry none or one (41%), and a dash means the mechanism was not found at this commit — not that the system needed it. Each mark is one LLM reviewer's reading of the code at this commit rather than a run of it — known limits.

  • Tombstone
  • Trust state
  • Bi-temporal
  • Scope enforced
  • Mutation audit
  • Human review
  • Negative evals

1. Executive Summary

xopc is a local-first personal assistant: a TypeScript gateway, desktop, web and mobile clients, and a personal agent called Ada. Its memory is a user model in SQLite: assertions about the owner, each in a typed slot with a scope, an authority, a status, a validity window and linked evidence, beside a store of work knowledge with the same lifecycle. A background reviewer model reads new conversation turns and proposes what to remember; code checks every quote it cites against the transcript.

Notable: every removal a person makes leaves a value-keyed refusal. Rejecting, archiving, deleting, correcting or rescoping an assertion writes SHA-256 fingerprints of the slot and value and of the statement, and the reconciler refuses a matching candidate from any path until the person restores it. A correction closes the old value's validity window and keeps the row, so when a preference changed is a query and not a guess.

Weak:

  • The agent can confirm what it inferred. user_context_update sets an assertion active with actor user when the call carries a quote that is a substring of the pending user message (src/agent/tools/user-context-tool.ts:148-155, :207-212). Only collaboration rules wait for a person.
  • The contradiction pass has no producer. The daily maintenance moves an assertion to needs_review when an evidence link with relation contradicts exists (src/memory-maintenance/service.ts:194-224); no product code writes that relation, and the user documentation describes the pass as checking contradictions.
  • Deletion takes the audit with it. Status events cascade with the assertion, and clearMemoryAudit deletes the maintenance decisions and context-retrieval rows that name it.

Licence. MIT for the repository. packages/image-providers/package.json:5 declares Apache-2.0; evals/personal/style/upstreams.json:10 names an evaluation upstream under BSD-3-Clause with Commons Clause that is downloaded separately and not redistributed.

2. Mental Model

The unit is a claim about the owner in a slot. A slot is principal, subject (user, person, goal, project, topic), predicate, cardinality and scope; a slot with single cardinality holds one current value. Each assertion in it records who said so — user_explicit, user_observed, system_inferred, external_untrusted — and the system's belief in it as a status.

Belief moves in three directions:

  1. Up, by authority or corroboration. An explicit statement from the owner is admitted active. An observation or inference is admitted as a candidate and needs two independent sources with independent quotes (src/user-model/capture/evidence-policy.ts:153-175); daily maintenance activates a candidate with two owner evidence links and no conflicting active value.
  2. Sideways, by conflict. A non-explicit value that overlaps an active one in time is stored conflicted, and both are marked when neither is explicit; an explicit value that disagrees with an explicit one is held as needs_review.
  3. Down, by time or refusal. A value past valid_to or review_at goes stale; a person's reject, archive, delete, correction or scope move removes it from use and writes its fingerprints into memory_suppressions.

What reaches the model is narrower than what is stored. canUseAssertion (src/user-model/usage-policy.ts:18-61) checks consent receipts, the evidence route, validity, permitted uses and agents, and sensitivity, and then admits an active explicit assertion as confirmed context or a strong candidate as a working assumption, rendered under a heading that says it may be wrong and never authorises an action.

Work knowledge — decisions, project facts, lessons, episodes — follows the same shape with fewer authority levels: origin_class owner, agent, system or untrusted, and a verification of supported, tentative or conflicted.

Diagram — a background reviewer's claim is refused if its fingerprint is suppressed; otherwise an explicit owner statement becomes active and an inferred one a candidate, which two owner sources promote; rejection, correction and expiry write fingerprints that block the claim's return; active claims enter the prompt as confirmed context and candidates at 0.7 or above as labelled working assumptions
Diagram source
%% caption: a background reviewer's claim is refused if its fingerprint is suppressed; otherwise an explicit owner statement becomes active and an inferred one a candidate, which two owner sources promote; rejection, correction and expiry write fingerprints that block the claim's return; active claims enter the prompt as confirmed context and candidates at 0.7 or above as labelled working assumptions
flowchart TD
    T["New transcript turns"] --> R["Background reviewer"]
    R --> Q["Quotes checked in code"]
    Q --> S{"Suppressed key?"}
    S -- yes --> X["Refused"]
    S -- no --> A{"Authority"}
    A -- "user_explicit" --> ACT["active"]
    A -- "observed / inferred" --> C["candidate"]
    C -- "2 owner sources" --> ACT
    C -- "overlaps active" --> CF["conflicted"]
    ACT -- "valid_to passed" --> ST["stale"]
    ST -- "30 days" --> AR["archived"]
    ACT -- "explicit correction" --> AR
    ACT -- "person rejects" --> RJ["rejected"]
    RJ --> F["Fingerprints written"]
    AR --> F
    F --> S
    ACT --> P["Confirmed context"]
    C -- "0.7 or above" --> W["Working assumption"]
    P --> CTX["Fenced prompt block"]
    W --> CTX

3. Architecture

Everything lives in one SQLite database opened through node:sqlite, under ~/.xopc/. The memory tables are part of a 4,204-line schema.sql:

  • User model: user_assertion_slots, user_assertions with an FTS5 mirror, user_assertion_evidence, user_assertion_status_events, user_goals and revisions, user_priority_windows, user_model_observations, user_assertion_edges, collaboration_rules.
  • Evidence: context_evidence rows with trust level, source type, content hash, conversation and message ids, and a redacted excerpt.
  • Work knowledge: knowledge_items, knowledge_revisions, knowledge_evidence_links, knowledge_item_status_events, source chunks and two FTS5 tables kept by triggers (schema.sql:3686-3716).
  • Governance: memory_suppressions, memory_maintenance_runs and memory_maintenance_decisions, execution_context_runs, _items and _feedback, learning jobs, receipts and cursors.

Three paths write:

  • MemoryLearningService (src/memory-learning/service.ts) wakes every 30 seconds, enqueues sessions from the last 30 days with new assistant turns, and runs at most three jobs per tick under a daily cap at 100 batches. Each job runs a review agent with the user-model maintainer prompt, repairs a schema or evidence failure once, and hands the parsed interpretation to the executor.
  • The personal agent's tools, during a turn.
  • The gateway, for the console: create, correct, rescope, change status, delete, review knowledge, enable rules.

Maintenance runs hourly, daily at 03:00 and weekly on Sunday at 04:00, keyed by period so a rerun is a no-op.

Deployment and ergonomics

A pnpm workspace on Node 26.12 or later with a Hono gateway, a React console and an Electron desktop shell, built on @earendil-works/pi-agent-core. Memory needs no external service; the reviewer and agent use whichever model provider is configured, and userModel.processingPolicy defaults to remote_allowed (src/user-context/config.ts). The catalog directory is a git submodule pointing at an apps repository; build scripts copy catalog/apps, and no source under src/ imports from it.

4. Essential Implementation Paths

Reconcile a candidate — reconcileAssertion (src/user-model/repository.ts:361-441), inside one write transaction:

  1. A sensitive candidate that is not explicit is refused.
  2. Consent receipts are checked for connector-derived candidates.
  3. The candidate's fingerprints are computed; with restoreDeleted and explicit authority, matching suppressions are removed first; any remaining match refuses.
  4. With correctionOfAssertionId and explicit authority, the new value is inserted active and the old one has its window closed and is archived; for a multiple-cardinality slot the old value's fingerprints are suppressed.
  5. Otherwise the candidate is a duplicate (evidence merged), a new value (no overlap or multiple cardinality), a supersession (explicit over lower authority, or a newer dynamic or event value of equal or higher authority), or a conflict.

Forget — deleteUserAssertion (:754-794) walks the supersession chain, suppresses every version's fingerprints, clears audit rows, deletes the FTS rows, strips the assertion from work-discovery candidates, deletes the assertions (status events cascade), suppresses the conversation-choice source, deletes the observations and nulls the evidence excerpts. The personal_memory forget also writes an active boundary rule that blocks automatic recall from the original conversations (src/agent/tools/personal-memory-tool.ts:164-176).

Build the turn's context — ExecutionContextCoordinator.prepare calls buildExecutionContext (src/agent/context/execution-context.ts:178-250), optionally deepens it with transcript recall, fits it to 6,000 characters, records what was injected in execution_context_*, and returns it as dynamic system context inside a <user-context> fence.

5. Memory Data Model

user_assertions (schema.sql:1175-1218) carries, besides value and statement:

Field Values
authority user_explicit, user_observed, system_inferred, external_untrusted
status candidate, active, needs_review, conflicted, stale, archived, rejected
volatility stable, slow, dynamic, event
sensitivity normal, personal, secret, regulated
time valid_from, valid_to (CHECK valid_to >= valid_from), observed_at, recorded_at, review_at, delete_after
use purpose_ids_json, allowed_uses_json, allowed_agent_ids_json, consent_receipt_id, disclosure_policy
support support_count, independent_source_count, last_supported_at

supersedes_assertion_id links versions. Volatility sets a review interval — 180 days for slow, 30 for dynamic, 7 for event (src/user-model/temporal.ts) — and current_state and event kinds must carry a bounded valid_to or enter as needs_review (repository.ts:193-198). A valid_from the extractor does not resolve is stored null, an open start, and not defaulted to record time.

knowledge_items (schema.sql:1774-1805) has nine kinds, scope, a canonical_key, status, confidence, a validity window with expires_at and review_at, origin_class, derived_from_recalled_context, record_class (memory or source index) and verification. Replacing an item writes a knowledge_revisions row.

memory_suppressions is fingerprint TEXT PRIMARY KEY, created_at (schema.sql:1657-1660). An assertion has two keys (repository.ts:744-752): one over principal, scope, subject, predicate and — for a multiple-cardinality slot only — the normalised value; one over principal, scope and statement. Knowledge keys are canonical key and content.

6. Retrieval Mechanics

Assertions. listUserAssertions returns active and candidate rows newest first, capped at 1,000 (execution-context.ts:191, repository.ts:460-475). Each passes scopeVisible (global, or the turn's agent, workspace, project or session), applicabilityVisible (operation, channel and similar conditions) and canUseAssertion, then is scored on importance, consequence, actionability, confidence and recency, with 0.05 off for a candidate. Items scoring under 0.12 are dropped unless high-consequence; confirmed items sort first; 20 are kept.

Knowledge. searchKnowledgeItems (src/knowledge-memory/repository.ts:442-491) runs FTS5 BM25 with status = 'active', the validity window and a scope visibility clause in SQL, then knowledgeExclusion (src/knowledge-memory/usage-policy.ts:21-70) drops conflicted, tentative, sensitive, revoked or changed-source items. A second arm searches source chunks. Query text is split into terms — Han characters as unigrams and bigrams — and up to 32 are ORed. There is no vector index.

Continuation. A query with 继续, 上次, 进度, 之前, continue, progress or last time adds up to three recent project or work-thread items (:232).

Rendering. Rules, goals, priorities, confirmed context and working assumptions are fitted to the character budget round-robin by category so one cannot starve the others (:293-348).

Agent reads. user_context_search, _get and _read apply the same scope and usage checks; the MCP server exposes active rules and user context read-only (src/mcp/user-context-tools.ts:132).

7. Write Mechanics

Background capture. The reviewer returns a zod-validated interpretation: assertions, goals, rules and intents (remember, correct, confirm, forget). Code, not the model, decides admission:

  • every evidence ref must quote a user-role entry (src/user-model/capture/semantic.ts:193-203); non-owner spans are masked;
  • inferred confidence is capped at 0.85 and authority comes from assessAssertionSupport;
  • confirm and forget take effect only when the owner's own text carries the directive (src/user-model/capture/executor.ts:139-158);
  • a candidate is restored past a suppression only when the latest user entry holds an explicit command (:317-319).

In-turn tools. personal_memory (registered only on the personal agent's surface, src/agent/tools/factory.ts:885) takes remember, correct, forget and scope, requires an explicit-request keyword in authored text outside quoted spans, and checks the target's version. knowledge_write stores an agent item as candidate, tentative, at 0.7. Compaction promotion writes an episode item and, when promotable, a durable agent item at 0.82 (src/agent/memory/compaction-promotion.ts).

Maintenance. runMemoryMaintenance (src/memory-maintenance/service.ts) purges expired observations, stales expired assertions, priorities and knowledge, moves contradicted assertions to review, activates corroborated candidates, activates supported agent knowledge at 0.7, repairs indexes and archives knowledge stale for 30 days. Each change writes a memory_maintenance_decisions row with before and after JSON.

Operational cost

  • Blocking: the per-turn context build is synchronous SQLite: one read of up to 1,000 assertions, one FTS query per knowledge arm, one audit write. Optional deep recall adds a transcript FTS search behind a timeout.
  • Lag: what the user says is learned only after the next learning tick and a full model call; the in-turn tool is the immediate path.
  • Whole-store passes: maintenance scans up to 1,000 rows per transition class per run; learning enqueues up to 200 sessions per scan.

8. Agent Integration

The context arrives as a fenced system block, separated into confirmed context and labelled assumptions, with the per-turn record kept for feedback (execution_context_feedback) and shown in the console. The personal agent gets personal_memory; user_context_update is registered when the personal tools are not configured or when allowed (factory.ts:898-926), and knowledge tools at :928-962. Writes from tools return receipts that carry no memory text.

9. Reliability, Safety, and Trust

Suppression is the strongest part. Every person-driven removal writes fingerprints, and the only delete from memory_suppressions is restoreMemory (src/user-context/memory-suppression.ts:20), reached from an explicit restore in the executor and the console's create route (src/gateway/hono/routes/user-model.ts:532). Two consequences follow from the key:

  • For a single-cardinality slot the key omits the value, so rejecting "prefers concise answers" refuses any later inferred value of preference.response.detail in that scope, not just "concise".
  • The in-turn personal_memory remember calls reconcileAssertion without restoreDeleted and throws memory_suppressed (src/agent/tools/personal-memory-tool.ts:197-212), while the background reviewer and the console restore the same request.

Confirmation by the agent. user_context_update confirm needs only that the supplied quote appear somewhere in the pending user message. A one-word quote such as "yes" satisfies it, and the assertion becomes active with authority user_explicit and confidence 1 (repository.ts:690-711). personal_memory correct of knowledge runs edit_and_approve with actor user (personal-memory-tool.ts:218). Ordinary memories need no approval by design (docs/user-understanding.md).

Contradiction. Conflict is detected at reconciliation time by slot and overlapping validity, and that path works. The separate daily pass that reads relation = 'contradicts' has no writer: every product insert into user_assertion_evidence passes supports, and the one contradicts row in the tree is inserted by raw SQL in src/memory-maintenance/__tests__/service.test.ts:101.

Revocation. Revoking a connector grant removes its evidence links, recomputes support, and moves a non-explicit assertion left without consent or with fewer than two supports to needs_review with a status event (src/user-context/sources/repository.ts:180-230).

Marks withheld

  • audit_log. user_assertion_status_events and knowledge_item_status_events are ON DELETE CASCADE, and clearMemoryAudit deletes memory_maintenance_decisions and execution_context_items for a deleted object (memory-suppression.ts:24-27) — by design, since the documentation promises deletion of the audit entries. Several status writes also bypass the event table: the same-value correction and the duplicate path (repository.ts:381, :405), setUserAssertionScope (:714-742), and a knowledge replace that does not change status. The nearest miss is memory_maintenance_decisions with before and after JSON per change.

10. Tests, Evals, and Benchmarks

The unit suite runs on an in-memory node:sqlite database with no skip path, and CI runs it in four shards (.github/workflows/test-suite.yml). The memory tests are specific:

  • src/user-model/__tests__/user-model.test.ts covers a correction closing the old window at 3,999 for a new value valid from 4,000, conflict, non-overlapping history, chain deletion with suppression and FTS cleanup, restore, rejection, sensitive inference, multiple-value correction, scoped deletion and event supersession.
  • src/agent/context/__tests__/execution-context.test.ts:73-102 requires the context to equal exactly the project-one knowledge item with another project's item stored; :104-116 requires a corrected preference absent and its replacement present.
  • src/knowledge-memory/__tests__/repository.test.ts:131-180 asserts exact visible key sets with agent, workspace, import and connector items stored.

Weak assertions: repository.test.ts:56 is not.toEqual(expect.arrayContaining(['other-session', 'expired'])), which passes when only one of the two leaks; the cases at execution-context.test.ts:139-158, :187-190 and :192-212 assert empty results where nothing eligible was stored.

Evaluations under evals/memory/ are opt-in runs against a real model with reports written to an ignored directory. evals/personal/memory is a LongMemEval stratified diagnostic over 120 questions and a Chinese fixture set; docs/design/technical/personal-memory-baseline-2026-10-22.md records 72/120 on LongMemEval native QA and 41/64 on the Chinese development set. No raw result files are committed.

11. For Your Own Build

Steal

  • Two fingerprints per claim — slot plus value, and statement — written by every removal and consulted inside the reconciliation transaction.
  • Close the old validity window at the new value's start minus one, archive the row, and keep it.
  • A working-assumption tier: an unconfirmed inference that may enter the prompt under a label that forbids acting on it.
  • Code-checked evidence: every quote the extractor cites must be found in a user-role entry before anything is admitted.

Avoid

  • An agent-callable confirm whose only guard is a substring of the user's message.
  • A single-valued slot key without the value, unless a refusal really should block the whole predicate.
  • Deleting the audit trail with the subject when the subject can be erased and the trail redacted.

Fit: a single-owner assistant that must learn from conversation, keep corrections sticky and explain what it injected.

12. Open Questions

  • Is the contradicts relation meant to be written by a reviewer intent not yet wired, or is the daily pass vestigial?
  • Does the console show inferred rules as a review queue? The disabled state and reviewRequired flag are written; the console view was not read.
  • Is the value-free single-slot key intended to block re-learning a changed preference after a rejection?

Appendix: File Index

  • src/storage/sqlite/schema.sql — memory tables, FTS5, triggers.
  • src/user-model/repository.ts — slots, reconciliation, status, deletion, fingerprints.
  • src/user-model/usage-policy.ts, src/user-model/temporal.ts — admission to context, validity.
  • src/user-model/capture/semantic.ts, evidence-policy.ts, executor.ts — extractor schema, grounding, execution.
  • src/user-context/memory-suppression.ts, src/user-context/config.ts — suppressions, defaults.
  • src/user-context/sources/repository.ts — grant revocation.
  • src/knowledge-memory/repository.ts, usage-policy.ts, search-text.ts — work knowledge.
  • src/memory-maintenance/service.ts — scheduled transitions.
  • src/memory-learning/service.ts, src/agent/background-review/ — background capture.
  • src/agent/context/execution-context.ts, coordinator.ts — per-turn context.
  • src/agent/tools/personal-memory-tool.ts, user-context-tool.ts, knowledge-memory-tool.ts, factory.ts — agent tools.
  • src/storage/sqlite/collaboration-rule-repository.ts, src/gateway/hono/routes/user-model.ts — rules and console routes.

Not read: connectors and collectors in depth, home intelligence, work discovery beyond the onboarding confirm, deep recall beyond its query planning, compaction beyond promotion, voice, the mobile and desktop apps, the web console, extensions, most of the evaluation harness, and the catalog submodule, which is not checked out.

Recorded searches

All run in the clone at the pin with git grep.

  • git grep -n -i -E 'embedding|sqlite-vec|vec0|cosine' -- src/user-model src/knowledge-memory src/agent/context src/retrieval — no match. The same pattern over src matches src/agent/prompt/sanitize-for-prompt.ts:2.
  • git grep -n "DELETE FROM memory_suppressions" -- src — only src/user-context/memory-suppression.ts:20.
  • git grep -n -E "'contradicts'" -- src — reads in maintenance and the test insert at src/memory-maintenance/__tests__/service.test.ts:101; no product writer.
  • git grep -n "INSERT INTO user_assertion_evidence" -- src — src/user-model/repository.ts:271, :298, :618, :674; every caller of linkAssertionEvidence passes supports.
  • git grep -n restoreDeleted -- src/agent/tools — no match. The same pattern over src/gateway matches routes/user-model.ts:532.
  • git grep -n setCollaborationRuleStatus -- src — the repository, its export and routes/user-model.ts:701.
  • git grep -n -E 'createCollaborationRule\(' -- src — the personal-memory forget boundary, forget capture, bootstrap, the executor, work-discovery onboarding and a console route; no agent tool creates a rule otherwise.
  • git grep -n -E "UPDATE user_assertions SET[^;]*status" -- src — maintenance, source revocation and repository.ts:346, :381, :405, :700.
  • git ls-files -s catalog — mode 160000, a submodule; no src import of catalog.

History

2026-12-02 — 33e462f5…. First reading, at the user's request from the 2026-12-02 triage shortlist, from a shallow clone at the head of main, read only; commit and contributor counts come from the GitHub API. Screened before reading: three auto-run surfaces (.cursor/rules/deveco-flow.mdc; .gitmodules, which pulls further trees on a recursive clone; opencode.json, whose MCP entries start local servers); one build-time surface, prepublishOnly running the test, build and release scripts. 40 manifests and lockfiles inside the seven-day cooldown, an upper bound because a shallow clone dates every file to the tip; 19 unpinned surfaces; AGENTS.md read as data. The memory subsystem and its tests were read; the parts named under Not read in the appendix were not. Nothing was installed, built or run, and no test was run. Six marks: tombstone, trust_state, bitemporal, scope_enforced, human_review, negative_eval.