{
  "markdown": "# memdsl\n\n<!-- mcp-name: io.github.Liyuan1992/memdsl -->\n\n[English](#english) | [中文](#中文)\n\n## English\n\n**Agent memory as source code the agent reads itself.**\n\n### 0.9 release line with experimental Edges\n\nVersion 0.9.0 adds an opt-in `memdsl.workspace.v3` first-class explicit Edge\nexperiment. It does not rewrite the frozen 0.8 contract: legacy relations and\nauthority remain compatible, explicit Edge proposals always require a human,\nand explicit `supersedes` is graph-only. Source remains runtime authority;\nreview/audit is a workflow contract, not a non-bypassable grant ledger. See\n[the Phase 6 design and risk matrix](docs/DESIGN_explicit_edges_phase6.md) and\n[the release-scope evidence freeze](docs/RELEASE_SCOPE_PHASE6.md).\n\n### Stable 0.8 compatibility contract\n\nThe 0.8 contract combines the previously unpublished navigation and View work\nnow shipped by 0.9.0; neither 0.7.0 nor 0.8.0 was released separately. Stable\npublic contracts include the v1 compatibility/authority surfaces, Catalog v1,\nTrace v1, indexed\nquery/search trace, report diagnostics, public rebuildable `CompiledWorkspace`\n/ `compile_workspace`, `memdsl.workspace.v2`, exact `use`, the generic\n`dialect_mapping` capability, `ViewContext`/`ResolvedView`, and the explicit\nopt-in v2 read schemas. Map v1 remains supported throughout the 0.8 line and\nwill not be reconsidered for removal before 1.0.\n\nThe software release is `0.9.2`, anchored by tag `v0.9.2`. It adds official\nMCP Registry metadata and a UV-based MCPB installer for the default-read-only\n`memdsl-mcp` server. Parser, schema, review, query, authority, and MCP tool\ncontracts are unchanged from 0.9.1. Neither patch nor package-level release\npromotes the opt-in Edge surface to stable or makes automatic Edge generation\nauthoritative.\n\nThe real-world rollout quality of `quarantine`/`strict`, dialect-candidate\nlearning, and host-attested principal integration is still experimental and\nopt-in. Their safety invariants are not experimental: authorization happens\nbefore aggregation, incomplete hard-rule evaluation never becomes ALLOW,\nnon-authoritative edges never gain authority, and repair paths remain open.\n`CompiledWorkspace` is a public rebuildable handle; its cache/index layout,\ncompiler contract strings, and synthetic timing constants remain implementation\ndetails. Workspace-v3 first-class Edges are experimental. Automatic dialect\nlearning, automatic Edge candidates, inferred authority, and cold-history/\nincremental compilation are not shipped. Host extraction/sanitization and\nprivate schemas/policies/samples remain outside memdsl and are not release\ngates.\n\nmemdsl started with a retrieval failure. A memory system built on RAG failed\nto recall a memory it certainly had; a coding agent pointed at the same raw\nmemory files traced it down in a few steps. Same model — the difference was\nthe context contract. The agent knew the memory existed and could keep\nreading toward it; the retriever got exactly one similarity guess, and a\nmiss looked identical to absence.\n\nmemdsl turns that difference into the product. Long-term memory lives in\nreadable, lintable, reviewable `.mem` source files, and every runtime\nsurface is built for an agent that reads memory itself:\n\n- **A bounded memory Catalog** (`memdsl catalog`, MCP `memory_catalog` /\n  `memdsl://catalog`, Python `build_memory_catalog`): paged module/type/subject/\n  status navigation with item and byte budgets, revision-bound cursors, and no\n  duplicated structured/text representation. It is the recommended\n  session-start surface for large workspaces.\n- **A compatible memory map** (`memdsl map`, MCP `memory_map` /\n  `memdsl://map`): the existing v1 full index remains available for older\n  clients and is not silently changed into Catalog.\n- **Indexed queries that explain their misses** (`search_trace` in every\n  serialized pack): deterministic lexical postings preserve the v1\n  EvidencePack ordering and authority lanes while exposing View/source\n  identity, candidate-pool counts, filter-hidden matches, bounded vocabulary\n  suggestions, and safe retry queries. Suggestions never write aliases or let\n  candidate symbols redirect retrieval.\n- **A bounded relation Trace** (`memdsl trace`, MCP `memory_trace`, Python\n  `trace_memory`): deterministic incoming/outgoing/both BFS navigation with\n  relation filters, explicit cycle/back/cross edges, hard depth/node/edge/byte\n  budgets, and revision-bound cursors. Connectivity is navigation, not proof.\n- **Report-only link diagnostics** (`memdsl lint`, MCP `memory_lint` and\n  `memdsl://status`): duplicate ids, ambiguous/wrong-prefix/dangling targets,\n  unknown relations, revision cycles, and supersede forks are explicit. Cycle\n  edges cannot make every participant disappear, forks never select a winner,\n  and default Map/query authority remains v1-compatible.\n- **Raw source as the floor** (`memdsl://file/{file_id}`): the agent can\n  always drop down and read the actual declarations, the way a coding agent\n  reads code.\n\nThe failure mode that started the project now fails loud — the memory\nexists, a filter hid it, and the trace says exactly that:\n\n```console\n$ memdsl query examples/domains/coding -q \"force push main\" \\\n    --type coding.bug_pattern --json\n  \"missing\": [\n    \"no active declarations matched query terms: ['force', 'push', 'main']\",\n    \"1 active declaration(s) matched the query but were excluded by type/subject filters\"\n  ],\n  \"search_trace\": {\n    \"excluded_by_filters\": [\n      {\"id\": \"coding.project_rule:git.no_force_push\", ...}\n    ], ...\n  }\n\n$ memdsl query examples/domains/coding -q \"force push main\"\nMUST\n- [coding.project_rule:git.no_force_push] Never force-push the main branch. (exceptions: []) [status=active; runtime_role=constraint; lifecycle={\"status\":\"active\"}]\n```\n\n### Try it with Claude Code in two minutes\n\nThe core library and CLI support Python 3.9+. The MCP extra and\n`memdsl-mcp` server require Python 3.10+ because the upstream MCP SDK does.\n\n```console\n# Python 3.10+\npip install \"memdsl[mcp]\"\nclaude mcp add memdsl -- memdsl-mcp --workspace ~/memory   # or an examples/ dir\n```\n\nThe server instructs the agent to read `memory_catalog` first, continue only\nwith a cursor bound to the same Source/View and filters, treat `no_match` as a\nretry signal, use `memory_trace` only for bounded explicit-relation navigation,\nand preflight consequential drafts against MUST constraints with\n`memory_check`. Legacy `memory_map` remains registered for compatible clients.\n\n### DeepSeek Harness\n\nDeepSeek Harness can mount the same stdio MCP server through its official MCP\nclient. The recommended overlay grants only `read:summary,read:search`, so the\nmodel can catalog, query, trace, explain, and check approved source memory but\ncannot create proposals. See the tested overlay and verification steps in\n[the DeepSeek Harness integration guide](docs/DEEPSEEK_HARNESS.md).\n\n![memdsl DeepSeek Harness demo](docs/assets/deepseek-harness-demo.gif)\n\n### Governed, typed memory\n\nThe second pillar: memory you can review like code, **without forcing one\nauthor's ontology on every user**. Version 0.8 preserves the two-layer type\narchitecture introduced in 0.5 and the lifecycle-safe review contract from\n0.6, then adds bounded compiled navigation and explicit workspace-v2 Views:\n\n```text\ncore memory record     claim / evidence / scope / confidence / lifecycle /\n                       access policy / relations\n\ndomain type system     coding.project_rule / assistant.commitment /\n                       writing.voice_preference / your own memory types\n```\n\nThe core owns the stable behavioral contract. A workspace owns its vocabulary.\nA coding agent, personal assistant, and writing system should not have to call\nthe same thing a `preference`, `boundary`, or `fact` just because memdsl's\nauthor chose those words.\n\n### Two layers\n\nThe **core layer** provides universal fields and five stable runtime roles:\n\n| Runtime role | EvidencePack behavior |\n| --- | --- |\n| `symbol` | Defines a subject that other memories can reference |\n| `constraint` | Active declarations surface in MUST and participate in compliance |\n| `guidance` | Active declarations surface in SHOULD |\n| `assertion` | Active declarations surface in CONTEXT when relevant |\n| `question` | Active declarations surface in MISSING rather than as fact |\n\nEvery searchable non-active hit is isolated under PROVISIONAL, regardless of\nruntime role. Candidate symbols cannot redirect queries, and candidate\nconstraints cannot enter MUST or compliance.\n\nThe same authority boundary applies to relations. A `supersedes` relation can\nhide a target only when its source is active and its full-id or unique bare\ntarget resolves exactly. Candidate, retracted, archived, ambiguous, duplicate,\nor wrongly prefixed superseders cannot change query, MUST, or compliance. This\nis the v1 compatibility authority rule retained by 0.8. The opt-in\nResolvedView path uses the same fail-safe base and adds only explicit v2\nquarantine enforcement.\n\nThe core also understands capabilities such as `requires_evidence`,\n`searchable`, `temporal`, `enforceable`, `guardable`,\n`exceptions_recommended`, and the explicit review opt-in\n`auto_approvable`.\n\nThe **domain layer** defines meaningful memory types and compiles each one to\na runtime role. The shipped examples include:\n\n- coding: `coding.project_rule`, `coding.bug_pattern`, `coding.tool_preference`\n- personal assistant: `assistant.routine`, `assistant.commitment`,\n  `assistant.relationship_context`\n- writing: `writing.voice_preference`, `writing.taboo_topic`,\n  `writing.style_example`\n\nThe built-in `memdsl.standard@1` pack keeps existing `entity`, `fact`,\n`preference`, `boundary`, `principle`, `decision`, `state`, and `open_issue`\nworkspaces working. Those names are compatibility defaults, not the universal\nontology of human memory.\n\n### Define a domain vocabulary\n\nA workspace opts into schemas with `memdsl.json`:\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v1\",\n  \"schemas\": [\"coding.memschema.json\"]\n}\n```\n\nThe schema defines domain types, fields, roles, and capabilities:\n\n```json\n{\n  \"name\": \"coding\",\n  \"version\": \"1\",\n  \"types\": {\n    \"project_rule\": {\n      \"runtime_role\": \"constraint\",\n      \"required_fields\": [\"claim\", \"evidence\", \"scope\"],\n      \"optional_fields\": [\"rationale\", \"owner\"],\n      \"search_fields\": [\"rationale\", \"owner\"],\n      \"capabilities\": [\n        \"requires_evidence\",\n        \"searchable\",\n        \"enforceable\",\n        \"guardable\",\n        \"exceptions_recommended\"\n      ],\n      \"defaults\": {\"force\": \"hard\", \"status\": \"active\"},\n      \"allowed_forces\": [\"hard\"],\n      \"allow_extra_fields\": false\n    }\n  }\n}\n```\n\n`project_rule` becomes the namespaced type `coding.project_rule`:\n\n```mem\nmodule coding.memory\n\nentity Repository.Memdsl {\n  canonical_name: \"memdsl\"\n  status: active\n}\n\ncoding.project_rule git.no_force_push {\n  subject: Repository.Memdsl\n  claim: \"Never force-push the main branch.\"\n  scope: repository(\"memdsl\")\n  confidence: high\n  exceptions: []\n  rationale: \"Published history must remain auditable.\"\n  guard {\n    when_any: [\"push\", \"git\", \"main\"]\n    deny_any: [\"force-push\", \"--force\", \"--force-with-lease\"]\n  }\n  lifecycle { status: active }\n  access_policy {\n    readers: [developer, coding_agent]\n    writers: [maintainer]\n    reviewers: [maintainer]\n    export: internal\n  }\n  evidence {\n    source: AGENTS.md\n    quote: \"Do not force-push unless the user explicitly asks.\"\n  }\n}\n```\n\nStrict schemas reject undeclared fields. Unknown memory types fail lint with\n`unknown_memory_type`; they do not silently acquire ad-hoc behavior.\n\n### Exact imports and workspace-owned dialect\n\nExisting workspaces stay compatible: no manifest and\n`memdsl.workspace.v1` keep legacy global linking. A workspace can explicitly\naudit or enforce imports with v2:\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v2\",\n  \"schemas\": [\"workspace-dialect.memschema.json\"],\n  \"linking\": {\"visibility\": \"report\"}\n}\n```\n\n`use X` is resolved after the whole workspace is indexed, so declaration order\ndoes not matter. `X` is one exact module or one exact active symbol name. There\nis no wildcard, prefix, alias, or module-over-symbol precedence. Report mode\nkeeps legacy links and emits migration diagnostics; strict mode removes\nunimported relation, subject-routing, and dialect-routing effects. Strict is\nnever inferred for a v1 workspace.\n\nDialect remains Source owned by the workspace. A schema type opts in through\nthe generic `dialect_mapping` capability; the fictional runnable example is\n`examples/dialect/`. Only active, public, valid, unambiguous positive mappings\nroute. Candidate, pending, private, ambiguous, and negative mappings do not.\nA no-match may return a `search_trace.dialect_candidate` template, but it does\nnot write anything: evidence, proposal, review, approval, and recompilation are\nstill required.\n\n### Opt-in quarantine enforcement\n\nWorkspace v2 can independently enable the v2 read gate:\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v2\",\n  \"schemas\": [\"workspace-dialect.memschema.json\"],\n  \"linking\": {\"visibility\": \"report\"},\n  \"enforcement\": {\"mode\": \"quarantine\"}\n}\n```\n\nOmitting `enforcement`, or selecting `report`, preserves the v1 read behavior.\n`quarantine` and `strict` are explicit opt-ins; they classify Source as\nauthoritative, provisional, quarantined, or excluded and use new v2\nquery/list/explain/check/Catalog/Trace envelopes. Empty results distinguish\n`no_match`, `quarantined`, `unauthorized`, `compiler_error`, and budget limits.\nIdentity-critical errors fail closed, while relation/use/dialect/type errors\nare quarantined at the smallest safe declaration, file, or revision-family\nscope. Lint, source edits, proposals, review, and audit remain available for\nrepair.\n\nMap stays a v1 compatibility surface and returns `unsupported_view` under\nexplicit enforcement. Use Catalog, query, list, explain, or Trace instead.\nPending proposals still do not enter a durable View, and candidate/private/\nambiguous dialect mappings never gain routing authority through quarantine.\n\n### Install and inspect\n\nThe base package supports Python 3.9+:\n\n```console\npip install memdsl                 # or: pip install -e . from a checkout\nmemdsl --version\nmemdsl types examples/domains/coding\nmemdsl lint examples/domains/coding --json\nmemdsl catalog examples/domains/coding --json\nmemdsl map examples/domains/coding\nmemdsl query examples/domains/coding -q \"force push main\"\nmemdsl trace examples/alex decision:aurora.pricing_free_tier --both --depth 2 --json\nmemdsl check examples/domains/coding \\\n  -t \"push main\" \\\n  -c \"git push --force origin main\"\n```\n\n`memdsl types` shows every loaded standard and domain type together with its\nruntime role, required fields, capabilities, schema version, and source. Use\n`--json` when another tool needs to discover the type system.\n\n`memdsl lint --json` reports the same findings as the text output in a\n`memdsl.lint.v1` envelope: every diagnostic with its code, severity, file,\nline, and declaration id, plus counts and a `status` of `ok`, `errors`, or\n`strict_warnings` that matches the exit code.\n\nThe custom coding rule behaves exactly like a MUST constraint without any\nPython code knowing the name `coding.project_rule`:\n\n```text\nMUST\n- [coding.project_rule:git.no_force_push] Never force-push the main branch. [status=active; runtime_role=constraint; lifecycle={\"status\":\"active\"}]\n```\n\nThe compliance check returns `BLOCK` and cites the same domain declaration.\nAn unguarded or non-enforceable constraint fails safely to `NEEDS_REVIEW`\ninstead of being guessed at.\n\n### Layered query contract\n\nQueries return an **EvidencePack**, not a flat hit list:\n\n- `MUST`: applicable `constraint` declarations\n- `SHOULD`: relevant `guidance` declarations\n- `CONTEXT`: relevant `assertion` declarations\n- `PROVISIONAL`: scored non-active searchable declarations\n- `CONFLICT`: declared conflicts among selected memories\n- `MISSING`: relevant `question` declarations and known gaps\n\nEvery item carries a stable declaration id, type, runtime role, capabilities,\nclaim, subject, scope, confidence, lifecycle, access policy, evidence, and\nsource location. Domain semantics stay expressive while runtime behavior stays\npredictable.\n\nJSON output remains `memdsl.evidence_pack.v1`; the `provisional` field added in\n0.6 remains additive in 0.8. Scored CONTEXT and PROVISIONAL entries include `score` and\n`matched_terms`, and every declaration item carries explicit lifecycle\nstatus and runtime role.\n\nThe reference retriever is deliberately lexical and uses a rebuildable\ninverted term index. Production systems can put BM25, embeddings, graphs, or\ndatabase indexes behind the same EvidencePack contract.\n\n### Navigation: bounded Catalog first, then query and drill down\n\nmemdsl exists because agent-driven reading beats blind similarity matching:\nan agent that knows a memory exists can drill down to it, while a retriever\nthat misses just returns nothing. Four surfaces support that loop:\n\n- **Bounded Catalog** (`memdsl catalog`, MCP `memory_catalog` /\n  `memdsl://catalog`, Python `build_memory_catalog`): module summaries filtered\n  by module/type/subject/status. The default page is 20 items / 8192 canonical\n  compact UTF-8 JSON bytes. `truncated`, `next_cursor`, `returned_items`, exact\n  totals, and vocabulary total/truncated metadata are explicit. Cursors bind\n  Source fingerprint, report-only View, filters, order, and representation;\n  changed Source returns `cursor_stale`.\n- **Map v1 compatibility** (`memdsl map`, MCP `memory_map` / `memdsl://map`,\n  Python `build_memory_map`): still returns the full serviceable declaration\n  index for existing clients. It is not the recommended large-workspace\n  session-start surface. Under explicit workspace-v2 enforcement it returns\n  `unsupported_view`; Map and Catalog are navigation, not citation.\n- **Search trace** (`search_trace` in serialized packs): how the query was\n  interpreted, which indexes ran, the candidate pool before/after filters, and\n  which matching declarations a type/subject filter excluded. A no-match may\n  add bounded lexical `vocabulary_suggestions` and `retry_queries`; candidate,\n  ambiguous, or access-restricted vocabulary never becomes an automatic route.\n- **Bounded Trace** (`memdsl trace`, MCP `memory_trace`, Python\n  `trace_memory`): follows explicit resolved relations with deterministic BFS.\n  Defaults are depth 3, 20 nodes, 40 edges, and 8192 bytes. Stateless cursors\n  bind Source/View, anchors, direction, relation filters, depth, and\n  provisional visibility. Back/cycle/cross edges are explicit; graph\n  connectivity is not evidence or proof.\n\n### Preflight constraints\n\nAny schema-defined `constraint` can participate in `memdsl check`. To run a\ndeterministic guard, its type must declare both `enforceable` and `guardable`.\nPhrase and regex guards produce `ALLOW` or `BLOCK`; natural-language-only\nconstraints produce `NEEDS_REVIEW`. Declared exceptions must be asserted\nexplicitly with `--exception`.\n\nThe standard v0.4 `boundary` type follows this same generic path. Its old JSON\naliases such as `boundary_id` and `applicable_must` remain available for\nclient compatibility.\n\nRun the reproducible standard or custom-domain suites:\n\n```console\nmemdsl eval compliance examples/compliance \\\n  --cases examples/compliance/cases.jsonl --json\n\nmemdsl eval compliance examples/domains/coding \\\n  --cases examples/domains/coding/cases.jsonl --json\n```\n\n### Use as an MCP server\n\nThe MCP server requires Python 3.10+:\n\n```console\n# Python 3.10+\npip install \"memdsl[mcp]\"\nmemdsl-mcp --workspace examples/domains/coding --inspect\nmemdsl-mcp --workspace ~/memory\n```\n\nThe MCP server exposes:\n\n- tools: `memory_catalog`, `memory_map`, `memory_types`, `memory_query`, `memory_trace`, `memory_check`,\n  `memory_explain`, `memory_list`, `memory_lint`, `memory_propose`,\n  `memory_review_list`\n- resources: `memdsl://status`, `memdsl://catalog`, `memdsl://map`, `memdsl://types`,\n  `memdsl://files`, `memdsl://file/{file_id}`\n\nAgents should read `memory_catalog` at session start so navigation remains\nbounded as the workspace grows, then use `memory_query` and bounded\n`memory_trace` for local drill-down. `memory_map` remains for v1 clients. Before\nproposing a declaration, call `memory_types` or read `memdsl://types`. This\ndiscovers the workspace's vocabulary instead of inventing a type or assuming\nthe standard pack is the only valid worldview.\n\nAccess can be narrowed with `--scopes` or `MEMDSL_MCP_SCOPES` (default:\n`read:summary,read:search,write:candidate`). The core represents and transports\ndeclaration-level `access_policy`. For an enforced View, an embedding host may\ninject a trusted principal and roles only when constructing\n`MemdslMCPService`; MCP tool arguments cannot self-assert identity. Filtering\nhappens before counts, vocabulary, diagnostics, graph traversal, and raw-file\nresources. memdsl does not provide an identity provider, so the host must\nauthenticate the principal and map roles.\n\n### Gated writes\n\nEvery MCP write is still a proposal. It must use a loaded type, parse, and\npass lint against the live workspace. Invalid proposals are rejected; exact\npending/approved duplicates return `no_op`; everything else is either queued\nor narrowly auto-approved by host-attested policy.\n\nThe default remains all-human. Initialize a valid but disabled policy:\n\n```console\nmemdsl review policy init memory\nmemdsl review policy show memory\nmemdsl review policy validate memory\n```\n\nThe generated JSON has empty clients/rules and a zero daily limit. To enable\nautomation, a workspace owner must explicitly add `auto_approvable` to one\ncandidate assertion type, configure an exact-kind rule and trusted host\nclient, set a positive daily limit, and grant the non-default `write:auto`\nscope:\n\n```console\nmemdsl-mcp --workspace memory \\\n  --scopes read:summary,read:search,write:candidate,write:auto\n```\n\nThe built-in `workspace_file_quote` verifier requires\n`evidence.source` to resolve inside a loaded workspace root and\n`evidence.quote` to occur exactly in that UTF-8 file. Question, guidance,\nconstraint, symbol, active, global, warned, destructive, or unverified\nproposals always stay queued. Without `write:auto`, a valid policy runs in\nshadow posture: the write remains pending while `eligible_route` records\nwhat policy would have done.\n\nHuman operations and quality feedback remain explicit:\n\n```console\nmemdsl review list memory\nmemdsl review approve memory PROPOSAL_ID --into memory/approved.mem\nmemdsl review reject memory PROPOSAL_ID --reason \"not durable\"\nmemdsl review digest memory\nmemdsl review stats memory\nmemdsl review audit memory PROPOSAL_ID --verdict confirm\n```\n\n`review list`, `review show`, and `review audit` accept `--json` alongside the\nexisting `policy show`, `digest`, and `stats` JSON output, so a queue dashboard\nor CI job can read the queue without parsing human text. Approve and reject\nstay text-only decisions.\n\nIn-process hosts use authoritative paths:\n\n```python\nfrom memdsl import (\n    ProposalContext,\n    ReviewStore,\n    Workspace,\n    load_policy,\n    staging_dir_for,\n)\n\nworkspace = Workspace.load([\"memory\"])\nstore = ReviewStore(staging_dir_for([\"memory\"]))\npolicy = load_policy(store.staging_dir, registry=workspace.registry)\nassert policy is not None\ncontext = ProposalContext(client_id=\"mcp-client\")\n\nresult = store.submit(\n    [\"memory\"],\n    proposal_source,\n    policy=policy,\n    context=context,\n    write_auto_granted=True,\n)\n```\n\nAutomatic approval reloads and fingerprints memory, manifest, and schema\ninputs, re-verifies evidence, enforces a finite UTC daily limit, writes only\nto a non-symlink `.mem` target inside the primary workspace root, and never\nuses `force`. Route assessments, decisions, post-review results, digest\ncursors, and no-op events remain append-only.\n\nA post-review `flag` does not silently delete memory. Promotion, revision,\nand retraction require a new human-reviewed declaration with a new id and\n`supersedes` (optionally `revision_of`) pointing to the old declaration. The\nsuccessor must be lifecycle `active` before the relation has authority; the old\ndeclaration does not need an in-place `status: superseded` rewrite.\nReviewStore does not create Git commits; hosts may add Git integration without\nmaking core correctness depend on it.\n\n### What's in the box\n\n- A domain-neutral `.mem` record with provenance, scope, confidence,\n  lifecycle, access policy, relations, and stable ids.\n- An extensible, namespaced `.memschema.json` type system and workspace\n  manifest.\n- A backward-compatible standard type pack for pre-v0.5 workspaces.\n- A schema-driven linter, layered query executor, explainer, and deterministic\n  Compliance Gate.\n- Type discovery through CLI and MCP.\n- A default-safe, host-attested review pipeline with human queueing,\n  deterministic narrow auto-approval, no-op detection, digest/stats, and\n  append-only audit.\n- Reproducible compliance benchmarks and coding/assistant/writing domain packs.\n- Fictional standard examples for Alex and Mira plus a deliberately broken\n  linter workspace.\n\nFull grammar and semantics are in [docs/SPEC.md](docs/SPEC.md). In-process hosts\nshould also read [docs/PUBLIC_API.md](docs/PUBLIC_API.md) and\n[docs/UPGRADING.md](docs/UPGRADING.md). The review-policy security contract is\nin [docs/DESIGN_review_policy.md](docs/DESIGN_review_policy.md). The\n[documentation index](docs/DOCUMENTATION_INDEX.md) keeps the software\ncontracts, implementation designs, release boundaries, and reproducibility\nmaterial together.\n\n### What memdsl is not\n\n- It is not a replacement for retrieval/extraction systems such as Mem0, Zep,\n  Graphiti, or LangMem. It is the governed source format and behavioral\n  contract above those systems.\n- It is not a universal taxonomy of people or memory. Domain owners define\n  their own types.\n- It is not a semantic policy oracle. Constraints that cannot be evaluated\n  deterministically remain `NEEDS_REVIEW`.\n- It is not an unrestricted automatic memory writer. Only explicitly\n  opted-in candidate assertions with trusted identity and verified evidence\n  can be auto-approved; every higher-risk or uncertain proposal remains human\n  reviewed.\n\n### Current evidence and limits\n\nEarly evidence from the private single-user system this project was extracted\nfrom showed higher retrieval precision than that system's tuned RAG baseline\non its internal evaluation. That result is encouraging, but it is not evidence\nthat one ontology generalizes to everyone. The v0.8 architecture makes that\nlimitation explicit: memdsl standardizes the record and runtime contract while\nletting each domain own its vocabulary.\n\nThe bundled suites are contract-level, deterministic tests. Cross-model\nbehavioral claims still require separately recorded model runs.\n\n### Roadmap\n\n- ~~Two-layer core + extensible domain type system~~ — shipped in v0.5\n- ~~Lifecycle-safe provisional serving + tiered review policy~~ — shipped in v0.6\n- ~~Public rebuildable CompiledWorkspace + bounded Catalog pagination/budgets~~\n  — stable/public 0.8 contract shipped by 0.9.0\n- ~~Indexed query + bounded Trace + exact use/report/strict + reviewed Dialect~~\n  — stable/public 0.8 contract shipped by 0.9.0\n- ~~Opt-in quarantine enforcement with explicit v2 envelopes~~ — stable/public schema/safety contract; real rollout quality remains experimental\n- ~~Opt-in first-class reviewed Edge experiment~~ — shipped as experimental in `0.9.0`\n  after an anonymous exploratory Pilot; relation/evidence narrowing remains\n  **ADJUST**, not a formal empirical validation\n- Cold history/incremental compilation — deferred until representative scale, SLO, and production bottleneck evidence exists\n- Schema package distribution, dependency/version constraints, and migrations\n- Richer field validators and domain-defined diagnostic rules\n- Pluggable retrieval backends behind the EvidencePack contract\n- Identity-provider adapters for enforcing represented access policies\n- Semantic conflict reviewers and per-client/per-rule quotas, gated by\n  measured shadow/sample/post-review evidence\n\n### License\n\nCode: [MIT](LICENSE). Specification ([docs/SPEC.md](docs/SPEC.md)): CC-BY-4.0.\n\n---\n\n## 中文\n\n### 0.9 正式软件版本中的实验 Edge\n\n0.9.0 新增显式 opt-in 的 `memdsl.workspace.v3` 一等 Edge 实验，不改写已经冻结的\n0.8 合同：legacy relation 与 authority 保持兼容，Edge proposal 永远进入人工\n审核，显式 `supersedes` 在本阶段仅进入 graph。当前 runtime authority 仍来自\nSource；review/audit 只是 workflow contract，不是不可绕过的授权账本。详见\n[Phase 6 设计与风险矩阵](docs/DESIGN_explicit_edges_phase6.md) 与\n[发布范围证据冻结](docs/RELEASE_SCOPE_PHASE6.md)。\n\n**把 Agent 记忆写成 agent 自己会去读的源代码。**\n\n### Stable 0.8 兼容合同\n\n0.8 合同把此前未单独发布的导航能力与 View 能力统一后由 0.9.0 承载；0.7.0 与\n0.8.0 均未单独发布。正式公共合同包括 Source/review authority、公共且可重建的\n`CompiledWorkspace` / `compile_workspace`、v1 兼容 surface、Catalog v1、Trace\nv1、indexed query/search trace、report diagnostics、`memdsl.workspace.v2`、\nexact `use`、通用 `dialect_mapping` capability、`ViewContext`/`ResolvedView` 与\n显式 opt-in 的 v2 read schemas。Map v1 在整个 0.8 line 继续保留，不早于 1.0\n才重新评估删除。\n\n正式软件版本为 `0.9.2`，由 tag `v0.9.2` 锚定。它增加官方 MCP Registry 元数据\n和用于安装默认只读 `memdsl-mcp` 服务的 UV MCPB 包；parser、schema、review、\nquery、authority 与 MCP tool 合同均与 0.9.1 相同。无论 patch 还是软件版本发布，\n都不会把 opt-in Edge 提升为 stable，也不会让自动 Edge 生成获得 authority。\n\n`quarantine`/`strict` 的真实 rollout 质量、dialect candidate 学习闭环和宿主证明\nprincipal 的集成仍是 experimental/opt-in；但 authorization-before-aggregation、\nhard rule 不完整时不得 ALLOW、非权威 edge 不得获得 authority、repair lane 必须\n可用等安全不变量不是实验性的。`CompiledWorkspace` 是公共、可重建 handle；其\ncache/index 布局、compiler contract 字符串和 synthetic timing 仍是内部事实。\nworkspace-v3 一等 Edge 保持 experimental；自动方言学习、自动 Edge 候选、inferred\nauthority 与冷历史/增量编译尚未发布。宿主 extractor/sanitizer、私人 schema/policy/\n样本不属于 memdsl，也不构成 release gate。\n\nmemdsl 起源于一次召回失败。一个基于 RAG 的记忆系统没能召回一条确实存在的\n记忆；而一个 coding agent 拿到同样的原始记忆文件，几步就把它找了出来。\n同一个模型——差别在上下文契约：agent 知道那条记忆存在，可以一层层读过去；\n检索器只有一次相似度猜测，而且\"没命中\"和\"不存在\"看起来一模一样。\n\nmemdsl 把这个差别做成了产品。长期记忆保存在可读、可 lint、可审查的 `.mem`\n源文件里，每个运行时 surface 都为\"agent 自己读记忆\"而设计：\n\n- **有界记忆目录 Catalog**（`memdsl catalog`、MCP `memory_catalog` /\n  `memdsl://catalog`、Python `build_memory_catalog`）：按 module/type/subject/\n  status 分页导航，具备 item/byte 硬预算、绑定 revision 的稳定 cursor，并避免\n  structured/text 双份返回；这是大型 workspace 推荐的会话起始 surface。\n- **兼容记忆地图**（`memdsl map`、MCP `memory_map` / `memdsl://map`）：旧的\n  v1 全量索引继续保留，不会被原地改成 Catalog。\n- **带倒排索引、会解释 miss 的查询**（序列化 pack 中的 `search_trace`）：\n  确定性的词法 postings 保持 v1 EvidencePack 排序与 authority lane，同时返回\n  View/source、候选池、filter-hidden match、受限词汇建议和安全 retry query；建议\n  不会写 alias，也不会让 candidate symbol 改写路由。\n- **有界关系 Trace**（`memdsl trace`、MCP `memory_trace`、Python\n  `trace_memory`）：确定性的 incoming/outgoing/both BFS、relation filter、显式\n  cycle/back/cross edge、depth/node/edge/byte 硬预算与 revision-bound cursor。\n  连通性只是导航，不是证明。\n- **原始源码兜底**（`memdsl://file/{file_id}`）：agent 随时可以下钻去读\n  真正的声明，就像 coding agent 读代码一样。\n\n当年启动这个项目的那种失败，现在会大声报错——记忆存在，是过滤器藏了它，\ntrace 会把话说明白：\n\n```console\n$ memdsl query examples/domains/coding -q \"force push main\" \\\n    --type coding.bug_pattern --json\n  \"missing\": [\n    \"no active declarations matched query terms: ['force', 'push', 'main']\",\n    \"1 active declaration(s) matched the query but were excluded by type/subject filters\"\n  ],\n  \"search_trace\": {\n    \"excluded_by_filters\": [\n      {\"id\": \"coding.project_rule:git.no_force_push\", ...}\n    ], ...\n  }\n\n$ memdsl query examples/domains/coding -q \"force push main\"\nMUST\n- [coding.project_rule:git.no_force_push] Never force-push the main branch. (exceptions: []) [status=active; runtime_role=constraint; lifecycle={\"status\":\"active\"}]\n```\n\n### 两分钟在 Claude Code 里跑起来\n\n底层库和 CLI 支持 Python 3.9+。由于上游 MCP SDK 的要求，MCP extra 和\n`memdsl-mcp` server 需要 Python 3.10+。\n\n```console\n# Python 3.10+\npip install \"memdsl[mcp]\"\nclaude mcp add memdsl -- memdsl-mcp --workspace ~/memory   # 或任意 examples/ 目录\n```\n\nserver 会指示 agent 先读 `memory_catalog`，只在 Source/View 和过滤条件不变时\n继续 cursor，把 `no_match` 当作重试信号，只用 `memory_trace` 做有界的显式关系\n导航，并在产出重要草稿前用\n`memory_check` 对照 MUST 约束做预检。旧客户端仍可调用 `memory_map`。\n\n### 受治理的类型化记忆\n\n第二根支柱：像审代码一样审记忆，**但不要求所有用户接受作者的一套世界观**。\nv0.8 保留 v0.5 引入的两层类型架构与 v0.6 的 lifecycle 安全审核合同，并加入\n有界编译导航与显式 workspace-v2 View：\n\n```text\n底层通用记录        claim / evidence / scope / confidence / lifecycle /\n                    access policy / relations\n\n上层领域类型系统    coding.project_rule / assistant.commitment /\n                    writing.voice_preference / 用户自定义类型\n```\n\n底层负责稳定的行为契约，workspace 负责自己的词汇。编程 Agent、个人助理和\n写作系统不应该仅仅因为 memdsl 作者选择了 `preference`、`boundary`、`fact`\n这些词，就被迫用同一套分类描述自己的记忆。\n\n### 两层架构\n\n**底层**提供通用字段和五种稳定的 runtime role：\n\n| Runtime role | 在 EvidencePack 中的行为 |\n| --- | --- |\n| `symbol` | 定义其他记忆可以引用的主体 |\n| `constraint` | 只有 active 声明进入 MUST 并参与合规检查 |\n| `guidance` | 只有 active 声明进入 SHOULD |\n| `assertion` | 只有 active 声明相关时进入 CONTEXT |\n| `question` | 只有 active 声明进入 MISSING，而不是伪装成事实 |\n\n任何 searchable 的非 active 命中都只进入 PROVISIONAL，不论 runtime role。\ncandidate symbol 不能重定向查询，candidate constraint 不能进入 MUST 或\ncompliance。\n\n同一 authority 边界也适用于关系。只有 source 为 active，且 full id 精确匹配或\nbare ref 唯一解析时，`supersedes` 才能隐藏 target。candidate、retracted、\narchived、歧义、重复或错误 kind 前缀的 superseder 都不能改变 query、MUST 或\ncompliance。这是 0.8 继续保留的 v1 correctness/security authority 规则。\nResolvedView 复用这个安全基础，只在显式 v2 opt-in 时增加 quarantine enforcement。\n\n底层还识别 `requires_evidence`、`searchable`、`temporal`、\n`enforceable`、`guardable`、`exceptions_recommended`，以及显式审核\nopt-in 的 `auto_approvable` 等 capability。\n\n**上层**定义领域真正关心的 memory type，并把每种类型编译到一个稳定 role。\n仓库自带三个示例领域：\n\n- 编程：`coding.project_rule`、`coding.bug_pattern`、\n  `coding.tool_preference`\n- 个人助理：`assistant.routine`、`assistant.commitment`、\n  `assistant.relationship_context`\n- 写作：`writing.voice_preference`、`writing.taboo_topic`、\n  `writing.style_example`\n\n内置的 `memdsl.standard@1` 兼容包会继续加载 `entity`、`fact`、\n`preference`、`boundary`、`principle`、`decision`、`state`、\n`open_issue` 等旧类型。它们是向后兼容的默认词汇，不是人类记忆的唯一分类法。\n\n### 定义自己的领域词汇\n\nworkspace 通过 `memdsl.json` 引入 schema：\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v1\",\n  \"schemas\": [\"coding.memschema.json\"]\n}\n```\n\n`.memschema.json` 定义类型的字段、role 和 capability：\n\n```json\n{\n  \"name\": \"coding\",\n  \"version\": \"1\",\n  \"types\": {\n    \"project_rule\": {\n      \"runtime_role\": \"constraint\",\n      \"required_fields\": [\"claim\", \"evidence\", \"scope\"],\n      \"optional_fields\": [\"rationale\", \"owner\"],\n      \"search_fields\": [\"rationale\", \"owner\"],\n      \"capabilities\": [\n        \"requires_evidence\",\n        \"searchable\",\n        \"enforceable\",\n        \"guardable\",\n        \"exceptions_recommended\"\n      ],\n      \"defaults\": {\"force\": \"hard\", \"status\": \"active\"},\n      \"allowed_forces\": [\"hard\"],\n      \"allow_extra_fields\": false\n    }\n  }\n}\n```\n\n加载后，`project_rule` 的完整名字是 `coding.project_rule`：\n\n```mem\ncoding.project_rule git.no_force_push {\n  subject: Repository.Memdsl\n  claim: \"绝不对 main 分支执行 force-push。\"\n  scope: repository(\"memdsl\")\n  confidence: high\n  exceptions: []\n  rationale: \"已发布的历史必须保持可审计。\"\n  guard {\n    when_any: [\"push\", \"git\", \"main\"]\n    deny_any: [\"force-push\", \"--force\", \"--force-with-lease\"]\n  }\n  lifecycle { status: active }\n  access_policy {\n    readers: [developer, coding_agent]\n    writers: [maintainer]\n    reviewers: [maintainer]\n    export: internal\n  }\n  evidence {\n    source: AGENTS.md\n    quote: \"除非用户明确要求，否则不要 force-push。\"\n  }\n}\n```\n\n严格 schema 会拒绝未声明字段。未知类型会产生 `unknown_memory_type` lint\n错误，不会悄悄获得一套临时行为。\n\n### 精确 use 与 workspace 自有方言\n\n旧 workspace 保持兼容：没有 manifest 或使用 `memdsl.workspace.v1` 时仍是\nlegacy 全局链接。只有显式使用 v2，才会进入 report 或 strict：\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v2\",\n  \"schemas\": [\"workspace-dialect.memschema.json\"],\n  \"linking\": {\"visibility\": \"report\"}\n}\n```\n\ncompiler 会先建立整库 module/symbol 表，再解析 `use X`，所以声明顺序不影响结果。\n`X` 只能精确命中一个 module 或一个 active symbol name；不支持通配符、前缀、\nalias，也不设置 module 优先或 symbol 优先。report 保留 legacy 链接并给迁移诊断；\nstrict 会去掉未导入 relation、subject 路由和 dialect 路由的效果。v1 绝不会因为\n出现了 `use` 就被暗中切成 strict。\n\n方言仍是 workspace 自己拥有、可版本化、可审核的 Source。schema type 通过通用\n`dialect_mapping` capability opt in，仓库提供了完全虚构、可运行的\n`examples/dialect/`。只有 active、公开、结构有效、无歧义的 positive mapping\n才会路由；candidate、pending、private、ambiguous 和 negative mapping 都不会。\nno-match 可以返回 `search_trace.dialect_candidate` 模板，但不会自动写 Source；\n仍需 evidence、proposal、人工审核、批准和重新编译。\n\n### 显式 opt-in 的 quarantine enforcement\n\nworkspace v2 可以独立开启 v2 读取 gate：\n\n```json\n{\n  \"schema_version\": \"memdsl.workspace.v2\",\n  \"schemas\": [\"workspace-dialect.memschema.json\"],\n  \"linking\": {\"visibility\": \"report\"},\n  \"enforcement\": {\"mode\": \"quarantine\"}\n}\n```\n\n省略 `enforcement` 或选择 `report`，仍保持 v1 读取行为。`quarantine` 与\n`strict` 必须显式 opt in；它们把 Source 分成 authoritative、provisional、\nquarantined、excluded，并使用新的 query/list/explain/check/Catalog/Trace v2\nenvelope。空结果会明确区分 `no_match`、`quarantined`、`unauthorized`、\n`compiler_error` 与预算不足。identity-critical 错误 fail closed，relation/use/\ndialect/type 错误则尽量只隔离最小安全的 declaration、文件或 revision family。\nlint、直接编辑 Source、proposal、review 和 audit 修复通道仍然开放。\n\nMap 保持 v1 兼容面，在显式 enforcement 下返回 `unsupported_view`；应改用\nCatalog、query、list、explain 或 Trace。pending proposal 仍不会进入 durable\nView，candidate/private/ambiguous dialect 也不会借 quarantine 获得路由权。\n\n### 安装与类型发现\n\n基础包支持 Python 3.9+：\n\n```console\npip install memdsl                 # 或在 checkout 中运行 pip install -e .\nmemdsl --version\nmemdsl types examples/domains/coding\nmemdsl lint examples/domains/coding --json\nmemdsl catalog examples/domains/coding --json\nmemdsl map examples/domains/coding\nmemdsl query examples/domains/coding -q \"force push main\"\nmemdsl trace examples/alex decision:aurora.pricing_free_tier --both --depth 2 --json\nmemdsl check examples/domains/coding \\\n  -t \"push main\" \\\n  -c \"git push --force origin main\"\n```\n\n`memdsl types` 会列出已加载的标准类型和领域类型，以及各自的 runtime role、\n必填字段、capability、schema 版本和来源。需要给其他工具消费时可加 `--json`。\n\n`memdsl lint --json` 输出与文本模式完全相同的诊断，包在 `memdsl.lint.v1`\n信封里：每条诊断的 code、severity、文件、行号、声明 id，加上计数和与退出码\n一致的 `status`（`ok`、`errors` 或 `strict_warnings`）。\n\n上面的自定义类型不需要在 Python 代码里写死 `coding.project_rule`，依然会作为\nMUST 约束出现：\n\n```text\nMUST\n- [coding.project_rule:git.no_force_push] Never force-push the main branch. [status=active; runtime_role=constraint; lifecycle={\"status\":\"active\"}]\n```\n\n合规检查会返回 `BLOCK` 并引用同一个领域声明。没有 guard 或不具备执行能力的\n约束会安全返回 `NEEDS_REVIEW`，不会假装已经理解。\n\n### 分层查询契约\n\n查询返回的是 **EvidencePack**，而不是扁平命中列表：\n\n- `MUST`：适用的 `constraint`\n- `SHOULD`：相关的 `guidance`\n- `CONTEXT`：相关的 `assertion`\n- `PROVISIONAL`：带分数的非 active searchable 声明\n- `CONFLICT`：已声明的冲突\n- `MISSING`：相关的 `question` 和已知信息缺口\n\n每一项都携带稳定 id、类型、runtime role、capability、claim、subject、scope、\nconfidence、lifecycle、access policy、evidence 和源码位置。这样领域语义可以扩展，\n运行时行为仍然稳定。\n\nJSON 输出仍为 `memdsl.evidence_pack.v1`；v0.6 加入的 `provisional` 在 v0.8\n继续保持 additive。带分数的 CONTEXT 和 PROVISIONAL 条目都包含 `score`、\n`matched_terms`，每个 declaration item 还明确携带 lifecycle status 和\nruntime role。\n\n参考实现使用可重建的词法倒排索引。生产系统可以在同一个 EvidencePack 契约\n后面替换成 BM25、embedding、图或数据库索引。\n\n### 导航：先读有界 Catalog，再查询和下钻\n\nmemdsl 的出发点是\"让 agent 自己读记忆\"胜过\"让相似度匹配替 agent 决定\"：\n知道某条记忆存在的 agent 可以一层层钻下去，而检索器一旦没命中就什么都没有。\n四个 surface 支撑这个闭环：\n\n- **有界 Catalog**（`memdsl catalog`、MCP `memory_catalog` /\n  `memdsl://catalog`、Python `build_memory_catalog`）：按 module 汇总，并可按\n  module/type/subject/status 过滤。默认 20 items / 8192 canonical compact UTF-8\n  JSON bytes；`truncated`、`next_cursor`、`returned_items`、精确 total 和词表\n  total/truncated metadata 都显式返回。cursor 绑定 Source fingerprint、\n  report-only View、过滤条件、顺序和 representation；Source 改变会返回\n  `cursor_stale`。\n- **Map v1 兼容面**（`memdsl map`、MCP `memory_map` / `memdsl://map`、Python\n  `build_memory_map`）：继续为旧客户端返回全量可服务声明索引，但不再推荐作为\n  大型 workspace 的会话起始 surface。显式 workspace-v2 enforcement 下会返回\n  `unsupported_view`。Map 与 Catalog 都只是导航，不是引用来源。\n- **检索痕迹**（序列化 pack 中的 `search_trace`）：记录查询被如何解释，以及\n  使用了哪些 index、过滤前后候选池，以及 type/subject filter 排除了哪些本来\n  匹配的声明。no-match 可返回有界 `vocabulary_suggestions` 与\n  `retry_queries`；candidate、歧义或 access-restricted 词汇不会成为自动路由。\n- **有界 Trace**（`memdsl trace`、MCP `memory_trace`、Python\n  `trace_memory`）：沿已解析的显式关系做确定性 BFS。默认 depth 3、20 nodes、\n  40 edges、8192 bytes；cursor 绑定 Source/View、anchor、direction、relation、\n  depth 与 provisional visibility。back/cycle/cross edge 显式返回，但连通性不是\n  evidence 或 proof。\n- **只报告、不隔离的链接诊断**（`memdsl lint`、MCP `memory_lint` 与\n  `memdsl://status`）：duplicate id、歧义/错误前缀/dangling target、未知 relation、\n  revision cycle 和 supersede fork 都会显式出现。cycle edge 不会让参与节点全部\n  消失，fork 不会暗选 winner，而默认 Map/query authority 仍保持 v1 兼容。\n\n### 执行前约束检查\n\n任何被 schema 编译为 `constraint` 的类型都可以参与 `memdsl check`。要执行\n确定性的 guard，该类型必须同时声明 `enforceable` 和 `guardable`。短语与正则\nguard 返回 `ALLOW` 或 `BLOCK`；只有自然语言的约束返回 `NEEDS_REVIEW`。\n例外必须由调用方通过 `--exception` 显式声明。\n\nv0.4 的标准 `boundary` 也走同一条通用链路。`boundary_id`、\n`applicable_must` 等旧 JSON 字段仍作为兼容别名保留。\n\n```console\nmemdsl eval compliance examples/compliance \\\n  --cases examples/compliance/cases.jsonl --json\n\nmemdsl eval compliance examples/domains/coding \\\n  --cases examples/domains/coding/cases.jsonl --json\n```\n\n### 作为 MCP server 使用\n\nMCP server 需要 Python 3.10+：\n\n```console\n# Python 3.10+\npip install \"memdsl[mcp]\"\nmemdsl-mcp --workspace examples/domains/coding --inspect\nmemdsl-mcp --workspace ~/memory\n```\n\nMCP server 提供：\n\n- tools：`memory_catalog`、`memory_map`、`memory_types`、`memory_query`、`memory_trace`、`memory_check`、\n  `memory_explain`、`memory_list`、`memory_lint`、`memory_propose`、\n  `memory_review_list`\n- resources：`memdsl://status`、`memdsl://catalog`、`memdsl://map`、`memdsl://types`、\n  `memdsl://files`、`memdsl://file/{file_id}`\n\nAgent 应该在会话开始时读取 `memory_catalog`，让导航成本不随 workspace 总量\n线性膨胀，再用 `memory_query` 与有界 `memory_trace` 局部下钻；`memory_map`\n继续服务 v1 客户端。在提出新声明前，应该先调用\n`memory_types` 或读取 `memdsl://types`，发现当前 workspace 的词汇，而不是自己\n发明类型，也不是默认标准兼容包就是唯一世界观。\n\n可通过 `--scopes` 或 `MEMDSL_MCP_SCOPES` 缩小 MCP 权限范围，默认值为\n`read:summary,read:search,write:candidate`。底层会表示、验证并传输声明级\n`access_policy`。在 enforced View 中，嵌入式宿主只能在构造\n`MemdslMCPService` 时注入可信 principal 与 roles；MCP tool 参数不能自报身份。\n过滤发生在 count、vocabulary、diagnostics、graph traversal 和 raw-file resource\n之前。memdsl 不提供身份提供商；宿主仍需认证 principal 并映射 roles。\n\n### 受审查的写入\n\n每次 MCP 写入仍然先成为 proposal。新声明必须使用已加载类型，能够解析，并\n通过当前 workspace 的 lint。非法 proposal 会被拒绝；与 pending/approved 内容\n完全相同的提交返回 `no_op`；其余 proposal 要么排队，要么由宿主证明过的窄\n策略自动批准。\n\n默认仍然全部人审。先生成一份合法但禁用自动批准的 policy：\n\n```console\nmemdsl review policy init memory\nmemdsl review policy show memory\nmemdsl review policy validate memory\n```\n\n生成的 JSON 里 trusted clients 和 rules 都为空，日限额为 0。要开启自动化，\nworkspace owner 必须给一个 candidate assertion 类型显式加入\n`auto_approvable`，配置精确 kind 规则和可信宿主 client，设置正数日限额，\n再授予默认不包含的 `write:auto` scope：\n\n```console\nmemdsl-mcp --workspace memory \\\n  --scopes read:summary,read:search,write:candidate,write:auto\n```\n\n内置 `workspace_file_quote` verifier 要求 `evidence.source` 解析到已加载\nworkspace root 内，且 `evidence.quote` 必须逐字出现在该 UTF-8 文件中。\nquestion、guidance、constraint、symbol、active、global、带 warning、带破坏性\n关系或证据未验证的 proposal 始终排队。没有 `write:auto` 时，合法 policy\n处于 shadow 姿态：写入仍 pending，但 `eligible_route` 会记录策略原本会怎么做。\n\n人工操作与质量反馈保持显式：\n\n```console\nmemdsl review list memory\nmemdsl review approve memory PROPOSAL_ID --into memory/approved.mem\nmemdsl review reject memory PROPOSAL_ID --reason \"not durable\"\nmemdsl review digest memory\nmemdsl review stats memory\nmemdsl review audit memory PROPOSAL_ID --verdict confirm\n```\n\n`review list`、`review show`、`review audit` 与已有的 `policy show`、`digest`、\n`stats` 一样支持 `--json`，队列面板或 CI 任务不必再解析给人看的文本。approve\n与 reject 仍然只有文本输出，保持决策动作显式。\n\n进程内宿主应传入权威 workspace paths：\n\n```python\nfrom memdsl import (\n    ProposalContext,\n    ReviewStore,\n    Workspace,\n    load_policy,\n    staging_dir_for,\n)\n\nworkspace = Workspace.load([\"memory\"])\nstore = ReviewStore(staging_dir_for([\"memory\"]))\npolicy = load_policy(store.staging_dir, registry=workspace.registry)\nassert policy is not None\ncontext = ProposalContext(client_id=\"mcp-client\")\n\nresult = store.submit(\n    [\"memory\"],\n    proposal_source,\n    policy=policy,\n    context=context,\n    write_auto_granted=True,\n)\n```\n\n自动批准前会重新加载并 fingerprint 记忆、manifest 和 schema，重新验证证据，\n执行有限 UTC 日配额，只写入主 workspace root 内的非 symlink `.mem` 目标，\n且绝不使用 `force`。路由 assessment、decision、post-review 结果、digest\ncursor 和 no-op 事件都保持 append-only。\n\npost-review `flag` 不会静默删除记忆。晋升、修订和撤销都要提交一条新 id 的\n人工审核声明，用 `supersedes`（可同时用 `revision_of`）指向旧声明。successor\n必须是 lifecycle `active` 才获得关系 authority；旧声明不需要原地改成\n`status: superseded`。\nReviewStore 不创建 Git commit；宿主可以增加 Git 集成，但核心正确性不依赖 Git。\n\n### 包里有什么\n\n- 与领域无关的 `.mem` 通用记录：来源、scope、confidence、lifecycle、\n  access policy、relations 和稳定 id。\n- 可扩展、带 namespace 的 `.memschema.json` 类型系统和 workspace manifest。\n- 面向 v0.5 之前 workspace 的标准兼容类型包。\n- schema 驱动的 linter、分层查询、explain 和确定性 Compliance Gate。\n- CLI 与 MCP 的类型发现能力。\n- 默认安全、宿主证明的审核链路：人工队列、确定性的窄范围自动批准、no-op\n  检测、digest/stats 和 append-only audit。\n- 可复现合规 benchmark，以及 coding、assistant、writing 三个领域包。\n- Alex、Mira 两个虚构标准示例和一个故意损坏的 lint 示例。\n\n完整语法与语义见 [docs/SPEC.md](docs/SPEC.md)。进程内宿主还应阅读\n[docs/PUBLIC_API.md](docs/PUBLIC_API.md) 和 [docs/UPGRADING.md](docs/UPGRADING.md)。\n审核策略的安全合同见\n[docs/DESIGN_review_policy.md](docs/DESIGN_review_policy.md)。\n[文档索引](docs/DOCUMENTATION_INDEX.md) 把软件合同、实现设计、发布边界和\n可复现材料集中在一起。\n\n### memdsl 不是什么\n\n- 它不是 Mem0、Zep、Graphiti、LangMem 等检索/抽取系统的替代品，而是位于\n  这些系统之上的受治理源格式和行为契约。\n- 它不是人或记忆的通用分类法；领域所有者定义自己的类型。\n- 它不是语义策略裁判；无法确定性执行的约束会保持 `NEEDS_REVIEW`。\n- 它不是不受限制的自动记忆写入器。只有显式 opt-in、身份可信且证据已验证的\n  candidate assertion 才可能自动批准；所有高风险或不确定 proposal 仍由人审。\n\n### 当前证据与边界\n\n这个项目来自一个私有的单用户系统。该系统的内部评测曾显示，DSL 结构化检索的\nprecision 高于它自己的调优 RAG baseline。这个结果值得继续验证，但不能证明一套\nontology 对所有人都通用。v0.8 正面承认这个限制：memdsl 标准化记录结构和运行\n契约，把领域词汇的所有权交还给使用者。\n\n仓库内置的是确定性的契约级测试。跨模型行为结论仍需单独记录真实模型运行。\n\n### Roadmap\n\n- ~~两层 core + 可扩展领域类型系统~~ — v0.5 已完成\n- ~~lifecycle 安全的 provisional 服务 + 分级审核策略~~ — v0.6 已完成\n- ~~公共可重建 CompiledWorkspace + 有界 Catalog 分页/预算~~\n  — 0.9.0 已发布的 stable/public 0.8 合同\n- ~~倒排查询 + 有界 Trace + exact use/report/strict + 受审核 Dialect~~\n  — 0.9.0 已发布的 stable/public 0.8 合同\n- ~~显式 v2 envelope 下的 opt-in quarantine enforcement~~ — schema/安全合同 stable/public，真实 rollout 质量仍为 experimental\n- ~~显式 opt-in 的一等可审核 Edge 实验~~ — `0.9.0` 以 experimental\n  状态承载该能力，依据匿名探索性\n  Pilot 开启；relation/evidence 收窄结论仍为 **ADJUST**，不是正式实证验证\n- 冷历史/增量编译 — 等待代表性规模、SLO 与生产瓶颈证据\n- Schema 包分发、依赖/版本约束和迁移机制\n- 更丰富的字段验证器和领域诊断规则\n- EvidencePack 后面的可插拔检索后端\n- 执行 access policy 的身份提供商适配器\n- 基于 shadow/sample/post-review 数据的语义冲突 reviewer 与 per-client/per-rule\n  配额\n\n### 许可证\n\n代码：[MIT](LICENSE)。规范（[docs/SPEC.md](docs/SPEC.md)）：CC-BY-4.0。\n",
  "bytes": 46272,
  "sha": "3211a28dd6974aa45905d51f72aaa842fd8781038ae2b66541d7102d463145de",
  "repo_slug": "liyuan1992/memdsl",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_liyuan1992_memdsl_9eee714a/readme"
}