Skip to content

Contracts

1. What the package is

@memhtml/contracts is the innermost workspace package: it imports only effect, and every other package imports it. It holds the closed vocabularies, the path algebra, the edge model, and the typed failures — the words the rest of the system agrees on. Closed vocabularies lists the vocabularies’ values; this page lists every exported symbol, 133 across 9 modules, as the source documents it.

Module Exports What it holds
checkout-lock.ts 13 The checkout lock: one cross-process lock per repository that every writer of the SHARED git index holds while it changes that index and moves the branch the checkout follows.
edges.ts 22 The four non-mixing edge classes. The class is what keeps a person or task edge out of PageRank, MMR, and the retention bridge count. Every memory-graph query filters edge_class = 'memory', and the SQL CHECK constraint refuses a rel that belongs to another class.
errors.ts 11 A driver or filesystem rejection, reduced to the operation that failed. The payload deliberately excludes SQL text, parameters, and row contents so a storage error can be returned to an agent without leaking corpus content; the driver’s own message goes to Effect.logError at the adapter edge instead.
guidance.ts 3 The recall discipline: how an agent uses a memory store well, stated once.
paths.ts 25 Path algebra. Every function here is pure and total, and a path is always the repo-root-relative git-tree form: no leading slash, forward slashes only.
record.ts 7 The v2 record plane: what one memory file becomes once parsed, and the read-only view of a corpus version that every v2 package codes against.
slug.ts 11 Slug rules. A slug is the filename stem and the path is the id. There is no uuid anywhere in the system, so the slug carries the whole burden of being stable, readable, and filesystem-safe on every platform git runs on.
store-config.ts 20 The store’s policy file: what every process that writes to one store must agree on, kept at the store root and tracked in git beside the corpus, so a clone carries its rules with it.
types.ts 21 The memory type vocabulary, closed. Ten values, restated by the files.memory_type CHECK constraint in SQL.

2. By module

Each table row is one exported name: what kind of thing it is (a name declared as both a schema value and its type is one row), its declaration’s own first line, and the first paragraph of its doc comment. A symbol whose comment runs longer is quoted in full beneath the table.

2.1. checkout-lock.ts

The checkout lock: one cross-process lock per repository that every writer of the SHARED git index holds while it changes that index and moves the branch the checkout follows.

Two kinds of writer share one checkout, and neither can see the other’s half-done state:

  • The v1 store stages with git add and then commits the WHOLE shared index (git commit). A commit that runs while another writer has staged something sweeps that something into its own commit, under its own subject.
  • A v2 session commit moves the shared index and working tree to its new tree (read-tree -m -u) and then compare-and-swaps the ref. Between the two the index is one commit ahead of HEAD.

Interleaved, the v1 commit takes the session’s new file into its own commit, the session’s swap loses, the session’s rollback leaves the file staged as deleted, and the next v1 commit removes it from the branch. So each holds this lock around its sequence: the store from its first stage to its commit (and its compensation on failure), the session commit around the checkout update, the swap, and the rollback.

It lives here, with zero I/O of its own, because the two writers are packages that cannot import each other (@memhtml/session never imports @memhtml/store), and they must agree on three things or the lock excludes nothing: the lock’s path, its timing, and the reentrancy key below. The filesystem half arrives as an injected function (AcquireLockDirectory), which each side implements with proper-lockfile (an atomic mkdir of <target>.lock whose mtime the holder refreshes, so a holder killed with no chance to clean up goes stale and is reclaimed).

Symbol Kind Declaration Summary
CHECKOUT_LOCK_PATH constant const CHECKOUT_LOCK_PATH = ".memhtml/checkout" The lock’s target, relative to the repository root. proper-lockfile’s lock is the directory .memhtml/checkout.lock beside it; the target itself is never created.
CHECKOUT_LOCK_STALE_MS constant const CHECKOUT_LOCK_STALE_MS = 10_000 How long the lock may go without an mtime refresh before another writer may reclaim it. A live holder refreshes every CHECKOUT_LOCK_UPDATE_MS, so only a holder that died (or whose event loop stalled for this long) loses it.
CHECKOUT_LOCK_UPDATE_MS constant const CHECKOUT_LOCK_UPDATE_MS = 2_000 How often a holder refreshes the lock’s mtime.
CHECKOUT_LOCK_WAIT_MS constant const CHECKOUT_LOCK_WAIT_MS = 15_000 How long a writer waits for another writer to release the lock before it gives up with CHECKOUT_LOCKED. Holds are milliseconds (a session’s checkout update and swap) to about a second (a v1 batch), so this is a short wait rather than fail-fast: the two writers are different callers, and the loser should take its turn rather than fail. It is longer than CHECKOUT_LOCK_STALE_MS, so a waiter outlasts a lock left by a killed holder and reclaims it.
CHECKOUT_LOCK_FIRST_PAUSE_MS constant const CHECKOUT_LOCK_FIRST_PAUSE_MS = 10 The first pause between attempts; pauses double up to CHECKOUT_LOCK_MAX_PAUSE_MS.
CHECKOUT_LOCK_MAX_PAUSE_MS constant const CHECKOUT_LOCK_MAX_PAUSE_MS = 250 The longest pause between two attempts.
CHECKOUT_LOCKED constant const CHECKOUT_LOCKED = "checkout.locked" The StorageFailure operation a writer gets when the wait ran out.
CHECKOUT_LOCK_FAILED constant const CHECKOUT_LOCK_FAILED = "checkout.lock" The StorageFailure operation for a lock that could not be taken for any other reason (EACCES).
LockDirectoryOptions interface interface LockDirectoryOptions … The options each attempt hands the injected acquisition: proper-lockfile’s, narrowed to what is used.
AcquireLockDirectory type type AcquireLockDirectory = ( … Take the lock at target once, or reject. A lock another live holder owns rejects with an error whose code is ELOCKED; any other rejection is a failure the wait does not retry. Resolves with the release.
CheckoutLockHeld constant const CheckoutLockHeld = Context.Reference<ReadonlySet<string>>( … The lock targets the current fiber already holds. A nested acquisition of a held target runs its effect directly instead of waiting on itself until the wait runs out, so a writer that holds the lock and calls another that takes it (a task status change that archives) cannot deadlock. Provided per call, so it scopes to the holder’s own effect and the fibers it forks, never to a sibling.
CheckoutLockOptions interface interface CheckoutLockOptions … undocumented
withCheckoutLockUsing function const withCheckoutLockUsing … The checkout lock over an injected acquisition: withCheckoutLockUsing(acquire)(target, effect) runs effect holding the lock at target.

withCheckoutLockUsing

The checkout lock over an injected acquisition: withCheckoutLockUsing(acquire)(target, effect) runs effect holding the lock at target.

  • Waits up to waitMs for another holder, pausing 10 ms and doubling to 250 ms between attempts, then fails with StorageFailure CHECKOUT_LOCKED. The wait is interruptible between attempts; each attempt is uninterruptible and registers its release in the same step, so an interrupt never strands a lock this fiber took.
  • Releases on every exit: success, failure, defect, and interruption.
  • Reentrant per fiber (CheckoutLockHeld): a nested call for a target this fiber holds runs effect without a second acquisition.
  • A compromised lock (reclaimed by another writer because this holder missed its refreshes for CHECKOUT_LOCK_STALE_MS) is logged when the holder finishes, instead of proper-lockfile’s default of throwing from a timer, which would kill the process mid-sequence.

2.2. edges.ts

The four non-mixing edge classes. The class is what keeps a person or task edge out of PageRank, MMR, and the retention bridge count. Every memory-graph query filters edge_class = 'memory', and the SQL CHECK constraint refuses a rel that belongs to another class.

Symbol Kind Declaration Summary
EDGE_CLASSES constant const EDGE_CLASSES = ["memory", "person", "provenance", "task"] as const The four non-mixing edge classes. The class is what keeps a person or task edge out of PageRank, MMR, and the retention bridge count. Every memory-graph query filters edge_class = 'memory', and the SQL CHECK constraint refuses a rel that belongs to another class.
EdgeClass schema, type const EdgeClass = Schema.Literals(EDGE_CLASSES) undocumented
MEMORY_RELS constant const MEMORY_RELS = [ … The nine memory rels. supersedes and contradicts are penalty-bearing: they gate the retention contested_status signal, so one counts only when it’s authored into both files rather than left in the rebuildable index.
MemoryRel schema, type const MemoryRel = Schema.Literals(MEMORY_RELS) undocumented
PERSON_RELS constant const PERSON_RELS = ["about_person", "authored_by"] as const The two person rels, pointing at resources/people/*.
PersonRel schema, type const PersonRel = Schema.Literals(PERSON_RELS) undocumented
PROVENANCE_RELS constant const PROVENANCE_RELS = ["from_session"] as const The one provenance rel, linking a memory to the session that produced it.
ProvenanceRel schema, type const ProvenanceRel = Schema.Literals(PROVENANCE_RELS) undocumented
TASK_RELS constant const TASK_RELS = ["blocks", "subtask_of"] as const The two task rels, both between two task files.
TaskRel schema, type const TaskRel = Schema.Literals(TASK_RELS) undocumented
ALL_RELS constant const ALL_RELS = [...MEMORY_RELS, ...PERSON_RELS, ...PROVENANCE_RELS, ...TASK_RELS] as const Every rel across all four classes. The edges.rel column’s full vocabulary.
EdgeRel schema, type const EdgeRel = Schema.Literals(ALL_RELS) undocumented
relClassFor function const relClassFor = (rel: EdgeRel): EdgeClass => … The class a rel belongs to. Total over ALL_RELS and injective per class: a rel name appears in exactly one class, which is what lets the class be derived rather than carried alongside the rel and risk disagreeing with it.
relsForClass function const relsForClass = (edgeClass: EdgeClass): ReadonlyArray<EdgeRel> => … The rels of one class. The inverse of relClassFor, as a set.
isEdgeRel function const isEdgeRel = (rel: string): rel is EdgeRel => … True when rel is in the closed vocabulary. Narrows an untrusted string.
EDGE_PROVENANCES constant const EDGE_PROVENANCES = ["authored", "sleep", "import"] as const Where an edge came from. sleep marks the mined edges of the pipeline removed in 0.16.
EdgeProvenance schema, type const EdgeProvenance = Schema.Literals(EDGE_PROVENANCES) undocumented
REL_TOKEN_PREFIX constant const REL_TOKEN_PREFIX = "memhtml-" A <link rel> token, which is the rel prefixed for the HTML plane. rel tokens cannot hold a colon, so the prefix is hyphenated and the rel’s own underscores become hyphens: laterally_related ⇒ memhtml-laterally-related.
relTokenFor function const relTokenFor = (rel: EdgeRel): string => … The HTML <link rel> token for a rel.
relForToken function `const relForToken = (token: string): EdgeRel undefined => …`
Edge schema, type const Edge = Schema.Struct( … One edge. derived separates a machine-mined suspicion from an authored assertion: the retention contested_status signal counts only derived: false contradictions, so an uncorroborated machine guess can never evict a memory.
isWellFormedEdge function const isWellFormedEdge = (edge: Edge): boolean => … True when an edge’s declared class matches its rel and it is not a self-loop, the two conditions the edges table’s CHECK constraints enforce, stated once here so a caller can refuse a bad edge before the driver does.

TASK_RELS

The two task rels, both between two task files.

Their own class for the same reason the person rels have one: task topology is working state, and a blocks edge entering PageRank would let an agent’s to-do list reweight the retention of its knowledge. @memhtml/store’s linkMemories refuses a task rel unless BOTH endpoints are tasks, and the edges CHECK refuses the rel under any other class.

Edge

One edge. derived separates a machine-mined suspicion from an authored assertion: the retention contested_status signal counts only derived: false contradictions, so an uncorroborated machine guess can never evict a memory.

strength is unitless in [0, 1]; an authored edge is 1.0 and a mined one carries its cosine. srcPath/dstPath are repo-root-relative with no leading slash.

2.3. errors.ts

A driver or filesystem rejection, reduced to the operation that failed. The payload deliberately excludes SQL text, parameters, and row contents so a storage error can be returned to an agent without leaking corpus content; the driver’s own message goes to Effect.logError at the adapter edge instead.

Symbol Kind Declaration Summary
StorageFailure class class StorageFailure extends Schema.TaggedError<StorageFailure>()("StorageFailure", … A driver or filesystem rejection, reduced to the operation that failed. The payload deliberately excludes SQL text, parameters, and row contents so a storage error can be returned to an agent without leaking corpus content; the driver’s own message goes to Effect.logError at the adapter edge instead.
GitFailure class class GitFailure extends Schema.TaggedError<GitFailure>()("GitFailure", … A git subprocess exited non-zero, or could not be spawned. command is the subcommand name only, never the full argv, because arguments carry memory paths and commit subjects carry memory titles, and a GitFailure is returned to an agent through a tool response. The stderr text goes to Effect.logError at the spawning boundary instead of into the payload.
WriteConflict class class WriteConflict extends Schema.TaggedError<WriteConflict>()("WriteConflict", … Two writers touched the same file. ourSha is the blob sha this process wrote from, theirSha the blob sha now in the tree. Recovery belongs to the caller: re-read the current content and reapply.
ModelUnavailable class class ModelUnavailable extends Schema.TaggedError<ModelUnavailable>()("ModelUnavailable", … Bedrock refused the call: throttling, an unavailable model, or a denied region.
InvalidMemory class class InvalidMemory extends Schema.TaggedError<InvalidMemory>()("InvalidMemory", … A memory that violates the file format or the type/placement vocabulary.
PathNotFound class class PathNotFound extends Schema.TaggedError<PathNotFound>()("PathNotFound", … A repo-root-relative path with no file behind it.
DuplicateContent class class DuplicateContent extends Schema.TaggedError<DuplicateContent>()("DuplicateContent", … The content hash already belongs to an active file. existingPath is what the caller wanted to create, so a deduped write is answerable without a second query.
DirtyTree class class DirtyTree extends Schema.TaggedError<DirtyTree>()("DirtyTree", … An operation that requires a clean tree found uncommitted changes.
LlmContractViolation class class LlmContractViolation extends Schema.TaggedError<LlmContractViolation>()( … The model broke its structured-output contract: an undecodable tool payload, a max_tokens stop, or a refusal. The item is reported with no result, and a violation does not become a value.
StoreConfigInvalid class class StoreConfigInvalid extends Schema.TaggedError<StoreConfigInvalid>()( … The store’s policy file (memhtml.config.json at the store root) could not be read or does not decode. Fails closed: every write that needs the policy refuses rather than running under the library defaults, because a typo in a policy file must not loosen the policy it states. path is the file; reason names what is wrong and where.
V1DoorClosed class class V1DoorClosed extends Schema.TaggedError<V1DoorClosed>()("V1DoorClosed", … A v1 door that creates a record was called where the store’s v1Doors mode closes it. door is the command or tool (write, memory_write); session is the MEMHTML_SESSION the process carries, or null when the mode is closed and no session is set.

GitFailure

A git subprocess exited non-zero, or could not be spawned. command is the subcommand name only, never the full argv, because arguments carry memory paths and commit subjects carry memory titles, and a GitFailure is returned to an agent through a tool response. The stderr text goes to Effect.logError at the spawning boundary instead of into the payload.

Declared here rather than in @memhtml/store because two packages spawn git: the store through its Git service, and @memhtml/session through its own execFile (it needs GIT_INDEX_FILE, which the store scrubs). One class means one _tag, so the CLI’s ERR_GIT mapping and an instanceof check hold for either producer.

2.4. guidance.ts

The recall discipline: how an agent uses a memory store well, stated once.

The CLI’s GUIDE teaches the mechanics of the binary (the envelope, the three write doors, when to batch, the authoring rule). The MCP tool descriptions teach each tool’s arguments. Neither says WHEN to recall, how to treat a hit, when to write, or how to cite, and an agent that has only the mechanics answers from a gap it could have searched. This module is that missing layer, and it is in @memhtml/contracts so that every surface renders the same words: the manifest’s recall-discipline guide topic, the fenced block memhtml integrations install writes into a host’s instruction file, the skill it installs, and the pointer the retrieval tools carry.

The text names both doors where they differ (memory_search on MCP, memhtml search on the CLI) so the same paragraph is correct whichever surface the reader is on. Written in the second person to an agent mid-task: action first, every claim true of this build.

Symbol Kind Declaration Summary
RECALL_DISCIPLINE constant const RECALL_DISCIPLINE: ReadonlyArray<string> = [ … One paragraph per rule, in the order an agent meets them: recall, read, cite, reinforce, write.
RECALL_DISCIPLINE_TEXT constant const RECALL_DISCIPLINE_TEXT = RECALL_DISCIPLINE.join("\n\n") The discipline as one string, paragraphs joined by a blank line: the form a guide topic renders.
RECALL_DISCIPLINE_SHORT constant const RECALL_DISCIPLINE_SHORT … Two sentences for a surface that cannot carry the paragraphs, appended to the retrieval tools’ descriptions so an MCP-only agent still meets the two rules that most often go wrong.

2.5. paths.ts

Path algebra. Every function here is pure and total, and a path is always the repo-root-relative git-tree form: no leading slash, forward slashes only.

Symbol Kind Declaration Summary
ARCS_DIR constant const ARCS_DIR = "areas/arcs" Behavioral arcs. Under areas/ because PARA is fixed at four buckets.
PEOPLE_DIR constant const PEOPLE_DIR = "resources/people" The person plane, folded into resources/ rather than given its own bucket. Placement never routes here: a person record is written at an explicit path by curation (placementFor).
INBOX_DIR constant const INBOX_DIR = "areas/inbox" Where a memory lands when no rule claims it. memhtml doctor reports inbox depth as a health signal, so an unplaceable memory is visible rather than lost.
TASKS_SUBDIR constant const TASKS_SUBDIR = "tasks" The directory segment every task file sits under, appended to its workspace’s project directory or to the inbox.
ARCHIVE_BUCKET constant const ARCHIVE_BUCKET = "archive" The bucket eviction moves into, partitioned by year.
MEMORY_EXTENSION constant const MEMORY_EXTENSION = ".html" The file extension every memory carries.
normalizePath function const normalizePath = (path: string): string => … Reduce a caller-supplied path to the canonical git-tree form: leading slashes dropped (callers may pass the <link href> document-reference form), repeated slashes collapsed, trailing slash dropped.
paraBucketOf function `const paraBucketOf = (path: string): ParaBucket undefined => …`
memoryPathViolation function `const memoryPathViolation = (path: string): string undefined => …`
isValidMemoryPath function const isValidMemoryPath = (path: string): boolean => memoryPathViolation(path) === undefined True when a path is a usable memory path: rooted in a PARA bucket, ending in .html, carrying no . or .. segment.
PlacementInput interface interface PlacementInput … What placementFor decides from. path is the caller’s explicit override.
placementFor function const placementFor = (input: PlacementInput): string => … The directory a memory belongs in, following design §2.1’s five rules in order (explicit path, arc, task, workspace, primary tag), else the inbox. Total: it always returns a directory rooted in a PARA bucket, so the write path never guesses twice and never fails.
memoryPathFor function const memoryPathFor = ( … The full path for a new memory. An explicit valid path is authoritative and returned verbatim in canonical form; otherwise the directory comes from placementFor and the filename from filenameFor over the title’s slugifyStem stem, which date-prefixes an episodic entry.
archivePathFor function const archivePathFor = (path: string, year: number, generation = 1): string => … The archive path a memory moves to on eviction: archive/<YYYY>/<original-path>, with the original path mirrored exactly beneath the year.
archiveSlotFor function const archiveSlotFor = ( … The slot an archive of path in year writes: the first generation isHeld does not claim, starting from the bare year, with “held” meaning a record (active or archived) the caller’s view or tree already has at the slot. Every writer that archives takes this slot, and the session validator refuses any other.
originalPathFor function `const originalPathFor = (archivePath: string): string undefined => …`
isArchivePath function const isArchivePath = (path: string): boolean => originalPathFor(path) !== undefined True when a path sits under the archive bucket with a year partition.
archiveYearOf function `const archiveYearOf = (path: string): number undefined => …`
archiveGenerationOf function `const archiveGenerationOf = (path: string): number undefined => …`
compareArchivings function const compareArchivings = (a: string, b: string): number => … Order two archive paths by the archiving each records, for sort: negative when a is the earlier, positive when it is the later, 0 for the same year and generation. A later year is later, and within a year a higher generation is, since each archive takes its year’s first free slot. A path that is not an archive path sorts before every one that is.
activeRecordPathViolation function `const activeRecordPathViolation = (path: string): string undefined => …`
DETECTION_PREFIX constant const DETECTION_PREFIX = "det-" The filename prefix that makes a detected task recognizable from its path alone: a task a detector minted at det-<digest>-<slug>.html, with no author column and no commit message to read. memhtml task list --detected filters on it and the curator’s briefing reads it, so both agree about what a detected path is.
DETECTION_DIGEST_CHARS constant const DETECTION_DIGEST_CHARS = 12 Hex characters of the digest carried in a detected task’s path.
detectionKeyOf function `const detectionKeyOf = (path: string): string undefined => …`
isDetectedTaskPath function const isDetectedTaskPath = (path: string): boolean => detectionKeyOf(path) !== undefined True when a path, live or archived, is a detected task’s.

TASKS_SUBDIR

The directory segment every task file sits under, appended to its workspace’s project directory or to the inbox.

A subdirectory rather than a fifth bucket: PARA is fixed at four, and a task belongs to whatever the memory beside it belongs to. Keeping tasks in one named segment is what makes ls projects/<slug>/tasks the list operation, which is the design’s CRUDL-without-retrieval contract. The segment name is therefore part of the contract.

normalizePath

Reduce a caller-supplied path to the canonical git-tree form: leading slashes dropped (callers may pass the <link href> document-reference form), repeated slashes collapsed, trailing slash dropped.

The trailing slash is removed by endsWith/slice rather than by /\/+$/, which is not a style choice: an unanchored-left \/+$ is quadratic on a long run of slashes followed by a non-slash, measured 2026-08-18 at 4 ms / 57 ms / 769 ms / 3049 ms for n = 2k / 8k / 32k / 64k. The collapse above happens to defuse it — after it, no run of two slashes survives, so the pattern can only ever match one character — but that made the cost of this function depend on the ORDER of three chained calls, with nothing stating it and nothing checking it. Reordering them, or dropping the collapse, would reintroduce a multi-second stall on 64 KB of input across this function’s callers, all of which sit on the write path that accepts agent-supplied paths. A single-character slice cannot be reordered into a hazard. packages/contracts/tests/paths.test.ts asserts the cost curve at adversarial sizes.

memoryPathViolation

Why a path is not a usable memory path, or undefined when it is one.

The RULE and its explanation in one function, because a refusal that restated the rule in its own words would be a second copy of it, free to name a clause this function does not check. A caller that refuses an unusable path quotes this string; isValidMemoryPath is the same question asked as a boolean.

Each clause names the input it saw rather than the rule in the abstract, so a caller holding the message can act without re-reading the format doc. The traversal clause is the security one: it is what keeps a caller-supplied path from escaping the memory repo.

isValidMemoryPath

True when a path is a usable memory path: rooted in a PARA bucket, ending in .html, carrying no . or .. segment.

memoryPathViolation asked as a boolean, so the predicate and the refusal’s reason cannot disagree about which paths are usable.

PlacementInput

What placementFor decides from. path is the caller’s explicit override.

Every optional field also admits undefined explicitly. Under exactOptionalPropertyTypes a bare path?: string would refuse placementFor({ path: params.path, … }) for a string | undefined param, forcing every tool adapter to strip absent fields by hand. The contract therefore accepts the shape the MCP and CLI layers actually hold.

placementFor

The directory a memory belongs in, following design §2.1’s five rules in order (explicit path, arc, task, workspace, primary tag), else the inbox. Total: it always returns a directory rooted in a PARA bucket, so the write path never guesses twice and never fails.

Returns the directory, not the full path, because the filename needs a title this input does not carry. memoryPathFor composes the two. An explicit path contributes its directory; when that path is unusable it is ignored rather than propagated, so the return stays a valid bucket and this function stays total.

Totality is why the refusal cannot live here. A caller that wants an unusable path refused rather than re-derived asks the store for it (strictPath on a WriteInput), which gates on memoryPathViolation before any of this runs and quotes its reason. Refusing here instead would make placement fallible for every caller, including a curator that places a synthesized arc and has no caller path to be wrong about.

archivePathFor

The archive path a memory moves to on eviction: archive/<YYYY>/<original-path>, with the original path mirrored exactly beneath the year.

year is a calendar year (a label, not an offset). Mirroring the whole original path is what makes the mapping injective and invertible, so git log --follow reads through the move and diff -M reports it as R100 rather than a delete plus an add.

generation numbers the archivings of one path within one year. The first is the bare year; a path archived again while that slot is held goes to archive/<YYYY>.2/<original-path>, then .3, and so on, so an archive never writes over an earlier one. archiveSlotFor picks the generation.

archiveSlotFor

The slot an archive of path in year writes: the first generation isHeld does not claim, starting from the bare year, with “held” meaning a record (active or archived) the caller’s view or tree already has at the slot. Every writer that archives takes this slot, and the session validator refuses any other.

Generations are tried in order, so the answer is the lowest free one and the slots of one path fill without gaps. It terminates for any predicate that holds for finitely many slots, which is every predicate over a real tree.

compareArchivings

Order two archive paths by the archiving each records, for sort: negative when a is the earlier, positive when it is the later, 0 for the same year and generation. A later year is later, and within a year a higher generation is, since each archive takes its year’s first free slot. A path that is not an archive path sorts before every one that is.

Not the paths’ string order, which puts archive/2031.2/ before archive/2031/ (. sorts before /) and archive/2031.10/ before archive/2031.9/.

activeRecordPathViolation

Why a path cannot name an active record, or undefined when it can: the source an archive move takes, and the task a status change edits.

Two clauses, in order. A path that is not a usable memory path is refused with memoryPathViolation’s own reason, because normalizePath keeps . and .. segments: the filesystem resolves ./archive/2031/x.html and areas/../archive/2031/x.html to an archived file, while the bucket read below sees . and areas, and archivePathFor would copy the spelling into the destination. A leading . or .. segment is named as such, ahead of the bucket clause it would otherwise trip, so ./projects/x.html is not told it has no bucket. A path in the archive bucket is already archived, year partition or not, because the index reads every path under archive/ as archived. Archiving one again would nest it under archive/<YYYY>/archive/, where originalPathFor maps it back to an archive path rather than to a live one.

DETECTION_DIGEST_CHARS

Hex characters of the digest carried in a detected task’s path.

Twelve, which is git’s own abbreviated-sha width. It leaves 48 bits against a queue whose size a cap holds in the tens, and it costs 17 characters of the 80-character slug budget rather than 68.

2.6. record.ts

The v2 record plane: what one memory file becomes once parsed, and the read-only view of a corpus version that every v2 package codes against.

MemoryRecord is a flat projection of one file. It carries the raw html so a version of the corpus can be materialized into a sandbox or a snapshot without going back to git, and it carries every field the indexes derive so an index rebuild never re-parses. HeadView is the read surface of one immutable version: the head process implements it over a persistent map, a session implements it over head-plus-overlay, and a test implements it over a plain Map.

Paths are repo-relative with no leading slash (areas/inbox/x.html). Link hrefs keep the file format’s root-relative form (/areas/inbox/x.html); hrefToPath and pathToHref convert.

Symbol Kind Declaration Summary
RecordLink interface interface RecordLink … The v2 record plane: what one memory file becomes once parsed, and the read-only view of a corpus version that every v2 package codes against.
RecordFacet interface interface RecordFacet … undocumented
MemoryRecord interface interface MemoryRecord … undocumented
HeadView interface interface HeadView … One immutable version of the corpus, read-only.
OverlayOp type type OverlayOp … One entry in a session’s overlay log. A session never edits an active claim in place: a changed claim is a put of a new file plus an archive of the old one, linked by a supersedes edge. link and unlink are the edge edits: each names one (rel, href) edge on one file. label and unlabel are the entity edits: each names one memhtml-entity value on one file. All four are head-only and none touches the article, so the record’s content hash survives every one of them. move relocates one active record to a new live path with its bytes unchanged (plus any head edit the batch made to it first), so its content hash, blob, and creation time travel with it; html names which article is meant, as an archive’s does. It is the placement op: an inbox record filed under areas/<slug>/ or resources/<tag>/. A move repoints nothing by itself: every live edge to the old path is moved by an unlink and a link in the same batch, and validateOps refuses a batch that leaves one behind.
hrefToPath function const hrefToPath = (href: string): string => (href.startsWith("/") ? href.slice(1) : href) undocumented
pathToHref function const pathToHref = (path: string): string => (path.startsWith("/") ? path : '/${path}') undocumented

RecordLink

The v2 record plane: what one memory file becomes once parsed, and the read-only view of a corpus version that every v2 package codes against.

MemoryRecord is a flat projection of one file. It carries the raw html so a version of the corpus can be materialized into a sandbox or a snapshot without going back to git, and it carries every field the indexes derive so an index rebuild never re-parses. HeadView is the read surface of one immutable version: the head process implements it over a persistent map, a session implements it over head-plus-overlay, and a test implements it over a plain Map.

Paths are repo-relative with no leading slash (areas/inbox/x.html). Link hrefs keep the file format’s root-relative form (/areas/inbox/x.html); hrefToPath and pathToHref convert.

2.7. slug.ts

Slug rules. A slug is the filename stem and the path is the id. There is no uuid anywhere in the system, so the slug carries the whole burden of being stable, readable, and filesystem-safe on every platform git runs on.

Symbol Kind Declaration Summary
SLUG_MAX_LENGTH constant const SLUG_MAX_LENGTH = 80 Maximum slug length in characters, before any collision suffix.
SLUG_MIN_WORD_CUT constant const SLUG_MIN_WORD_CUT = 60 The fewest characters a word-boundary cut may leave. A slug cut at its last word boundary inside the budget keeps at least this many, else it is cut at the budget itself: a boundary further back would drop most of a title whose last word inside the budget is long.
SLUG_FALLBACK constant const SLUG_FALLBACK = "untitled" The stem used when a title reduces to nothing sluggable, such as an all-punctuation or non-Latin title. A placeholder beats an empty filename, and memhtml doctor can find these by name.
slugify function const slugify = (title: string): string => … Kebab-case a title into [a-z0-9-], at most SLUG_MAX_LENGTH characters.
slugifyStem function const slugifyStem = (title: string): string => … The filename stem a new record takes from its title: slugify’s kebab-case, with a longer title cut at its last word boundary inside SLUG_MAX_LENGTH when that keeps at least SLUG_MIN_WORD_CUT characters, else at SLUG_MAX_LENGTH itself. A cut stem is still a valid slug and, when it can be, ends on a whole word rather than a fragment of one. Equal to slugify for every title whose slug fits the budget.
isSlug function const isSlug = (value: string): boolean => … True when a string is already a valid slug, the fixed point of slugify and slugifyStem.
withCollisionOrdinal function const withCollisionOrdinal = (slug: string, ordinal: number): string => … Append a collision suffix. ordinal is a 1-based ordinal for display in the filename; ordinal 1 is the unsuffixed slug, 2 becomes -2, and so on, matching the -2/-3 convention. The suffix is added inside the length budget, so a maximum-length slug is shortened rather than overflowed, and the stem is cut by the rule slugifyStem cuts with: at its last word boundary inside the room left when that keeps SLUG_MIN_WORD_CUT characters, else at the room itself.
EPISODIC_PREFIX_LENGTH constant const EPISODIC_PREFIX_LENGTH = 9 The YYYYMMDD- prefix an episodic filename carries. Time is part of an episodic entry’s identity and it never receives a correction in place, so the date belongs in the name; every other type is timeless and correctable, so it gets a bare slug.
datePrefix function const datePrefix = (at: Date): string => … Format an instant as the YYYYMMDD stamp of an episodic filename, in UTC.
filenameFor function const filenameFor = (input: … The filename for a memory: 20260802-slug.html for episodic, slug.html otherwise. The date prefix sits outside the slug’s length budget, because it is identity, not title.
hasDatePrefix function const hasDatePrefix = (filename: string): boolean => /^\d{8}-/.test(filename) True when a filename carries the YYYYMMDD- episodic prefix.

slugify

Kebab-case a title into [a-z0-9-], at most SLUG_MAX_LENGTH characters.

Diacritics are folded to their base letters (déployé ⇒ deploye) rather than dropped, so a title stays recognizable. Runs of separators collapse to one hyphen and the result carries no leading or trailing hyphen, which makes the function idempotent: a slug fed back in comes out unchanged.

Truncation cuts at SLUG_MAX_LENGTH and then trims any hyphen the cut exposed, so a truncated slug is still a valid slug rather than one ending mid-separator.

This is the slug of every name that is recomputed each time it is used: a workspace’s projects/<slug>/ folder, a tag’s resources/<slug>/, and the names the curator matches against them. Its cut never changes, so a long workspace or tag stays one folder. A new record’s filename stem, computed once when the record is minted, is slugifyStem’s.

slugifyStem

The filename stem a new record takes from its title: slugify’s kebab-case, with a longer title cut at its last word boundary inside SLUG_MAX_LENGTH when that keeps at least SLUG_MIN_WORD_CUT characters, else at SLUG_MAX_LENGTH itself. A cut stem is still a valid slug and, when it can be, ends on a whole word rather than a fragment of one. Equal to slugify for every title whose slug fits the budget.

Only a filename stem takes this cut, because a stem is computed once, when a record is minted, and the path is the record’s id from then on: the rule decides new filenames and never moves an existing file. A folder name is recomputed on every write and keeps slugify’s cut.

withCollisionOrdinal

Append a collision suffix. ordinal is a 1-based ordinal for display in the filename; ordinal 1 is the unsuffixed slug, 2 becomes -2, and so on, matching the -2/-3 convention. The suffix is added inside the length budget, so a maximum-length slug is shortened rather than overflowed, and the stem is cut by the rule slugifyStem cuts with: at its last word boundary inside the room left when that keeps SLUG_MIN_WORD_CUT characters, else at the room itself.

The result never equals the input, at any slug length. That is what makes the store’s collision loop (packages/store/src/store.ts, pathFor) terminate rather than re-propose the name that collided. It is not free near the length cap: for a slug whose own tail IS the suffix, cutting to make room and appending the suffix can rebuild the slug — and because the cut also trims any hyphen it exposes, the rebuild can recur at MORE than one cut width. The stem is therefore re-cut from its own post-trim length until appending the suffix no longer reproduces the input; each re-cut strictly shortens the stem, so the loop terminates and the result stays inside the budget.

2.8. store-config.ts

The store’s policy file: what every process that writes to one store must agree on, kept at the store root and tracked in git beside the corpus, so a clone carries its rules with it.

The library’s defaults are neutral: the write bar refuses no type and requires no anchor, the v1 record doors close only inside a run session, and the curator treats no directory as a writer’s bucket. A deployment that wants a stricter bar writes the file; nothing in the code names one deployment’s choices.

Decoding is strict and fails closed. An unknown key (requireAnchors for requireAnchor), a value of the wrong type, an unknown memory type, or a type listed twice is refused with a reason naming where the file broke, never read as “unset”: a typo in a policy file must not loosen the policy it was meant to state. This module is pure; the read lives in the CLI (store-config.ts).

Symbol Kind Declaration Summary
STORE_CONFIG_FILE constant const STORE_CONFIG_FILE = "memhtml.config.json" The file’s name, at the store root. Not a memory: it does not end in .html.
V1_DOOR_MODES constant const V1_DOOR_MODES = ["open", "closed-in-session", "closed"] as const How the v1 doors that create a record (memhtml write, apply, correct, task add, and the MCP memory_write, memory_write_batch, memory_correct tools) behave. They commit straight to the store with no write bar, where a session is judged by it.
V1DoorMode type type V1DoorMode = (typeof V1_DOOR_MODES)[number] undocumented
PLACEMENT_QUOTA_MAX constant const PLACEMENT_QUOTA_MAX = 200 The most records one curator run may file, restating BATCH_CAP in @memhtml/session (which this package cannot import): a run’s moves and their repoints land in one commit of at most that many ops, so a larger quota could never be met.
DEFAULT_PLACEMENT_QUOTA constant const DEFAULT_PLACEMENT_QUOTA = 60 The quota when the file sets none: 60 placements plus their repoints fit one proposal.
StoreConfig schema, type const StoreConfig = Schema.Struct( … The file’s shape. Every key is optional; an absent key is the library default.
WriteBarPolicy interface interface WriteBarPolicy … The write bar’s policy half: what validateOps refuses beyond format and integrity.
CuratorPolicy interface interface CuratorPolicy … undocumented
StorePolicy interface interface StorePolicy … The whole effective policy, every key resolved.
DEFAULT_WRITE_BAR constant const DEFAULT_WRITE_BAR: WriteBarPolicy = … The library’s own write bar: no refused type, no anchor rule.
DEFAULT_V1_DOORS constant const DEFAULT_V1_DOORS: V1DoorMode = "closed-in-session" undocumented
DEFAULT_CURATOR_POLICY constant const DEFAULT_CURATOR_POLICY: CuratorPolicy = … undocumented
DEFAULT_STORE_POLICY constant const DEFAULT_STORE_POLICY: StorePolicy = … undocumented
STORE_POLICY_KEYS constant const STORE_POLICY_KEYS = [ … Every key the file can set, as a dotted path, in the order memhtml config reports them.
StorePolicyKey type type StorePolicyKey = (typeof STORE_POLICY_KEYS)[number] undocumented
StorePolicySource type `type StorePolicySource = “file” “default”`
StorePolicySources type type StorePolicySources = Readonly<Record<StorePolicyKey, StorePolicySource>> undocumented
refusedTypeReason function const refusedTypeReason = (type: string): string => … The reason a type listed by name alone gives when the bar refuses it.
storePolicyOf function const storePolicyOf = ( … The policy a decoded file states, every absent key at its library default, and each key’s source.
decodeStoreConfig function const decodeStoreConfig = ( … Decode the file’s text: { ok: true, config }, or { ok: false, reason } naming what is wrong and where. JSON that does not parse, a top level that is not an object, an excess key at any depth, a value outside its key’s type, and a type refused twice are each a reason, never a default.

V1_DOOR_MODES

How the v1 doors that create a record (memhtml write, apply, correct, task add, and the MCP memory_write, memory_write_batch, memory_correct tools) behave. They commit straight to the store with no write bar, where a session is judged by it.

  • open: always open.
  • closed-in-session: closed in a process whose environment carries MEMHTML_SESSION, the session an agent runtime hands every subprocess of a run, and open elsewhere. The library default, because it is the session contract: a process that has a barred door uses it.
  • closed: closed in every process; records go in through sessions only.

Reads and the edits of existing records (link, archive, task status, reinforce) are not record-creating doors and no mode closes them.

2.9. types.ts

The memory type vocabulary, closed. Ten values, restated by the files.memory_type CHECK constraint in SQL.

arc is in the vocabulary but absent from WRITABLE_MEMORY_TYPES: an arc is synthesized by curation from many memories, so an agent naming one directly would be asserting a conclusion the corpus has not yet earned.

task is ONE axis with the other nine rather than a parallel kind column, because three overlapping type vocabularies is what made the predecessor memory system’s classification unanswerable. A task is a memory type whose retrieval, dedup, and curation treatment a filter states, not a second axis. Tasks are default-excluded from search and shielded from curation. See @memhtml/index’s assembleScope and @memhtml/curator’s isShielded.

Symbol Kind Declaration Summary
MEMORY_TYPES constant const MEMORY_TYPES = [ … The memory type vocabulary, closed. Ten values, restated by the files.memory_type CHECK constraint in SQL.
MemoryType schema, type const MemoryType = Schema.Literals(MEMORY_TYPES) undocumented
WRITABLE_MEMORY_TYPES constant const WRITABLE_MEMORY_TYPES = MEMORY_TYPES.filter( … The nine types memory_write exposes. arc is system-written only, so the tool parameter enum is narrower than the storage vocabulary by exactly that one value.
WritableMemoryType schema, type const WritableMemoryType = Schema.Literals([ … undocumented
isWritableMemoryType function const isWritableMemoryType = (type: MemoryType): type is WritableMemoryType => type !== "arc" True for the nine types an agent may write. Narrows, so a caller can branch on it.
PARA_BUCKETS constant const PARA_BUCKETS = ["projects", "areas", "resources", "archive"] as const PARA’s four buckets, closed and ordered. archive is a bucket rather than a status because eviction is a git mv. The path itself records the state, so git log --follow reads through it and diff -M reports the move as R100.
ParaBucket schema, type const ParaBucket = Schema.Literals(PARA_BUCKETS) undocumented
MemoryStatus schema, type const MemoryStatus = Schema.Literals(["active", "archived"]) The status a memory file carries in memhtml-status.
TASK_STATUSES constant const TASK_STATUSES = ["todo", "doing", "blocked", "done"] as const A task’s own status, carried in memhtml-task-status, a SEPARATE axis from MemoryStatus, which stays active | archived for every type including task.
TaskStatus schema, type const TaskStatus = Schema.Literals(TASK_STATUSES) undocumented
isTaskStatus function const isTaskStatus = (value: string): value is TaskStatus => … True when a string is in the closed task-status vocabulary. Narrows an untrusted value.
Importance constant const Importance = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })) Importance, 1-10 inclusive, 1-based ordinal on a display scale, never an arithmetic input on its own. The retention scorer divides it by 10 to reach [0, 1] before it meets any other signal.
Confidence constant const Confidence = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 })) Confidence, unitless in [0, 1]. 1.0 is an unqualified assertion.
MemoryPath constant const MemoryPath = Schema.String.check(Schema.isMinLength(1)) A repo-root-relative path to a memory file, e.g. areas/oncall/rollback-order.html. No leading slash: this is the git-tree form, the files.path primary key, and the id of a memory. <link href> values carry the same path with a leading /. That is a document-reference form, converted at the HTML boundary, never stored here.
ENTITY_SEPARATOR constant const ENTITY_SEPARATOR = ":" A type:name entity reference, e.g. service:checkout-api, person:sasha. The prefix before the first colon is the entity type; everything after is the name, which may itself contain colons.
parseEntity function const parseEntity = ( … Split an entity reference into its type and name at the first separator. undefined when the reference has no separator, or when the type or the name on either side of it is empty.
normalizeEntityName function const normalizeEntityName = (name: string): string => … Lowercase, NFC-normalize, collapse internal whitespace, trim. What it means for two entity names to be the SAME name.
normalizeEntityRef function const normalizeEntityRef = (entity: string): string => … A whole reference in that form: both halves normalized, rejoined, padding around the separator gone.
isWellFormedEntity function const isWellFormedEntity = (entity: string): boolean => … True when an entity reference is well formed for a new label: it parses as type:name (parseEntity) and is already in the normalized spelling (normalizeEntityRef), so service:memhtml, project:agent-runtime, and person:laura pass while memhtml, Service:MemHTML, and person: laura do not.
PERSON_ENTITY_PREFIX constant const PERSON_ENTITY_PREFIX = 'person${ENTITY_SEPARATOR}' The person: entity prefix, which routes a semantic memory to resources/people/.
isPersonEntity function const isPersonEntity = (entity: string): boolean => … True when an entity reference names a person: the person: prefix plus a name that survives trim().

MEMORY_TYPES

The memory type vocabulary, closed. Ten values, restated by the files.memory_type CHECK constraint in SQL.

arc is in the vocabulary but absent from WRITABLE_MEMORY_TYPES: an arc is synthesized by curation from many memories, so an agent naming one directly would be asserting a conclusion the corpus has not yet earned.

task is ONE axis with the other nine rather than a parallel kind column, because three overlapping type vocabularies is what made the predecessor memory system’s classification unanswerable. A task is a memory type whose retrieval, dedup, and curation treatment a filter states, not a second axis. Tasks are default-excluded from search and shielded from curation. See @memhtml/index’s assembleScope and @memhtml/curator’s isShielded.

TASK_STATUSES

A task’s own status, carried in memhtml-task-status, a SEPARATE axis from MemoryStatus, which stays active | archived for every type including task.

Two axes rather than four memhtml-status values because active/archived is what every archive, correction, and publish path switches on, and a fifth value there would silently change the meaning of each of them. Finishing a task stamps done AND archives the file through the same archiveMemory machinery, so done is not a resting state on its own and “what did I finish” is answered by the archive tree plus git log.

normalizeEntityName

Lowercase, NFC-normalize, collapse internal whitespace, trim. What it means for two entity names to be the SAME name.

It lives in contracts rather than beside a caller because it is a vocabulary rule, and a second copy of a vocabulary rule fails silently: entity-resolution decides which memhtml-entity metas to rewrite by comparing a name against this form, so a divergent copy would have the phase canonicalize files toward a spelling nothing else recognizes, reporting merges no query can reach.

file_entities stores names AS AUTHORED, not in this form, and that is deliberate — the phase finds its work by reading those rows back, so a projection that pre-normalized would hide every unnormalized meta from the one pass whose job is to fix it. The two SQL doors fold with lower() on both sides instead: a narrower fold (SQLite’s lower() is ASCII-only) that cannot disagree with itself across the JS/SQL seam. Full canonicalization is durable in the TREE, applied by the phase.

normalizeEntityRef

A whole reference in that form: both halves normalized, rejoined, padding around the separator gone.

For callers comparing references in TypeScript — the write path deciding whether a candidate entity is one the corpus already names. The SQL doors do NOT use this; see the seam note above.

Total over unparseable input. A string with no separator normalizes as a whole and is returned without one, so the caller still decides what an untyped reference means rather than receiving a silently invented type.

isWellFormedEntity

True when an entity reference is well formed for a new label: it parses as type:name (parseEntity) and is already in the normalized spelling (normalizeEntityRef), so service:memhtml, project:agent-runtime, and person:laura pass while memhtml, Service:MemHTML, and person: laura do not.

The session’s label op holds its value to this, because a label writes a memhtml-entity meta that every entity index keys on as authored: a second spelling of one entity splits its records across two keys until the entity-resolution phase rewrites them, so the cheap place to refuse it is before the file is written.

isPersonEntity

True when an entity reference names a person: the person: prefix plus a name that survives trim().

The trim keeps a whitespace-only name from counting as a person anywhere the predicate is asked: slugify maps such a name to untitled, which names nobody. Placement does not ask it; a person entity no longer moves a record into resources/people/ (see placementFor).

3. Provenance

A loader generates this page from packages/contracts/src while the site builds, so no file in the repository holds it: the modules are the ones index.ts re-exports, each symbol is an exported declaration read with the TypeScript compiler, and every description is the doc comment above it. Change the registry and this page changes with it.