Skip to main content

somnians · 蝶花半梦(Viola Somnians)

Deduplicate the memory you already have. Scan for near-duplicates → have your own seat adjudicate each pair → soft-delete in one transaction → roll back one batch at a time. Every step leaves an audit trail.

[English](README.md) · [中文](README.zh-CN.md)

mem0 / Zep / Letta decide at write time whether something gets stored. This tool handles a different pile: duplicates that have already settled in your store — the rule you wrote twice, three times, five times across 3,000 records.

The artifact is a CLI. A library would need a host first; a prompt would need something that can run prompts. A CLI needs one line after install, and it prints numbers you can check. The seven subcommands are independent, so you can wire it into any store without changing yours.

Naming: Chinese name 蝶花半梦, Latin name Viola Somnians (pansy + dream). Commands and package name are somnians — the name is free on PyPI; viola was taken.

scan → candidate groups → seat verdicts (merge / keep apart) → apply (soft delete) → rollback (by batch)
                                      └── audit_merge + audit_change: two tables, every step

Install, then read the numbers

pipx install .        # or pip install .
somnians demo         # replays two seats' recorded verdicts offline: no network, no key

# or skip installing: the repo ships a zero-install entry
./somnians demo
Public gold set, 26 cases: CANARY×2, COMPRESS×4, LIMIT×4, NONENTRY×5, OBJECT×4, POLARITY×4, VALUE×3

seat             accuracy  reversed   canary   verdict
perch(auto)      26/26     0.0%       all pass usable
qwen3.8-flash    25/26     0.0%       all pass usable

1 disagreement: T10 — perch says keep apart (correct); qwen merges it (flattens the channel difference between a message and an email)

How to read it: accuracy = agreement with the gold labels, denominator 26 (canaries included); if any canary fails, the whole reading is void. Change the seats or the corpus and these numbers move; the row only claims what these two seats score on this criterion set, reproducibly.

Read those two rows as a self-test: change the seat or the criterion, print them again, and only then decide whether to trust the rest.

One criterion

The cost of a merge = the information in drop that keeper does not have.

  • drop has more than keeper (a qualifier, an exception, a second object, a different value, an opposite tone) ⇒ keep apart
  • drop has less than keeper (abbreviated form, fragment, dropped modifier, different word order, one extra preposition) ⇒ merge
  • Opposite polarity (one forbids, one permits) ⇒ keep apart

On top of that sits a pre-filter (structural, not semantic): annotations and status words, fragments under 8 characters with no predicate, pure punctuation/numbers/emoji, receipt chatter ⇒ not an entry at all; verdict "keep apart" and list them by name. Skipping this layer backfires: something like 全批。 ("approve the whole batch") has no information to lose, so the criterion would say "merge", and merging it into a keeper only pollutes the text.

Three contracts, and nothing else

// records.jsonl — export your own store into this
{"id":"a1","text":"归档时必须包含 AGENTS.md 文件,并记录背景信息及遇到的问题","is_deleted":false}

// candidates.jsonl — produced by scan, one line per pair
{"group":"G01","keeper":"a1","drop":"a2","score":0.8421,"keeper_text":"…","drop_text":"…"}

// decisions.jsonl — seat verdicts
{"group":"G01","verdict":"并", ...}

No database, no ORM, no MCP host. Exporting is about 20 lines of code.

Any field these three contracts do not name is carried through untouched: apply and rollback rewrite the whole line and only change is_deleted (plus merged_into on the drop). An upstream source or source_client column can therefore ride along even though this tool has no idea what it means — passthrough, not a criterion. selfcheck holds that to a test.

Seven subcommands

# 1. scan candidates (default threshold 0.62, deliberately low: scan handles recall, the seat handles precision)
./somnians scan --in records.jsonl --out candidates.jsonl

# 2. hand them to your seat. Adapter contract: the command receives a brief path as argv[1],
#    prints ID|并 (merge) or ID|不并 (keep apart), one per line
./somnians adjudicate --in candidates.jsonl --out decisions.jsonl \
    --adapter ./my-seat.sh --brief-out brief.md \
    --jobs 3         # three seats in parallel, candidates split by group
    --retry 2        # truncation recovery: resend only the missing groups, at most twice

# 3. commit (soft delete + audit; the original file is backed up as .bak-<batch>)
./somnians apply --records records.jsonl --decisions decisions.jsonl --batch dream-20261118

# 4. restore one batch (a single line; the audit table keeps an op=rollback record)
./somnians rollback --records records.jsonl --batch dream-20261118

# 5. crash recovery (only needed when apply was cut off midway; with no journal it does nothing)
./somnians recover --records records.jsonl --db somnians-audit.db --batch dream-20261118

# 6. self-check (offline, no network): data root / canary / optimization reconciliation / audit schema / apply-rollback round trip
./somnians selfcheck        # expect SELFCHECK_PASS, exit code 0

# 7. demo — offline replay of two recorded seats (see "Install" above)
./somnians demo

Before writing anything, apply proves its own backup: it reads .bak-<batch> back, computes sha256 and compares it with the original, and aborts before touching the target if they differ (exit code 3). "The file is still there" is not proof.

Languages

Runtime copy ships in three catalogs: English / 简体 / 繁體. Order of choice: --lang > SOMNIANS_LANG > LC_ALL / LC_MESSAGES / LANGUAGE / LANG > English. C, POSIX and empty values are skipped; an unrecognised tag falls back to English instead of guessing.

./somnians demo                    # follows your locale
SOMNIANS_LANG=zh-Hant ./somnians demo
./somnians --lang en selfcheck

Three things are never translated: the verdict values 并 / 不并 / 未判 (they are the JSONL contract, so a translated run still writes the same bytes), the SELFCHECK_PASS / SELFCHECK_FAIL tokens, and every number, ID, path and exit code. Traditional Chinese is a static catalog, not a runtime conversion: the CLI is zero-dependency and offline, and 一简对多繁 (发→發/髮, 干→乾/幹) means a runtime guess makes the reader guess again. Vocabulary differences (數據 vs 資料) belong to a review pass, not to a silent substitution.

Two surfaces stay out of scope on purpose: the seat brief written by adjudicate --brief-out is the experimental stimulus — translating it would change what the recorded verdicts measure, so it stays Chinese byte for byte. And --help is a fixed bilingual table (English term plus Chinese gloss) rather than a per-language render: a flag you half-guessed should read the same either way.

The order inside apply, and what a half-way break leaves behind

A torn state — store updated, file not updated — hurts more than a crash, so the order is fixed:

① back up + read back + compare hash   ② write a staging file (original untouched)
③ write the journal <records>.journal-<batch>   ④ atomic rename (os.replace)
⑤ commit the transaction   ⑥ delete the journal

Both breakpoints have a recovery path that selfcheck exercises:

Breakpoint What you find What to do
after ④, before ⑤ file merged, store has no audit row somnians recover writes the audit from the journal; rollback then works normally
after ③, before ④ file untouched, journal present somnians recover decides "never took effect", drops the journal, changes nothing

recover looks at the file's actual state, not at whether a journal exists. Journal present, rename not done → no audit to write.

An adapter can be one shell script

#!/usr/bin/env bash
# my-seat.sh — anything that can read a brief and answer verdicts: curl, a local model, another agent
BRIEF="$1"
curl -s https://your-endpoint/v1/chat/completions \
  -H "Authorization: Bearer $YOUR_KEY" -H 'Content-Type: application/json' \
  -d "$(python3 -c 'import json,sys;print(json.dumps({"model":"your-model","messages":[{"role":"user","content":open(sys.argv[1]).read()}]}))' "$BRIEF")" \
| python3 -c 'import json,sys;print(json.load(sys.stdin)["choices"][0]["message"]["content"])'

You fill in the model. That is where vendor decoupling lives: the protocol is "one brief in, n lines of ID|并/ID|不并 out", and who answers is not baked into the repo.

Why the default threshold is 0.62, not 0.75

Records are short. A near-duplicate that differs by one character or two drops to around 0.5 under 3-gram Jaccard. So the score is max(3-gram Jaccard, character-sequence similarity) and the threshold stays low to collect more candidates. Scan over-collects (recall); the seat rejects (precision) — a two-stage split that one threshold cannot replace.

Large stores: inverted index, plus a ruler you can re-run

scan prunes candidates with a 3-gram inverted index by default. Scoring is unchanged (still max(3-gram Jaccard, sequence similarity)):

Data Full pairwise --exact Inverted (default) Candidate pairs Identical?
Real store, 3,201 records 174.6 s 14.5 s 808 pair by pair, score by score
Synthetic 3,120 (many isomorphic short lines) 82.4 s 7.0 s 80,114 hits the cap; the number is not usable as-is

How to reproduce (measured on one Mac, 2026-11-18):

python3 scripts/make_bench.py --n 3120 > /tmp/bench.jsonl    # the synthetic row
./somnians scan --in /tmp/bench.jsonl --out /tmp/a.jsonl --exact     # slow ruler
./somnians scan --in /tmp/bench.jsonl --out /tmp/b.jsonl             # inverted

--exact is the ruler: re-check any speed-up against it; a speed-up without that row is not a result. --cap (default 500) is the high-frequency gate — a 3-gram whose posting list is longer than that stops contributing pairs, and the moment it triggers, a warning is printed: the real store's largest posting list is 362, so nothing was skipped; the synthetic distribution does skip, and there --exact or a bigger --cap is the only honest answer.

What this does not do

  • ⛔ Does not touch your storage: reads JSONL, writes JSONL plus one audit table
  • ⛔ Does not commit on its own: apply is run by a human; adjudicate only produces verdicts
  • ⛔ Does not deduplicate at write time: that is mem0 / LangMem's job; this handles the existing pile
  • ⛔ Does not lock you to a vendor: the adapter is your script; the repo ships no vendor client
  • ⛔ Ships no private memory: data/public-cases.jsonl is entirely synthetic traps

Concurrency and truncation

Free and small-model seats often cut off mid-stream. adjudicate fills gaps only instead of rerunning the batch:

round 1: 1/2 groups (concurrency 1)
retry 1: resend the 1 missing group → G02
verdicts 2/2 groups → decisions.jsonl

When retries run out and groups are still missing: exit code 2, and those groups are written as 未判 (undecided) in decisions — never silently recorded as "keep apart". --jobs 3 splits candidates by group and dispatches concurrently; the seats do not affect each other. A single seat's timeout is handled by --timeout.

Files

somnians                    # zero-install entry (run straight from the repo)
.github/workflows/selfcheck.yml  # CI: 3.9/3.11/3.13, self-check + readings + inverted-index reconciliation
scripts/make_bench.py       # synthetic stress data (reproduces the timings above)
examples/seat.py            # seat adapter example (returns fixed verdicts without an endpoint; pipeline only)
src/somnians/cli.py         # implementation: one file, no dependencies (stdlib + sqlite3)
src/somnians/data/
  public-cases.jsonl        # public gold set, 26 cases (traps + canary, no private content)
  recorded/                 # two seats' recorded verdicts (IDs and verdicts only, no record text)
  sample-records.jsonl      # 8 runnable samples
pyproject.toml              # for pipx / pip install; data installs with the package
LICENSE                     # MIT
README.zh-CN.md             # Chinese original of this file
CONTRIBUTING.zh-CN.md       # Chinese original of CONTRIBUTING
CHANGELOG.zh-CN.md          # Chinese original of CHANGELOG

Name

Chinese name 蝶花半梦, Latin Viola Somnians, identifier somnians everywhere.

Read literally, 蝶花半梦 is butterfly-flower, half-dream: the butterfly takes the flower for the thing it loves; the half-dream is the stretch before waking. The mechanism answers to the same image — two records close enough to merge, but not yet beyond doubt, are a half-dream; a half-dream is not merged. The name stays in the title; readers of other languages can treat it as flavour.

Viola is the violet genus; read the Latin as the dreaming violet. The Chinese text never names the plant — one image, not a botanical footnote.

The image has a second layer this tool does not wire: 庄周梦蝶 — writer and written, or whether a record came from the agent's own sleep or from input that actually happened. There is no criterion for that here, because the tool never looks at provenance: it compares text. The blank is deliberate, not a to-do.

Every identifier stays ASCII — see the naming table in CONTRIBUTING.md.

Where the criterion came from

The criterion and the pre-filter both come from one real incident on 2026-11-17: two of four seats read "drop is missing a word" as "keep apart" (direction reversed), and chatter like 全批。 got merged into body text. Both became canaries. The failing cases in the gold set are pitfalls already stepped in, not invented exercises.

When to come back and edit this file

  • A second seat reverses direction on a criterion that was "obvious" → add the case to the gold set first, then fix the wording here.
  • Someone reads the CLI as "a library with a thin wrapper" → the "The artifact is a CLI" paragraph failed; rewrite it with the actual install line.
  • --exact and the inverted index disagree on one pair → stop publishing timings until they agree again.
  • Someone proposes a second criterion, or one more metaphor layer, for this tool → answer two questions first: does that information change a merge/keep decision, and can it be read from the input JSONL without a guess? Two "no"s mean it does not belong here.
  • A new subcommand lands → update "Seven subcommands", the file tree, and CONTRIBUTING's subcommand row in the same commit.

© 2026 东十四 (Tungsisos) · @L4ST-afk · MIT License

Metadata

Release files for somnians 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for somnians 0.1.1
File Size Uploaded Provenance Actions
somnians-0.1.1.tar.gz 36.0 kB With provenance Details for somnians-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for somnians 0.1.1
File Interpreter ABI Platform Actions
somnians-0.1.1-py3-none-any.whl Python 3 none any Details for somnians-0.1.1-py3-none-any.whl

Total release size: 66.8 kB

Release files / somnians-0.1.1.tar.gz

Download URL somnians-0.1.1.tar.gz
Size 36.0 kB
Tags Source
SHA-256 checksum
How to use checksums
d96e866f8f6b5696dcfc95d37f5d683bae1768c89ff3fc2aa9a7acaf80639f55
BLAKE2b-256 checksum
How to use checksums
f69e4934fb88e11f2d2f2e46d10c3411084dabcc30b4a69ab7c1cb3a825829f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / somnians-0.1.1-py3-none-any.whl

Download URL somnians-0.1.1-py3-none-any.whl
Size 30.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c57400e9b2067e6ad925e24d1dc4b7a958d47b35a9b549cad47c907f670fb683
BLAKE2b-256 checksum
How to use checksums
713542b540153b753ac7ce412a9bea2367cfbc9bced7934729ffbf443a7f2e74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for somnians 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for somnians-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page