Skip to content

Add persistent-memory primitives: live_extract, contradiction_pipeline, correction_gate - #2

Closed
agulaya24 wants to merge 82 commits into
mainfrom
memory-primitives
Closed

Add persistent-memory primitives: live_extract, contradiction_pipeline, correction_gate#2
agulaya24 wants to merge 82 commits into
mainfrom
memory-primitives

Conversation

@agulaya24

Copy link
Copy Markdown
Owner

What this adds

Three package modules under src/baselayer/ that form the stable per-conversation ingestion/consistency layer for the planned conversation-capture proxy (D-049):

  • live_extract.py: single-conversation extraction orchestrator. Wraps extract_facts.process_conversation, snapshots fact IDs before extraction, reports each newly stored fact as an ADD action, runs the contradiction hook on new state-facts, and returns a change manifest (conversation_id, facts_stored, actions, contradictions_found, probes_queued, optional error). Also supports import-then-extract for a single file. Runnable as python -m baselayer.live_extract.
  • contradiction_pipeline.py: per-fact consistency check. ChromaDB similarity search over active state-facts, LLM classification into contradiction / enrichment / coexistent / ambiguous, then execution: contradictions supersede the older fact, ambiguous pairs land in a probe_queue table, enrichment and coexistence take no action. Follows D-036 (Binary Collapse Resistance: default coexistent on any failure) and skips events (immutable).
  • correction_gate.py: query-time fact filtering for the serving layer. Pass 1 drops superseded_by IS NOT NULL; pass 2 drops facts with a delete/supersede row in user_corrections. Corrections take effect immediately without re-running the pipeline.

Placement reasoning

These were loose scripts under scripts/, which a recent commit is actively cleaning out (the orphaned mirror was retired). They are library code with a small public API that the capture proxy will import per conversation, so they belong in the package: absolute baselayer.* imports, no sys.path mutation, shipped by the existing packages = ["baselayer"] setuptools config, testable under the standard suite.

Scrubbed / hardened

  • No personal names, machine paths, or keys were present in the originals; verified again after the move (no C:\Users, no subject names beyond the public examples, no key material).
  • All constants and paths routed through config.py. Classification model now routed through LLM_PROVIDER_CONFIG["contradiction"] (env-overridable via BASELAYER_LLM_CONTRADICTION) instead of a hardcoded model constant.
  • correction_gate rewired from a nonexistent fact_corrections table to the standard user_corrections schema (original_fact_id, correction_type matched case-insensitively; flag corrections do not remove facts). IN(...) lists chunked below SQLite's host-parameter limit.
  • probe_queue.created_at set explicitly at insert time; the previous unixepoch() column default requires SQLite 3.38+.
  • LLM judgments outside the four valid categories are rejected and degrade to coexistent.
  • Extraction and contradiction-hook failures are logged and reported in the manifest instead of raising; silent bare excepts replaced with logging on the paths that matter.
  • Dead code removed (unused imports, an unused source-conversation lookup in cascade detection).

Test coverage

29 new tests in tests/test_memory_primitives.py, using the existing temp_db/populated_db fixtures, all API calls mocked:

  • live_extract: manifest shape with new-fact ADD actions, pre-existing facts not re-reported, NOOP path, conversation-not-found, extraction failure, contradiction hook invocation and hook-failure isolation.
  • contradiction_pipeline: classification parsing (clean JSON, embedded JSON, invalid judgment, API error), judgment execution per verdict (supersession, probe queueing, no-op), batch dispatch counting, event/incomplete-fact skipping, similarity-search filtering (self, threshold, superseded).
  • correction_gate: superseded filtering, delete/supersede corrections (both cases), flag corrections retained, missing-table tolerance, large-list chunking, get_active_facts shape and subject filter.

Full suite: 480 passed (451 existing + 29 new). Doc test counts updated (CLAUDE.md and AGENTS.md were already stale at 403; CONTRIBUTING at 414).

🤖 Generated with Claude Code

agulaya24 and others added 30 commits March 9, 2026 16:36
Behavioral compression pipeline: Import → Extract → Author → Compose.
47 constrained predicates, 414 tests, 76 design decisions.
Validated on 10 subjects across 6 source types (73-82/100).
Twin-2K benchmark: 71.83% accuracy at 18:1 compression (p=0.008).

Apache 2.0. https://base-layer.ai
Radial falloff with per-dot size/opacity variation, 28px spacing, sky-400 color.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Increased dot radius (1.0-2.0) and opacity (0.12-0.55) so the pattern
is clearly visible on GitHub dark and light mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
SVG dots were invisible against GitHub's dark background. PNG with
slate-900 background and prominent dot grid renders reliably.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…arent PNG

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- ARCHITECTURE.md: S74 north star, honest local-first→API evolution,
  accessibility improvements, smart links to ablation results
- DESIGN_PRINCIPLES.md: Data Sovereignty honest about API default,
  brain-inspired/surprise-based marked partially superseded per S79 ablation
- FLOW_GUIDE.md: Simplified to 4-step pipeline, updated costs/times,
  added baselayer run one-command version
- PROJECT_OVERVIEW.md: Session 82 metrics, completed milestones,
  subject names with full context
- EPISTEMIC_AXIOMS.md: Expanded jargon and session references for new readers
- All docs: cross-links, first-use explanations, GitHub-relative paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Full audit found 37 contamination sources across agent_pipeline.py and
author_layers.py. The compose prompt's literal example sentence was copied
verbatim into 7/11 briefs. Fix: remove all example sentences, ban formulaic
openings, expand blocklist from 11→30+ phrases, add Contamination Gate to
compose output. Franklin recompose test: Gate PASSED, zero template phrases.

Also adds PSYCH_PROFILING_EVAL_SPEC.md (D-078-PSYCH).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three upstream template sources identified and fixed:
1. ANCHORS: Removed mandatory GENERAL FRAME (was generating identical
   "hold tension explicitly" boilerplate in all 11 anchors layers).
2. CORE: Rewrote internal processing style from leading binary question
   to evidence-required-only (was causing "surfaces problem, already
   pre-processed" in 4/11 briefs from text format, not behavior).
3. COMPOSE: Made [THIN DATA] conditional instead of mandatory (was
   forcing identical "Behavioral prediction data is insufficient"
   boilerplate in 7/11 briefs regardless of actual data coverage).

Also: compose retry with decontamination on gate failure, bumped
author max_contamination_retries 1->3, added 14 new phrases to
blocklist (acknowledge both sides, forcing resolution, etc).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ation (33→0)

Problem: Opus compose step injects pre-training knowledge for famous subjects
despite anonymization and "derive only from input" constraints. Franklin had
18 ungrounded claims, Aarik had 1 inverted claim (brief said opposite of source).

Solution: Split composition into Planner (Opus, sees all layers, outputs
structured claim plan) and Executor (Sonnet, sees ONE claim + its source text
per call, cannot infer identity). Context isolation prevents pre-training
knowledge injection.

Test result on Franklin: Opus-only 33 ungrounded claims → P-E brief 0.
Cost: $0.33 vs $0.25 (30% increase). Pending multi-subject validation.

Files:
- docs/diagnostics/D079_PROVENANCE_ENFORCEMENT_DIAGNOSTIC.md (full analysis)
- scripts/experiments/planner_executor_test.py (test harness)
- docs/core/DECISIONS.md (D-079 entry added)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
… variance?

Hypothesis: behavioral brief acts as stabilizer — reduces response variance
across temperature settings compared to no-brief and same-length control.
1,200 API calls, 3 conditions, 4 temperatures, 10 prompts, 2 subjects.
~$10 estimated cost. Falsifiable predictions at each temperature level.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fixes soft contamination found in v1 multi-subject test:
- Executor prompt bans intensifying adjectives, editorial framing,
  clinical labels, and causal explanations not in source material
- Availability index generated by planner from source layers (not
  assembly hallucinating from pre-training — fixed Buffett 7→0 items)
- Assembly passes planner's availability index verbatim
- Planner output format changed from array to object with paragraphs +
  availability_index keys

v1 results: Franklin 33→0, but Buffett/Aarik/Douglass showed 15-42
soft contamination (embellishment, not biographical injection).
v2 Buffett test: availability index fully grounded, prose quality improved.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Assembly prompt was reordering paragraphs by "concreteness," putting
niche trading scenarios before broad identity patterns. Fix: preserve
planner's paragraph ordering (broadest pattern first, specifics later).
Tested on Aarik — opens with core coherence principle, narrows into
domain-specific patterns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- ARCHITECTURE.md: reframed around agentic world framing — identity as
  load-bearing infrastructure, owned/auditable/portable brief, removed
  bravado language about AI "knowing you like a friend"
- V5 two-file system: brief_v5.md (cited) + brief_v5_clean.md (stripped),
  served via MCP from clean version
- agent_pipeline.py: auto-generates both cited and clean on compose
- config.py: UNIFIED_BRIEF_FILE -> brief_v5_clean.md, added UNIFIED_BRIEF_CITED_FILE
- mcp_server.py, cli.py, ui.py, generate_website_data.py: updated brief paths
- Experiments: contradiction ablation scripts moved to experiments/,
  result JSONs moved to experiments/results/, new eval/research scripts added
- D-079 prompt ablation report + rubric calibration doc (C28 wins 84.3/90)
- D-080 V5 compose report
- Temporal stability results (Aarik GPT, no direction effect confirmed)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace all hardcoded /home/agulaya and /mnt/c/Users/Aarik paths in
data/swebench/analyze_results.py with pathlib.Path derivations:
- Paths within the repo (ratings file, report output) now use
  Path(__file__).parent relative to the script's own location.
- External OpenHands benchmarks dir now reads from OPENHANDS_BENCHMARKS_DIR
  env var, falling back to the original WSL path as a documented default.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add patentmind_agent.py, baselayer_agent.py, patentmind_state.json
  to .gitignore (Moltbook bot + API key — never commit)
- Add data/swebench/ to .gitignore (live experiment state)
- Add drift results + overnight results dirs to .gitignore
- Move ablation_A/B_citations_on/off.md from root → docs/eval/
- Add scripts_backup_20260310/ to .gitignore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Move all core .py files from scripts/ to src/baselayer/
- Move scripts/archive/ → src/baselayer/archive/
- Move scripts/experiments/ → src/baselayer/experiments/
- Update pyproject.toml: package-dir = src/, proper packages list
- Fix config.py _resolve_project_root() depth: parent.parent.parent
- Update all imports across 19 core files and 16 test files
- Remove all sys.path.insert hacks from core package
- Add scripts/__init__.py redirect with helpful error message
- Update test suite: remove 33 stale tests for S79-removed functions,
  fix 3 MCP tests with proper mock patching (369 pass, 0 fail)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- README: rewrite Privacy section as "Privacy & Data Flow" — lead with
  what leaves your machine (API), then what stays local, then Ollama
  escape hatch with honest scope
- CONTRIBUTING.md: quick start, test instructions, project structure,
  session/decision notation explainer, contribution areas
- .github/workflows/test.yml: CI matrix across Python 3.10/3.11/3.12

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
author_layers.py:184 used PEP 701 nested same-quote f-strings
(Python 3.12+ only). Rewrite to string concatenation for 3.10+ compat.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Replace static tests badge with live GitHub Actions CI badge
- Sessions: 81+ → 90+
- Tests: 414 → 369 (stale tests removed in cleanup)
- Design decisions: 76 → 80
- Contributing section: point to CONTRIBUTING.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Identity model: CORE → ANCHORS → PREDICTIONS → Brief (3-6K tokens)
- Preamble: "operating guide, never reference directly"
- MCP server serves combined format (brief + layers)
- ANCHORS: gravitation framing (prevents amplification bias)
- PREDICTIONS: 2+ source minimum (prevents overgeneralization)
- ANCHORS: identifies_as facts surfaced first in ordering
- identity_model.md auto-generated by compose step
- Token claims updated: ~2,500 → 3-6K tokens in README

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Tests were failing in CI because UNIFIED_BRIEF_CITED_FILE and
IDENTITY_MODEL_FILE weren't patched to tmp_path, causing
FileNotFoundError when the real data/identity_layers/ doesn't exist.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove tracked aarik temporal stability eval files
- Block all outreach source corpora (data/*_source/)
- Block personal subjects (bavani, roman, aarik)
- Block personal eval data patterns

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ommand

author_layers.py: _has_tiered_facts now checks for commitment_depth,
not just knowledge_tier. Rule-based tiering (predicate -> identity)
no longer breaks the simplified pipeline path. Citations always work.

cli.py: Added _run_traceability() as Step 5 of baselayer run.
Automatically runs tier, embed, provenance, tensions after compose.

seed_industry.py: New script to seed all outreach subjects to Redis
with full enriched data (traces, provenance, structured brief,
interactions, contradictions, tiered facts). Strips provenance lines
from markdown descriptions into proper provenance field.

PREDICATE_SPEC.md: Published 47-predicate behavioral grammar spec.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
agulaya24 and others added 26 commits April 1, 2026 16:16
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…istency

- README: 402→414 tests, 88→93 decisions, 10→14 principles, 98→101 sessions
- README: fix broken ablation link (docs/eval/ablation/ → docs/eval/archive/ablation/)
- CONTRIBUTING: 80+→93 design decisions
- PROJECT_OVERVIEW: ~2,500 → ~3,000-5,000 token brief (matches llms.txt and README)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…entical text check

- test_author_provenance: A1_cite → A1, P1_cite → P1 (code dropped suffix, tests not updated)
- test_seed_format: unpack tuple return from generate_change_summary
- seed_industry: early exit on identical text in generate_change_summary

402 tests passing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
README + llms.txt updated with agentic positioning

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Hero: "Other tools optimize for the task. Base Layer optimizes for you."
- Subjects: 44+ -> 57+
- Vision: reframed from personalization to agentic alignment + constraint layer
- Limitations: temporal trajectory in research, not "no model of change"
- Active research: added temporal trajectory, 66-model collective review, failure modes, stacking findings
- Core framing: AI never knew, not AI forgot

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1,082 lines -> 468 lines. Cut all historical/ceremonial content.
- Problem reframed: "AI never knew" not "AI forgets"
- Removed brain metaphors, old layer descriptions, speculative sections
- Design decisions table with one-phrase explanations
- Pipeline steps 1-5 with schema, data flow, and rationale
- Current state only, no archaeological layers
- 57+ subjects, 3-6K token briefs, 101+ sessions

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- README: "The behavioral layer for AI agents", behavioral specification language
- ARCHITECTURE.md: operating guide → behavioral specification, operational constraints
- PROJECT_OVERVIEW.md: personal AI memory → behavioral alignment infrastructure
- DESIGN_PRINCIPLES.md: personal memory system → behavioral specification system
- llms.txt: full rewrite — behavioral specifications, agent alignment framing
- pyproject.toml: updated description and keywords
- cli.py: Personal AI Memory System → Behavioral Alignment for AI Agents
- author_layers.py: CORE layer label + domain guard updated
- mcp_server.py: identity model → behavioral specification in preamble
- test_unified_brief.py: assertion updated to match new preamble

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…arch docs

Serving layer prototype — the behavioral diff cascade:
- serving_engine.py: core logic — load spec, retrieve facts, generate responses,
  compute diff. Mem0-faithful baseline (Chhikara et al., 2025). Multi-subject support.
- serving_tui.py: Textual TUI visualizing the cascade live. 7 panels showing
  Mem0 vs Base Layer retrieval divergence, spec activation, three response conditions.
  Non-blocking startup, error logging, embedding cache.
- question_battery.py: 50 questions across 10 topics, mechanical measurements only.
  No subjective scoring. Maps structural divergence by topic.
- question_battery_subject.py: Multi-subject version for cross-validation.

Research documentation:
- SERVING_LAYER_PLAN.md: full architecture — the diff as identity signal, daemon design
- SERVING_LAYER_EVAL.md: 6-condition eval spec including C6 model-routed activation
- TEMPORAL_PREDICTION_STUDY_V2.md: clean temporal split design (v1 failed)
- BEHAVIORAL_INFLUENCE_COMPLETE_PLAN.md: complete research plan with collective review
- SERVING_LAYER_RESEARCH_BRIEF.md: briefing doc for external feedback

Key findings (S102):
- 18/19 retrieval divergence between Mem0 and Base Layer on same fact store
- Spec consistently produces fewer lists, more questions (conversation vs info dump)
- Relationships topic shows highest structural divergence (4.75 avg)
- AlpsBench proved recall != alignment — Base Layer fills that gap

Experimental — not production. Requires anthropic + openai + sentence-transformers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Optional last step in the pipeline flow:
  baselayer run <file>     # build the spec
  baselayer export --open  # view it in browser

Generates a single HTML file with tabbed view (Brief, Anchors, Core, Predictions).
No server needed. Dark theme matching base-layer.ai. Self-contained — works offline.

Designed for AI agents (Claude Code, Cursor) to display the spec to users
after a pipeline run, but works for anyone who wants to see what was built.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The always-on memory://specification resource now returns CORE plus a
manifest of additional tools, instead of the full unified specification.
ANCHORS, PREDICTIONS, and the unified brief are exposed as
model-controlled tools (get_anchors, get_predictions, get_brief) the
model calls on demand.

Rationale: empirical work on the Beyond Recall study shows the
specification's largest effect is on interpretation-heavy questions
(judgments, decisions, predictions about the user's behavior), not
literal recall. The manifest tells the model when fetching a layer is
worth the context cost, with concrete trigger examples and a "not a
substitute for the user" caveat.

Baseline MCP context cost drops from approximately 5,000 to 10,000
tokens to approximately 2,500 tokens. The other layers remain available
within one tool call.

Adds:
- get_anchors(), get_predictions(), get_brief() tools with concrete
  trigger language and "not for X" guards
- get_call_log() tool: in-process ring buffer of recent MCP calls,
  queryable by the model for self-inspection
- Per-call stderr logging (format: [base-layer] INFO: mcp_call name=X)

Preserves:
- memory://identity as a deprecated alias to memory://specification
- All five existing tools (recall_memories, search_facts, trace_claim,
  verify_claims, get_stats)

Tests: 422 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…able)

The `baselayer` package name on PyPI is held by an unrelated project
(SkyPortal baselayer, Stéfan van der Walt). Base Layer cannot publish
under that name. Updates user-facing install instructions across the
repo to use `pip install git+https://github.com/agulaya24/BaseLayer.git`
instead, with version-pinning via `@v0.2.0` (paper baseline) or `@main`
(current 0.3.0).

Files updated:
- README.md, AGENTS.md: Quick Start and Setup sections
- llms.txt: reproducibility section
- CHANGELOG.md: 0.3.0 and 0.2.0 reproducibility notes
- docs/core/FLOW_GUIDE.md: Step 1 install
- docs/core/ARCHITECTURE.md: package row in tech stack table
- docs/core/MCP_REGISTRY_SUBMISSIONS.md: install JSON for registry
- recipes/run_pipeline_on_chatgpt_export.md, recipes/serve_specification_via_mcp.md: prerequisites

Historical references to `pip install baselayer` in CHANGELOG.md (older
entries) and docs/core/DECISIONS.md (decision rationale) are preserved
as written.

The paper-baseline source is also vendored directly into the
memory-study-repo at ./baselayer/ so paper readers do not need to
install separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two stale descriptions that still asserted full-spec injection on every
turn:

- docs/core/ARCHITECTURE.md: Serving Layer section was titled "Specced,
  Not Built" and said "current serving path injects the full
  specification every turn". 0.3.0 shipped partial-serving, so renaming
  the section and rewriting the body to cover what shipped, plus a note
  that activation matching remains a future direction.
- recipes/serve_specification_via_mcp.md: goal/expected-output framed
  the always-on resource as loading the full unified specification.
  Updated to describe CORE plus manifest, the on-demand layer tools,
  and the get_call_log inspection path. Added a failure-mode entry for
  "model never calls get_anchors/get_predictions" pointing at the
  stderr log and the Beyond Recall trigger-language rationale.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related additions for monitoring and controlling MCP spec serving
without a Claude Code restart.

Toggle:
- New CLI: `baselayer serve enable | disable | status`
- Reads/writes ~/.baselayer/serving_enabled (single character "0"/"1")
- MCP server checks the file on every resource read and on every layer
  tool call (get_anchors, get_predictions, get_brief). When disabled,
  returns a "spec serving paused, run `baselayer serve enable`" message
  instead of content. The model is told to continue helping without
  spec context. Fact-database tools (recall_memories, search_facts,
  trace_claim, verify_claims, get_stats) keep working.
- Mid-session flips take effect on the next MCP call. No restart of
  the server or the host required.
- Default (file missing) is enabled, preserving prior behavior.

Counter:
- ~/.baselayer/mcp_session_count holds an integer call count
- Reset to 0 on server startup, incremented on every _log_call,
  deleted on clean shutdown via atexit handler
- Designed for external monitors (IDE statuslines, scripts) that want
  live call volume without speaking the MCP protocol

Tests: 7 new tests for the toggle covering default-enabled, "0"
disables, "1" enables, and disabled-message return paths for all four
serving handlers. Suite at 429 tests, all passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related changes for understanding when and why the model decides to
pull from Base Layer.

Per-session storage:
- Replaces the single-file counter at ~/.baselayer/mcp_session_count
  with per-session directories at ~/.baselayer/sessions/<pid>/.
- Each running server writes meta.json (pid, parent_pid, start_time,
  cwd), count (live integer), and log.jsonl (append-only call log).
- Two simultaneously-open Claude Code windows now show independent
  counts instead of sharing one. The statusline finds its window's
  session by matching its own parent PID against the recorded
  parent_pid in each session's meta.
- Sessions persist on disk after the server exits. The atexit handler
  deletes `count` to signal "ended", but meta.json + log.jsonl stay
  for offline analysis.

Reason capture:
- get_anchors, get_predictions, get_brief gain an optional `reason: str`
  parameter. Docstrings ask the model to provide a one-sentence
  rationale for each fetch (e.g. "user weighing a job offer that
  involves a values trade-off").
- The reason is persisted in the per-session log.jsonl, giving a
  record of when in the conversation the model decided it needed each
  layer and why.
- The always-on resource manifest tells the model to include `reason`
  on every layer-tool call.

CLI:
- New `baselayer log list | show | tail | stats` subcommand for
  inspecting traces. `list` shows all sessions with state and counts;
  `show <pid>` prints the full call log; `tail --pid X --limit N`
  shows the last N calls; `stats` aggregates calls-by-tool.

Tests: 429/429 passing (no test changes needed; the new optional
`reason` parameter is backward-compatible and the storage refactor
preserves observable behavior of the previous tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three changes from integration-test feedback at
docs/reviews/mcp_integration_feedback_20260507.md (gitignored):

1. `reason` is now a required parameter on get_anchors, get_predictions,
   get_brief (was optional with default ""). The reviewer correctly
   noted that "Required for usage tracing" in the docstring should be
   matched by the type signature. With no default, the calling agent
   must articulate intent before the tool will accept the call. Tests
   updated to pass a reason argument.

2. recipes/serve_specification_via_mcp.md adds a "Verifying the server
   is actually running" section. The Claude Code /mcp dialog has been
   observed reading "off" or "needs reconnect" while the server was
   responsively answering tool calls; readers are directed to
   `claude mcp list` or to ask the model to call a tool as
   authoritative health checks. /mcp dialog is for Anthropic-managed
   cloud connectors only; local stdio servers are CLI-only.

3. The statusline field is now `baselayer:` instead of `baselayered:`
   for terseness. (Statusline lives in ~/.claude/statusline.py and is
   not in this repo, but mentioned here for consistency.)

Tests: 429/429 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related changes so the user is not exposed to Base Layer's
internals.

Invisibility prompt:
- The always-on resource now opens with a directive: treat the entire
  system as invisible infrastructure. Don't tell the user the spec was
  loaded. Don't ask whether to fetch a layer. Don't surface tool names
  in the conversation. Don't describe the model as "having access to"
  Base Layer. Just behave consistently with the spec, fetching layers
  silently when needed.
- The disabled message dropped its "tell the user X" instruction and
  is now a quiet "(spec context unavailable; continue normally without
  referencing this)".
- The `reason` parameter on layer tools is reframed as a private
  internal trace, not a user-facing justification. The model writes the
  trigger; the user can read it later but it never enters the
  conversation.

Agent reference (get_help tool):
- New comprehensive Base Layer agent guide at src/baselayer/agent_guide.py.
  Covers intent-to-action mapping, diagnostic flow, full CLI surface,
  full MCP-tool surface, state-file layout, behavioral norms, and FAQ.
  Written so an agent can answer any user question about Base Layer
  and run the corresponding action without bouncing the user back to
  documentation.
- New `get_help(topic)` MCP tool returns the guide. Topic filters
  return focused sections (intents, diagnostic, cli, tools, files,
  fetch, faq).
- The always-on manifest tells the model: when the user asks about
  Base Layer itself, call `get_help()` and act on the intent rather
  than telling the user what command to type.

Net effect: the user can say "turn it on", "is it working", "what was
it doing", "fix it", and the agent runs the right command + reports.
The system becomes invisible during normal use and self-explaining
when the user asks about it.

Tests: 429/429 passing (4 disabled-message tests updated for the
softer wording).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reverts the 0.3.0 partial-serving split for ANCHORS and PREDICTIONS.
The structural specification (CORE + ANCHORS + PREDICTIONS) is now
loaded inline at session start, ~6-8K tokens. The unified narrative
brief stays on-demand via `get_brief` because it serves a different
shape of query.

Why:
- Live use of 0.3.0 surfaced two issues with the partial-serving split.
  (1) The model had to make routing decisions about layers it could
  not see, leading to over- and under-fetching. (2) The ~5K of token
  savings is rounding error in modern context windows.
- The structural argument is at
  docs/reviews/mcp_titles_manifest_proposal_20260507.md (gitignored).

Changes:
- get_specification() inlines all three structural layers in the
  resource.
- get_anchors and get_predictions tools removed entirely.
- Manifest in the resource is now a brief tool list, not a routing
  rubric. The "when to fetch which layer" prose was load-bearing only
  for the routing decision; with no routing decision, it's gone.
- get_brief retains its `reason` parameter (private internal trace).
- Agent guide's "When to fetch which layer" section reduced to one
  short paragraph about when to fetch the unified brief.
- Tests updated: TestSpecificationTools now verifies removal; resource
  tests assert all three layers are inlined.
- Version bumped 0.3.0 -> 0.4.0; CHANGELOG entry covers the reversion
  and the rationale.

Tests: 424/424 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…sonal scripts

Prevents committing the 798 MB data/_backup_* and data/_snapshot_* snapshots,
experiment/dataset dirs (experiments, external_datasets, scotus, collective_review),
and outreach scripts that carry personal data (emails, subject names).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
CODEOWNERS, SECURITY.md, CODE_OF_CONDUCT.md, .editorconfig, ROADMAP.md, ORIENTATION.md
for public-repo readiness. tests/test_verify_provenance.py and
tests/test_ingestion_content_preservation.py were part of the running 451-test suite
but untracked; a clean clone was missing them.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
… duplicate

docs/research and docs/reviews (the latter already gitignored) plus assorted
internal notes are removed from the public tree; all remain recoverable from
history at 63f2aa8. scripts/mcp_server.py was a 473-line orphaned duplicate of
src/baselayer/mcp_server.py (the registered baselayer-mcp entry point); no code
references it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…red archive)

scripts/ held an orphaned 2026-04-07 mirror of src/baselayer modules; the live,
shipped code is src/baselayer/ (registered as the console entry points in
pyproject.toml). The 18 duplicate modules are moved to
scripts/archive/legacy_mirror/ (gitignored) — kept locally for reference,
removed from the repo. No code imports the scripts package.
scripts/swebench_harness.py (not a duplicate) is retained.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Cuts ~40% (276 to ~165 lines). Reframes toward the tool's function;
moves detailed paper results to the paper. Adds HF benchmark dataset link
and llms-full.txt. Fixes: 46 behavioral predicates, 451 tests, full-spec
paste-token label, compression section reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Pre-existing src/baselayer refactor (per-source extraction caps, IDENTITY_PREDICATES
as config source-of-truth, chunked batch extraction with chunk-level resume, shared
predicate tiering, init_database schema trim, MCP serving via FastMCP instructions,
identity->specification terminology) plus stability hardening:
- pyproject: testpaths=["tests"] so bare `pytest` no longer collects stray tests
- embed.py: UTF-8 stdout/stderr so verification can't crash mid-pipeline (Windows cp1252)
- extract_facts.py: two no-silent-data-loss guards (stale vectors; <50-fact full run)
- tests: guard-predicate unit tests; privacy test now checks src/baselayer/config.py
  (was pointed at the retired scripts/ duplicate)

451 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…DME)

The earlier 403->440 bump predated the 11 stability-guard tests that brought the
suite to 451. README (pushed) already says 451; aligning ORIENTATION.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…e, correction_gate

Move the three loose ingestion/consistency scripts into src/baselayer/ as
package modules. These form the stable per-conversation layer a planned
conversation-capture proxy (D-049) will call.

- live_extract: single-conversation extraction orchestrator. Wraps
  extract_facts.process_conversation, snapshots fact IDs, runs the
  contradiction hook on new state-facts, returns a change manifest.
  Extraction and hook failures are reported in the manifest, never raised.
- contradiction_pipeline: per-fact ChromaDB similarity search, LLM
  classification (contradiction/enrichment/coexistent/ambiguous), and
  judgment execution with a probe_queue for ambiguous pairs. Model routed
  through LLM_PROVIDER_CONFIG["contradiction"]. Any classification failure
  degrades to coexistent (D-036 Binary Collapse Resistance).
- correction_gate: query-time filtering of superseded and manually
  corrected facts. Rewired from the nonexistent fact_corrections table to
  the standard user_corrections schema (original_fact_id, case-insensitive
  correction_type). IN(...) lists chunked below SQLite's parameter limit.

Hardening: package-absolute imports (no sys.path mutation), constants
routed through config.py, unknown LLM judgments rejected, probe_queue
created_at set explicitly (no unixepoch() default, needs SQLite 3.38+),
logging instead of silent excepts.

Tests: 29 new tests in tests/test_memory_primitives.py covering the
change-manifest shape, classification dispatch and degradation, judgment
execution, and gate filtering. All API calls mocked. Suite: 451 -> 480.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fb8f1776-036c-4d85-9e3c-a2ea375f5473

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch memory-primitives

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@agulaya24 agulaya24 closed this Jul 16, 2026
@agulaya24
agulaya24 deleted the memory-primitives branch July 16, 2026 21:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant