Repository navigation
feat!: hold the corpus as an immutable head, write through sessions, and curate on a branch - #287
Merged
Merged
Conversation
Adds the shared MemoryRecord/HeadView/OverlayOp contract in @memhtml/contracts, three empty registered packages, and docs/v2-poc.md, the spec implementers read.
…lay sandbox @memhtml/head: MemoryRecord parsing, persistent HashMap versions with structural sharing on advance, entity/hash/frame-key/inbound indexes, BM25 plus recency RRF. @memhtml/session: per-session GIT_INDEX_FILE plumbing, overlay log on disk, validator (format, dedup, claim-edit, reserved paths, batch cap), six-step commit with disjoint check, frame-key contradicts edge, update-ref compare-and-swap. @memhtml/snapshot: Arrow IPC snapshot per commit with zero-copy html column. apps/cli/src/session-exec.ts: in-memory sandbox seeded from a HeadView, writes harvested into overlay ops. docs/design.md section 15 and a README pointer.
…urrency integration test Nine commands (session start|put|exec|commit|rebase|status, head status|search|snapshot) on the pre-app path in apps/cli/src/v2.ts; GitFailure moves to @memhtml/contracts and is re-exported by store and session; exec.ts exports its sandbox constants so session-exec.ts imports them. tests-integration/tests/v2-sessions.test.ts drives eight concurrent sessions through rebase-and-retry plus the four conflict cases through CLI envelopes. mise run check green: 80 tasks.
… commit path Validate against the version the ref is at (rebase-needed on any advance), per-id session lock (proper-lockfile) and atomic log writes, archive body from the head's current bytes with a hash identity check, checkout follows before the ref moves and a dirty session path refuses with worktree-dirty, write-ahead pending commit recovered on the next call, harvested exec ops validated before append, session start refuses an existing id unless --force, invalid --id is a usage error. mise run check 80/80 and package smoke 86/86 green on this tree.
Deletes packages/sleep (32,517 lines) and apps/consolidator (6,559 lines), the six sleep commands, the consolidate flag, the MCP sleep resource, the eval write-path arm that measured them, and the docs-site pages. Relocates what the pipeline hosted that is not curation: sandbox mounts to apps/cli/src/mount.ts, artifact generation to apps/cli/src/artifacts.ts, the salience sidecar to packages/index/src/sidecar.ts, head-edit repair to apps/cli/src/repair.ts, detected-task paths to apps/cli/src/detected-tasks.ts. Curation is a session on a curate/<date> branch behind the discrimination gate (docs/design.md section 15). mise run check: 72 tasks green.
…nation gate A curator is a session on a curate/<date> branch; memhtml curate merge <ref> refuses a missing or non-descendant ref, runs the discrimination gate in fake mode unless --skip-gate, brings the checked-out working tree along, and fast-forwards --into with update-ref compare-and-swap. session start --ref qualifies bare branch names the same way. mise run check 72/72 and package smoke 82/82 green.
…e/<date> Add @memhtml/curator: a generateText tool loop (search, read, exec, propose, status, finish) over an injected CuratorTools interface, a charter prompt read at run time, a code-computed briefing, and a budget enforced in code (40 steps, 8,000 output tokens per call, 20 min wall clock, 200 ops). Model specs: fake (scripted, credential-free), bedrock:<id>, proxy:<model>. Add `memhtml curate run` (apps/cli/src/curate-run.ts binds the tools to the real head, session, and sandbox): starts or resumes the session on curate/<UTC date>, refuses any --ref outside curate/ or the checked-out branch, lands as memhtml(curate): <report line> through a bounded rebase-and-retry loop, and reports the curate.run envelope. --dry-run uses an in-memory overlay on new and resumed sessions alike. exec refuses a harvest carrying any violation the commit would refuse. A model failure is ERR_MODEL_UNAVAILABLE at exit 1 with the session kept for --resume. Session commits take an optional scope so the curator subject differs from a plain session's. Tests use the AI SDK mock model and a closed loopback port; no live model call. mise run check 76/76, package:smoke 83/0.
… arcs and people Harvester: a seeded file whose bytes changed but whose article text hash did not is compared as parsed documents; every <link rel="memhtml-*"> added to its head becomes a link op. A removed link, a title or meta change, an article markup change, or any other head residue rejects the file with a reason naming what changed. Links added to an archive twin's head become link ops on the source ahead of the archive. A changed article stays a put, which validation still refuses as a claim edit. Validation scope: validateOps and isReservedPath take the commit scope. Under "curate" the areas/arcs/ and resources/people/ prefixes are writable; .memhtml/, index.html and sitemap.xml stay refused under every scope. commitSession passes its scope; runSessionExec takes one; the curator binder runs everything at "curate" while the plain session arms stay at "session". The fake curator now splices the supersedes link in the sandbox and calls no propose, so curate run --model fake proves edges from code mode end to end. mise run check 76/76, package:smoke 83/0.
…k with no target The first live run (Opus 5.5 through the proxy, 2026-09-23) placed 23 link ops in two minutes and then closed with prose instead of a finish call. Under toolChoice "required" the AI SDK throws on a step with no tool call, so the run was reported as a model failure with its ops stranded. The loop now runs with "auto": a text-only step ends the run and its text is the report, stoppedBy finish. validateOps now resolves every link's href: the target must be a record in the head, active or archived, or a path the same batch puts or archives, gathered before the walk because the harvester emits links ahead of the archives they point at. A dangling edge was the one thing a curator could land unnoticed.
… output ceiling The collapse run on a store clone (2026-09-24) archived 2,170 records through commitSession, and every one was rejected by the reader: the default archive stamp came from Date.prototype.toISOString, which carries milliseconds, while the format's ISO rule takes whole seconds. The archive looked empty to search and every supersedes link pointed at an unloaded file. nowIso now stamps whole seconds; a test parses the archived file with checkMemory. The same run showed the curator's 8,000-token per-call ceiling truncating every large fold proposal mid-argument (an 18-record fold needs about 10,000 output tokens). DEFAULT_BUDGET.maxOutputTokensPerCall is 32,000.
…-key agreement, and Louvain communities Four cuts in order: rulings, source plus memory type, frame key (a group folds only when its values agree; disagreement is a keep cluster naming the contradiction), and a lexical TF-IDF kNN graph cut by graphology's Louvain with a seeded generator, PageRank anchoring each cluster. Output is a JSON-serializable CollapsePlan. Louvain rather than Leiden because no maintained graphology Leiden package exists (probed 2026-09-24). Also the collapse charter (prompts/collapse.md), the per-cluster briefing, and the fake model's fold branch, so a fold runs end to end with no credential.
…ast its base
A ref that is not a descendant of --into is no longer refused. The
merge rebuilds the curator's operation log from the trees at the merge
base and at the ref's tip (apps/cli/src/replay.ts, reusing the
harvester's comparison with the archive stamps restamped on the seeded
side), validates it under the curate scope against --into's tip, runs
the gate, lands it through commitSession with a rebase-and-retry loop
bounded at MERGE_ATTEMPTS, and moves the curate ref to the landed
commit. Anything on the ref that is not an operation refuses the merge
naming the path. The payload gains replayed: null | { base, ops,
attempts, originalTip }.
…m a file's head
Add `{ kind: "unlink", path, rel, href }` to `OverlayOp`. The head overlay applies it with
`removeLink` (head-only cut, content hash unchanged) and fails on a path the view lacks, an unknown
rel, or an edge the file does not carry. `validateOps` requires an active source (or a put in the
batch), a vocabulary rel, and the edge on the source as the batch has left it, so a batch may drop an
edge it added and may not drop one twice; `touchedPaths`, the batch cap, and the reserved-path rules
count it. `commitSession` stages it like `link`, so an archive built after an unlink carries the
removal.
Every new guard is mutation-verified; the test headers name the mutation per guard.
A seeded file whose article hash is unchanged and whose head lost a `<link rel="memhtml-...">` edge yields one `unlink` op per removed edge; a file that gained one edge and lost another yields both kinds. Any other head change still rejects, with the reason now naming the edited links beside the other change. The archive twin is held to the same rule, so a link cut from the copy is an `unlink` on the source staged before the archive.
…e key One regex match through the same two guards as `frameKeyOf`, so the two accessors cannot disagree about whether a claim has a slot shape (asserted over the reference cases and under fast-check). The value is normalized the way the key is. `frameKeyOf` itself is unchanged.
…ugh the curator The briefing lists `duplicates` (one key, one value, two or more active records) and `contradictions` (one key, two or more values) instead of every multi-member key as a dedup candidate; each list keeps the 50-group cap and its uncapped total. Records of type `verdict` and `task` join no group: measured over the live store at the commit the 2026-09-23 run saw, every one of the eleven groups the model refused was a pair of verdicts sharing a headline claim (identical key and value, different articles). The charter's dedup priority now reads `duplicates` and its contradiction priority `contradictions`. `unlink` reaches the model: the `propose` schema takes it, `status` and the run payload count it, `session status` reports `unlinks`, the charter names four operations and repairs a dangling link with an unlink, and the fake model's one exec also sweeps the active buckets for dangling links, so `curate run --model fake` lands one archive, one link, and one unlink end to end. The curator now depends on @memhtml/domain for `frameValueOf`.
…adiction, not a fold A verdict record carries its judgment in the title over a claim that is the objective judged; measured on the 2026-09-22 store, one of the eleven shared frame keys was exactly that pair and the other ten were byte-identical re-mints.
…lusters on one curate/ branch Flags: --ref (under refs/heads/curate/, the curate run rule), --model, --plan, --rulings, --concurrency (default 4), --only, --limit, --dry-run, --max-steps, --wall-clock-ms. Archive clusters land through validated sessions in chunks of 180 with no model; each fold runs one curator session under the collapse charter, the driver completes every archive and supersedes link (all of them past 30 members), and every session lands through the rebase-and-retry loop with one held head advanced by delta. Payload curate.collapse; the fake model drives a whole collapse on a fixture.
…llapse in the smoke run
…and's contract, deltas, and measured timings
versionFromRecords builds a HeadVersion from parsed records with the same insertRecord fold the git load uses, so a snapshot-built version can be advanced with structural sharing. gateHeads scores a seeded sample of the records active in both versions by their titles at both versions and passes when the landed MRR is within a tolerance of the base's and the inversions (fell out of the top k, or a superseded record outranking its superseder) did not grow. HeadGateFailed carries the report.
SNAPSHOTS_DIR, listSnapshots (every <sha>.arrow newest first by mtime, staging files excluded), and pruneSnapshots, which keeps the newest four and answers the shas it removed.
…in every store The scaffold's .gitignore names both directories. An existing store's .gitignore is committed content, so ensureExcluded appends the missing patterns to .git/info/exclude once (found via rev-parse --git-path, so a linked worktree writes the common directory's file), and startSession calls it before the first write under .memhtml/sessions.
…nd gate curate merge on the head loadHeadAt takes the cheapest path that exists: the sha's own snapshot, else an ancestor's snapshot advanced over the changed paths (source snapshot+advance, with ancestorSha and reparsed), else git. session commit, curate merge, and curate run write the snapshot for the commit they made and prune to the newest four, best-effort, reported as `snapshot` in the payload. curate merge's default gate is the head gate over the two tips instead of the eval fixture gate; HeadGateFailed maps to ERR_DISCRIMINATION_FAILED. Measured on an 8,245-record clone: git 6.4-6.8 s, snapshot 2.3-2.4 s, snapshot+advance over 40 paths 2.4-2.6 s.
…ots, and the ignore rules
The case that asserts a session commit leaves no temporary index behind listed the shared OS temp dir, where the package's other test files stage their own commits at the same moment. It failed in two of three full runs of the session suite on one host, and it failed the full check too, while it passed alone. The case now points TMPDIR at a directory of its own for its two commits and asserts that directory is empty. Making the release step keep the directory fails the case with both leftover names, and three full runs of the suite pass.
…chedule Nothing in memhtml has a schedule, and the repo's census over the word holds the prose to that. ROADMAP and design.md now count the old pipeline's compress phase per run, and RUNBOOK says the example cron block exports the state plane once a day.
The dependency-review skill still named eve and the consolidator, which 0.16 removes, as the packages and the live tier to check. Its eve section is gone, its examples name just-bash, and its counts match this tree: 76 check tasks, and 91 live smoke checks. RELEASING.md and design.md count the credential-free smoke at 88 checks as of 0.16.0, from the run on this commit's parent.
…stream commit.test.ts keeps fix/v2-gauntlet-round1's plumbing-seam check of the temporary index directories over this branch's private-TMPDIR variant of the same fix.
The wire protocol restated the overlay op union without its `move` branch, so a session holding a move (from `session exec` or the curator) got a 400 from `/v1/neighbors` on every later `session put`, which then loaded the base locally. The protocol now decodes `ops` and `appended` with the log's own `OverlayOpSchema`, exported from `@memhtml/session`, so the log and the wire read the same kinds and the session log's compile-time guard covers both.
The collapse's held head ran each load on its own runtime, outside the command's stderr logger, so a line the load logged (`git merge-base exited 1` when a snapshot of another curate branch was no ancestor of the base) was written to stdout ahead of the envelope. The cache now loads in the calling fiber behind a one-permit semaphore, and the curator's tools run with the binding fiber's context, so `curate run` and `curate collapse` log to stderr and stdout carries one envelope.
`head status` spreads the head's stats into the payload, so it reports `source` at the top level, not under `head`. Its `--server` help said `head.source`. A test now runs every command whose `--server` help names a field as `server` against a live server and reads that path in the payload.
The private-terms scan skipped `apps/docs/` while the docs site's own gate lived on a separate branch. Both are merged, and the full tree passes, so the exclusion is gone and a census checks that every tracked file under `apps/docs/` is part of the scan.
…a tagged error A tagged error's message is empty, so describeError returned "" for every StorageFailure, GitFailure, InvalidMemory, and DirtyTree a fold or a head load raised. It now renders tagged errors through messageFor, as the envelope does.
…tagged error A tagged error's message is empty, so a tool that failed with InvalidMemory or StorageFailure answered the model "read failed: " with no cause. describeFailure now renders the tag and payload fields.
Keeps the v2 package names where git paired the deleted sleep and consolidator manifests with head and snapshot, moves every package release-please bumps to 0.15.2, drops test:budget from check, and regenerates the lockfile without the lhci tree.
laithalsaadoon
marked this pull request as ready for review
October 18, 2026 14:16
Contributor
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
This was referenced Oct 19, 2026
laithalsaadoon
added a commit
that referenced
this pull request
Oct 20, 2026
Moves the Effect catalog set (`effect`, `@effect/platform-node`, `@effect/platform-node-shared`, `@effect/vitest`) from 4.0.3 to 4.0.5 with no source or test change. One 4.0.4 entry changes what `packages/telemetry` does when tracing is on, so this move was held for a maintainer's decision and merged on it.
What moves:
- `pnpm-workspace.yaml:61-64`: the four catalog lines.
- `pnpm-lock.yaml`: only the four Effect entries and their peer suffixes (10 lines in the peer-stripped table).
- Docs: the 17 mentions of the pin on 15 lines in `docs/architecture/system-overview.md`, `docs/diagrams/structural/dependency-graph.md`, `docs/insights/debugging-guide.md`, `docs/insights/tech-debt.md` and `docs/reference/rpc-tools.md`. Each claim those lines make was re-checked at 4.0.5 (five MCP protocol adapters, `layerStdio`'s `instructions` option, the `@stability unstable` tags, `Schema.Struct({})` and `Tool.EmptyParams` JSON Schemas, `Config.String`). The same lines' citations into `pnpm-workspace.yaml`, `apps/cli/src/head-server.ts` and `CLAUDE.md`, stale since #265 and #287 moved those files, now name the lines they mean. Every edit keeps its cell width.
Behavior that reaches memhtml:
- Effect-TS/effect#9053 (4.0.4), telemetry on only: the OTLP exporter waits for a collector's `Retry-After` between its three retries after a 408 or 5xx, never less than the 1 s it waited before. Measured on this tree against a local collector: arrivals at 0, 2, 4 and 6 s instead of 0, 1, 2 and 3 s for a 503 with `Retry-After: 2`; unchanged without the header.
- Effect-TS/effect#9014 (4.0.4): Node HTTP text decoding drops a leading UTF-8 BOM, so a BOM-prefixed JSON body to the head server's `/v1/search`, `/v1/read`, `/v1/neighbors`, `/v1/commit` or `/v1/rebase` now decodes instead of answering 400. `/v1/exec` parses its body itself and still refuses one. memhtml's own head client never sends a BOM, so its traffic is unchanged.
- Effect-TS/effect#9136 (4.0.5): the values of `sig`, `Signature`, `AWSAccessKeyId` and `X-Goog-Signature` query parameters are redacted in the request line a head-server 400 echoes and, with telemetry on, in server span `url.full` and `url.query`. memhtml's client sends no query string.
- Measured identical on this tree: interrupt merging (#9113), JSON Schema bounds on the two new decode-only schemas (#9081), the MCP server's shared codecs (#9031, 15 tools, identical transcripts), `Duration` conversion (#9109, #9161), and server span timing (#9066).
Verified:
- `mise run check`: 75/75 tasks on this branch.
- A reader compiled all 16 TypeScript packages plus `tests-integration` against the 4.0.5 tarballs with the repo's compiler options (0 errors), with a two-way self-check: a probe using APIs that exist only in 4.0.5 (`UrlParams.redactUrl`, `NodeHttpClient.layerNodeHttpOptions`) fails on 4.0.3 and passes on 4.0.5, and a probe that #9112 breaks passes on 4.0.3 and fails on 4.0.5.
- The unit suites of `packages/session`, `head`, `curator`, `snapshot`, `telemetry`, `store`, `eval`, `apps/cli` and `apps/mcp` pass 1443/1443 on both versions.
Effect 4.0.6 is not published; its "Version Packages" PR (Effect-TS/effect#9197) queues entries on the head server's Node HTTP paths, MCP stdio streams and OTLP serialization, so the next move gets its own read.
Supersedes the Effect members of Dependabot's minor-and-patch group.
This was referenced Oct 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
memhtml 0.16 changes how the corpus is held and written. A memory file is the same file it was, and git is still the system of record. What changes is the path a write takes and where judgment happens.
Writers now work in sessions. A session sees one immutable version of the corpus, the head, plus its own log of operations.
memhtml session commitvalidates the whole log against the store's write bar, checks that the ref is still at the version it validated, marks a frame-key contradiction with acontradictsedge, and lands the log as one commit with a compare-and-swap on the ref. A writer that loses the race getsrebase-needed, rebases, and retries. Every writer of one checkout holds a checkout lock while it changes the shared index, so a v1 write and a session commit never interleave.memhtml head servekeeps the head loaded and answers over a Unix socket (a named pipe on Windows). Search,session put,session exec,session commit, andsession rebaseask it first and fall back to the local path when no server answers. MCPmemory_searchandmemory_recallask it too, so a record a session committed is searchable before the SQLite index catches up. Arrow snapshots and a vector cache under.memhtml/bound the cold start.Curation runs off the write path.
memhtml curate runis a bounded, model-driven tool loop that works as a session on acurate/<date>branch, andmemhtml curate collapsefolds clusters of near-duplicates from a deterministic plan. Onlymemhtml curate mergelands a curate branch, after a head gate scores retrieval on both versions. Whenmainmoved, the merge replays the branch's operations onto its tip as one commit.What every writer to one store must agree on lives in
memhtml.config.jsonat the store root, tracked in git: the write bar, thev1Doorsmode, and the curator's writer buckets and placement quota. With no file, neutral defaults apply. A malformed file fails closed withERR_STORE_CONFIG, andmemhtml configprints the effective policy.Why
Three measurements on a production store (2026-09-22, 8,213 files, 2,216 commits) motivated the change.
areas/inbox/. A writer picks a record's directory, retrieval never reads a path, and nothing filed a record later. The curator now files inbox records with amoveoperation that keeps the record's bytes and identity.memory_searchheld the single SQLite writer and blocked the index update behind it. Sessions commit without openingindex.db, and reads go through a head that never blocks a writer.On a 7,437-record copy of that store (2026-09-27), a search through the head server took 0.84 s at p50 from the CLI against 2.6 s locally, and 36 ms over the socket directly. On a 10,286-record fixture, a session commit took 1.2 s through the server against 3.2 s locally from a snapshot.
docs/design.mdsections 15 to 24 describe the design, and section 24 records the five decisions behind it.What was removed
@memhtml/sleeppackage, its seventeen phases, the sixmemhtml sleepcommands, and the reports under.memhtml/sleep/.apps/consolidator.memhtml apply --consolidateand MCPmemory_write_batch.consolidate, with the fields they reported.The
sleep.*response types stay inRESPONSE_TYPES, because that list is append-only, and no command answers them. The0006_sleep.sqlmigration stays applied.How to upgrade
The migration guide walks through the steps: https://memhtml.github.io/learn/operations/migrate-to-0-16/
In short, commit a
memhtml.config.jsonto the store if the defaults don't fit, install 0.16, start onememhtml head serveper store under a supervisor, and replace any scheduledmemhtml sleep runwithmemhtml curate runfollowed by a reviewedmemhtml curate merge. The sleep pipeline exported the state-plane sidecar on every run, so schedulememhtml state exportyourself. Snapshots and vector caches written by earlier builds read as format 1, so nothing needs a rebuild or a re-embed.Changes since the v2 preview branch
These surfaces existed only on the v2 preview branch and never shipped in a release, so they're listed here and not in the footer:
SOCKET_PATH_MAXis removed, replaced bysocketPathMax(platform), which counts the socket path limit in UTF-8 bytes per platform.sessionIndexFileandsessionRefare removed. Nothing writes<id>.idxorrefs/memhtml/sessions/<id>now, andmemhtml session pruneremoves old ones.snapshot.sha-mismatchis no longer raised.MEMHTML_EMBED_WARM_IDLE_MS) is off by default.BREAKING CHANGE: The six
memhtml sleepcommands (sleep run,sleep resume,sleep review,sleep merge,sleep status,sleep plan) andmemhtml apply --consolidateare removed, andmemhtml curate run,memhtml curate collapse, andmemhtml curate mergereplace them. MCPmemory_write_batchno longer takesconsolidate,memory_statusno longer reportslast_sleep, and the resource templatememhtml://sleep/{run-id}is removed. The output fieldsconsolidated_intoandsuperseded_pathon batch ops, the batch summary'sconsolidated,lastSleeponmemhtml status, andstuckSleepRunsonmemhtml doctorare removed. In a process whose environment setsMEMHTML_SESSION, the record-creating v1 doors (write,apply,correct,task add, and the MCP toolsmemory_write,memory_write_batch, andmemory_correctwhen the MCP server carries the variable) refuse withERR_SESSION_BOUNDunless the store'smemhtml.config.jsonsetsv1Doorstoopen. When a head server runs for the store, MCPmemory_searchandmemory_recallrank through it by default, with lexical and vector arms fused by RRF and recency as an exact-tie break, and no salience arm and no MMR diversification;MEMHTML_MCP_HEAD=offkeeps them on the index.Release-As: 0.16.0