Skip to content

Automations

Chris edited this page Nov 30, 2026 · 61 revisions

Automations & Nightly Cognitive Maintenance

Tip

Value Proposition: Keep project memory self-cleaning, self-healing, and drift-free automatically. Memory Journal pairs session lifecycle hooks with Cognitive Management System (CMS) nightly automationsβ€”consolidating episodic notes into semantic knowledge (CMS-02) and healing recurring tool friction (CMS-04) while you sleep.

Memory Journal provides two complementary layers of automation (plus optional startup auto-pruning and one-shot memory-journal-mcp admin CLI subcommands for zero-token OS cron / container schedules):

  1. Session Hooks & Issue Telemetry (SessionStart, PreToolUse, PostToolUse, & Built-In Logger) β€” Client hooks inject deterministic workspace_id, project_number, briefing_uri, repo_map_uri (memory://repo-map/<repo>), optional code_map, and peer_repos context at startup, guard bare memory://briefing / memory://repo-map / memory://graph / memory://agent-context URIs and mj_execute_code scope/share_with_team: true calls before execution, and pair with the server's built-in issue logger (logs/agent-issues.jsonl, configurable via DISABLE_ISSUE_LOGGING) to capture redacted validation friction for nightly healing.
  2. Agentic Cognitive Automations (CMS-02 & CMS-04) β€” Scheduled AI sessions powered by native MCP prompts (optimize-journal and cms-rem-supervisor) and Code Mode (mj_execute_code) to compact fragmented notes, verify Git/GitHub ground truth, repair graph links, audit soft-deletions, and self-heal agent friction.

1. Architecture: Awake Hooks & The Nightly CMS Sleep Cycle

Inspired by human memory consolidation, the Cognitive Management System (CMS) connects daytime coding telemetry to a staggered sleep cycle that separates high-volume Data-Plane database curation (CMS-02) from Meta-Plane supervision and code adaptation (CMS-04)β€”and optionally composes with daily bounded dependency & security hygiene across 1–2 clean repositories (CMS-10), periodic container/observability stack maintenance (CMS-05), host transcript backups (CMS-01), CLI wrapper healing (CMS-03), daily Governance-Plane rules/SSoT alignment (CMS-06), daily sidecar/automation meta-auditing (CMS-09), weekly Sunday morning repository map maintenance (CMS-08), and weekly Sunday skill version/upstream verification & adversarial auditing (CMS-07), coordinated via cooperative repository lease locks:

sequenceDiagram
    autonumber
    participant Day as β˜€οΈ Daytime Agent Sessions
    participant Hook as πŸͺ SessionStart / PostToolUse Hooks
    participant DB as πŸ—„οΈ SQLite + Vector Index
    participant Logs as πŸ“‹ logs/agent-issues.jsonl
    participant NREM as πŸŒ™ CMS-02: NREM Consolidation (02:00 AM)
    participant REM as 🧠 CMS-04: REM Supervisor (04:45 AM)

    Hook->>Day: Inject workspace_id + project_number at startup
    Day->>DB: Create entries, commits, anchors, & session summaries
    Hook->>Logs: Capture redacted MCP validation / tool friction
    Note over NREM,DB: 02:00 AM β€” Data-Plane + Closed-Loop Self-Improvement
    NREM->>DB: 1. Pre-flight backup & retain 15 newest snapshots
    NREM->>DB: 2. Migrate unassigned / default workspace entries
    NREM->>DB: 3. Verify Git/GitHub ground truth & mark stale code anchors
    NREM->>DB: 4. Episodic-to-semantic compaction (>10 fragments >14d old)
    NREM->>DB: 5. Link orphans, merge synonym tags, & auto-prune noise
    NREM->>DB: 6. Sync vectors, run optimizeDatabase (integrity/FTS5/WAL/VACUUM) & log CMS-02
    NREM->>Logs: Apply self-improvements (conditional gate) or log blockers for CMS-04
    Note over REM,Logs: 04:45 AM β€” Meta-Plane + Closed-Loop / Targeted Gate
    REM->>DB: 1. Audit CMS-02 soft-deletions & auto-restore high-value entries
    REM->>DB: 2. Verify 0 unassigned entries & vector index parity
    REM->>Logs: 3. Mine agent-issues.jsonl, audit logs, & session blockers
    REM->>REM: 4. Apply batched schema / healer / prompt adaptations
    REM->>REM: 5. Targeted Gate (docs skip tests; code runs targeted eslint/vitest/playwright)
    REM->>DB: 6. Commit explicit fixes, clear resolved logs, & log CMS-04 milestone
Loading

Why Separate CMS-02 and CMS-04?

Dimension CMS-02: NREM Memory Consolidation CMS-04: REM Meta-Cognitive Supervisor
Schedule Nightly at 02:00 AM local time Nightly at 04:45 AM local time
Plane Data-Plane + Closed-Loop Self-Improvement (SQLite + sqlite-vec curation + proactive prompt/code/doc fixes) Meta-Plane + Closed-Loop Self-Improvement (Safety audit/rollback + proactive code/prompt/automation/doc adaptation)
Build / Test Policy Conditional Code-vs-Docs Gate β€” Zero-Build on data-only or docs-only runs; runs targeted eslint, typecheck, targeted vitest, and conditional build + targeted playwright only when applying observed code/prompt/instruction improvements (logs unresolvable blockers for CMS-04) Targeted Code-vs-Docs Single-Pass Gate β€” Skips builds/tests on clean or docs-only trees; runs targeted eslint, typecheck, targeted vitest, and conditional build + targeted playwright only when src//instructions change (never full sweeps)
Recommended Model Fast / cost-efficient tier (e.g., flash, haiku, gpt-4o-mini) Reasoning / coding tier (e.g., pro, sonnet, o3 / gpt-5)
Native MCP Prompt /mcp:memory-journal-mcp:optimize-journal /mcp:memory-journal-mcp:cms-rem-supervisor
Audit Trail Tag cms-02-nrem-consolidation, database-optimizer cms-04-rem-supervisor, meta-learning

Note

Optional Host Extensions (CMS-01, CMS-03, CMS-05, CMS-06, CMS-07, CMS-08, CMS-09 & CMS-10) & Cooperative Repository Locks: Multi-repository agent workspaces can bracket the core MCP automations with staggered host stages enforced with >= 60-minute separations (>= 75m among heavy overnight stages, hourly morning cadence from 06:00 AM to 09:00 AM), and cooperative per-repository lease locks with stale-heartbeat reclamation: CMS-05 (1st & 15th at 11:30 PM, Infra-Plane) for pruning container engine build/image/volume bloat, aligning safe patch/minor observability image tags, and verifying multi-stack health ahead of the nightly cycle, CMS-01 (01:00 AM, IO-Plane) for backing up IDE conversation transcripts/indexes prior to database consolidation, CMS-03 (03:15 AM, Code-Plane) for healing local CLI execution wrappers and hooks, CMS-06 (06:00 AM, Governance-Plane) for daily rules, hooks, profiles, permissions, and SSoT documentation alignment, CMS-09 (07:00 AM, Meta-Governance) for daily static & empirical sidecar schedule/collision/redundancy auditing, CMS-08 (Sundays 08:00 AM, Structure-Plane) for weekly curation of static AGENT_README.md REPO_TREE labels (fallback & label source for live memory://repo-map/{+repo}) and code-map.md drift checks on clean unlocked trees, CMS-07 (Sundays 09:00 AM, Knowledge-Plane) for upstream/version-triggered, protocol-spec, and server-repo skill upgrades (with customization diff-preservation, prompt-wrapper parity checks, and /mcp:memory-journal-mcp:adversarial-audit-skill verification), and CMS-10 (10:00 PM, Security-Plane) for daily bounded (1–2 clean repositories/run) dependency lockfile bumps, safe CVE overrides, Dockerfile Scout/Trivy scans, GitHub Actions SHA pinning, and conditional local CodeQL SAST with fail-closed rollback and deferred-update reporting. All automations operate as closed-loop, self-improving agents that refine their own prompts, scripts, skills, and repo-scoped documentation whenever operational friction or drift is observed: CMS-02 and CMS-04 maintain Memory Journal docs (AGENT_README.md, README.md, DOCKER_README.md, SECURITY.md, bundled skills/, src/constants/instructions/markdown/, test-server/*.md, and affected wiki pages including Automations.md), while host stages maintain host repo, skill, governance, sidecar, dependency, and container infrastructure docs.


2. CMS-02: NREM Memory Consolidation & Graph Defrag

Sidecar ID: optimize-journal-database
Display Name: CMS-02: NREM Memory Consolidation & Graph Defrag
Default Schedule: CRON_TZ=America/New_York 0 2 * * * (Daily at 02:00 AM ET)

Execution Phases

  1. Phase 1 β€” Safety Backup, Retention & Full-History Unassigned Scan (Option A):
    • Reads memory://health first to check teamDatabase.configured. Creates a timestamped backup via mj.backup.backupJournal({}) (aborts immediately if the backup fails), retains the 15 most recent regular backups via mj.backup.cleanupBackups({ keep_count: 15 }) (without counting pre-prune-* snapshots against keep_count), and when teamDatabase.configured is true also runs mj.team.teamBackup({}).
    • Scans the entire Personal database across all workspaces (workspace_id: '*' with readonly: true on top-level mj_execute_code read scans; mutating/admin calls pass a concrete top-level workspace_id + project_number and pass inner workspace_id: '*' only on cross-workspace admin calls; paginating with cursor: res.next_cursor until !res.hasMore β€” never passing raw numeric string offsets as cursor, and passing include_archived: true when verifying archived history) plus Team DB across registered (workspace_id, project_number) pairs (const { projects } = await mj.admin.listProjects({}); then mj.team.teamGetRecent({ workspace_id, project_number, limit: 200 }) per project β€” never passing workspace_id: '*' to teamGetRecent, teamGetStatistics, teamListTags, or teamGetEntryById or probing sequential entry IDs across workspaces, as wildcard cross-tenant reads are blocked by multi-tenant isolation) to detect entries with workspaceId === 'default', missing/stale projectNumber, or misattributed projects, migrating Personal entries inside a concrete source-scoped mj_execute_code call (or direct update_entry) via mj.admin.updateEntry({ entry_id: id, workspace_id: '*', target_workspace_id: correctWorkspace }) (omitting project_number when correctWorkspace is registered so projectRegistry resolves the destination project_number without triggering source-project ownership rejection) and Team entries via mj.team.teamUpdateEntry({ entry_id: id, workspace_id: correctWorkspace, project_number: correctProject }).
  2. Phase 2 β€” Ground-Truth Verification, Staleness Sweep & 7-Dimension Audit (Option B):
    • Cross-checks recent session-summary, bug_fix, project_decision, and planning entries against Git commit history (mj.git.getCommitHistory) and GitHub issues/PRs (mj.github.getGithubIssues, mj.github.getGithubPrs).
    • Runs mj.git.checkEntryStaleness across anchored workspaces (check_entry_staleness skips already-invalidated anchors by default unless include_invalidated: true, and check_entry_staleness, update_entry, and team_update_entry are excluded from automatic top-level mj_execute_code session_id injection unless explicitly passed in inner args; omitting top-level session_id on that call remains harmless defensive hygiene; checkEntryStaleness persists refreshed anchor statuses directly, reserving mj.core.markAnchorsStale for explicit manual overrides; on repositories with high anchor counts, batch by entry_id to stay within the 30s worker timeout).
    • Calibrates missing significance_type, trust_score, impact_score, validation_status, technical subsystem tags, autoContext lineage, and knowledge graph relationships in single-batch concrete-workspace mj_execute_code calls of at most 30 entries (mj.admin.batchUpdateEntries, passing auto_index: false on metadata-only or archive-only batches where content is unchanged so updates stay well within the 30s worker timeout).
  3. Phase 3 β€” Multi-Agent Domain Audit, Episodic-to-Semantic Compaction, Graph Defrag & Team Parity (Option C):
    • Episodic-to-Semantic Compaction: Identifies dense clusters (>10 non-commit, non-summary entries older than 14 days for the same feature, audit campaign, or recurring log stream β€” including test_entry, development_note, bug_fix, technical_note, project_decision, feature_implementation, other, personal_reflection, non-summary retrospective, or daily maintenance logs, while preserving keep-tagged entries unarchived), synthesizes a single retrospective or project_decision entry (significance_type: 'architecture' or 'milestone', trust_score: 0.95, tagged semantic-summary β€” never session-summary), links it via evolves_from (note: createEntry relationships resolves target IDs strictly within the same database), and archives the raw fragments (is_archived: true, auto_index: false).
    • Orphan, Taxonomy, Physical SQLite & Team DB Defrag: Links genuine orphan entries via mj.relationships.linkEntries (always passing a concrete workspace_id and project_number β€” never workspace_id: '*', which is rejected on write tools; leaving ephemeral auto-prune breadcrumbs unlinked), merges duplicate/synonymous tags (mj.admin.mergeTags), soft-deletes zero-value transient noise (mj.admin.deleteEntry), runs mj.admin.runAutoPrune({ workspace_id: '*', target }) (enforcing configured --prune-older-than-days, --prune-importance-threshold, --prune-exclude-tags), rebuilds Personal/Team vector indexes (mj.admin.rebuildVectorIndex, mj.team.teamRebuildVectorIndex) if drifted, checks Team DB links/tags when teamDatabase.configured is true, and finishes with mj.admin.optimizeDatabase({ target: 'both', vacuum: 'auto' }) for PRAGMA integrity_check, PRAGMA foreign_key_check, dead-tag pruning, stale vector cleanup, FTS5 compaction, PRAGMA optimize, wal_checkpoint(TRUNCATE), and conditional VACUUM.
  4. Phase 4 β€” Maintenance Entry & Streamlined 5-Part Report:
    • Records a maintenance milestone entry tagged ['cms', 'cms-02-nrem-consolidation', 'database-optimizer', 'maintenance'] linked via evolves_from to the prior CMS-02 run.
    • Outputs a non-redundant 5-part report: Part 1 surfaces SQLite Physical Maintenance (mj.admin.optimizeDatabase({ target: 'both', vacuum: 'auto' }) Personal + Team integrity_check, foreign_key_check, dead tags pruned, stale vectors cleaned, FTS5/PRAGMA optimize, WAL truncate status, VACUUM executed or skipped reason, and DB size before/after), Part 4 summarizes Executed Consolidation Phases (All Enabled by Default), Part 5 reports Closed-Loop Self-Improvement & CMS-04 Handoff, and the Reference Parameters Addendum is omitted in unattended full / autoRun runs (retained only on interactive quick / targeted runs, where Part 4 labels Options A & B as Enabled by Default and Part 5 presents Option C On Request).

3. CMS-04: REM Meta-Cognitive Supervisor & Self-Healing

Sidecar ID: heal-memory-journal-mcp
Display Name: CMS-04: REM Meta-Cognitive Supervisor & Self-Healing
Default Schedule: CRON_TZ=America/New_York 45 4 * * * (Daily at 04:45 AM ET)

Execution Phases

  1. Pre-Flight Baseline & Concurrent-Agent Isolation:
    • Captures baseline uncommitted files (Code Mode mj.git.getCommitHistory({ uncommitted: true }), or git status --porcelain in standalone hosts) and checks for active vitest, playwright, or tsc processes before editing so concurrent WIP from another session is never overwritten or staged.
  2. Phase A β€” Post-NREM Supervisor Audit & Safety Rollback:
    • Inspects the latest CMS-02 maintenance report, recent soft-deletions (mj.search.listDeletedEntries({ limit: 50, workspace_id: '*' })), and audit log mutations (mj.admin.searchAuditLog({ limit: 100 })).
    • Automatic Safety Rollback: Immediately restores (mj.admin.restoreEntry) any soft-deleted entry from the last 24 hours that has significanceType !== null, impactScore >= 0.5, or active relationships.
    • Confirms 0 unassigned entries remain across workspace_id: '*' and verifies mj.search.getVectorIndexStats({}) parity.
  3. Phase B β€” Cross-Run Experience, Telemetry Mining & Closed-Loop Self-Improvement:
    • Inspects logs/agent-issues.jsonlβ€”populated automatically by the server's built-in issue logger (disabled in Vitest and Playwright runs via DISABLE_ISSUE_LOGGING=true), client PostToolUse / afterMCPExecution hooks, and manual agent telemetryβ€”plus logs/mcp-audit.jsonl (when --audit-log / AUDIT_LOG_PATH is configured), the Root-Cause Investigation section of the latest CMS-02 entry, and recent session-summary ## Unfinished / Blocked sections.
    • Proactively implements any deterministic bug fixes, workflow/prompt/tool/schema/instruction optimizations, or automation/doc improvements noticed during the run (in addition to logged telemetry issues), formulating adaptations across the 6 Architectural Healing Layers:
      1. Schema & Instruction Hardening (.describe() hints, src/constants/instructions/markdown/*.md compiled via pnpm run generate:instructions)
      2. Dispatcher Healing (param-normalizer.ts, hallucination-healer.ts)
      3. Sandbox Proxy Interceptors (worker-api-proxy.ts, worker-result-proxy.ts, namespace-shims.ts)
      4. Alias Management (METHOD_ALIASES in src/codemode/constants/method-aliases.ts, re-exported via src/codemode/api-constants.ts)
      5. CLI Guardrails & Help Injection
      6. Environment & Workflow Guardrails (client AGENTS.md, hooks.json, shipped skills)
  4. Phase C β€” Batched Self-Adaptation & Targeted Single-Pass Validation Gate:
    • Applies all adaptations in a single batch without touching baseline WIP files, then diffs working tree state against the Pre-Flight Baseline.
    • Case 1 β€” Zero Changes by This Run: Skips lint, typecheck, build, vitest, and playwright completely to save CPU and memory when no source or documentation files changed.
    • Case 2 β€” Docs-Only Changes: Skips build/vitest/playwright and commits explicit paths with --validation none.
    • Case 3 β€” Code, Test, or Instruction Changes: Runs sequentially targeted pnpm exec eslint <modified-files> β†’ pnpm run typecheck β†’ targeted pnpm exec vitest run <affected-test-files>, and ONLY when runtime src/ or markdown instructions changed runs pnpm run build β†’ PLAYWRIGHT_WORKERS=1 pnpm exec playwright test <affected-e2e-specs> (never full vitest/playwright sweeps, pnpm run test:e2e, or update-badges.ts inside scheduled sidecars; full suites stay in interactive audits, prepublishOnly, and CI), then commits explicit modified paths only (--add <paths>, never --add .).
  5. Phase D β€” Clear Issue Logs & Log REM Supervisor Entry:
    • Purges resolved entries from logs/agent-issues.jsonl and creates a maintenance milestone entry tagged ['cms', 'cms-04-rem-supervisor', 'meta-learning', 'maintenance'], linked via evolves_from to the prior CMS-04 entry and references to today's CMS-02 entry (both within your configured project).

4. Cross-Client Setup & Portability Guide

Because both automations are backed by first-class MCP prompts built directly into memory-journal-mcp (optimize-journal and cms-rem-supervisor), they require little to no adjustment to run in Cursor, Claude Code, Windsurf, Cline, or Google Antigravity.

Option A: One-Command Native MCP Prompt Invocation (Cursor, Claude Desktop, Windsurf, Antigravity)

In any MCP client that supports slash prompts, you can trigger the exact same autonomous workflows on demand or from a lightweight scheduled wrapper without copying long prompt strings:

  • Run CMS-02 (Full Unattended NREM Consolidation):
    /mcp:memory-journal-mcp:optimize-journal mode="full" autoRun="true" limit="0"
    
  • Run CMS-04 (REM Supervisor & Safety Audit):
    /mcp:memory-journal-mcp:cms-rem-supervisor lookbackHours="24" autoRestore="true"
    

Note

In Cursor, type /optimize-journal or /cms-rem-supervisor directly in the chat input box. Cursor will prompt you for the optional arguments or use the defaults.


Option B: Google Antigravity (hooks.json & sidecar.json)

In Google Antigravity, real-time session hooks live in ~/.gemini/config/hooks.json and scheduled automations live in ~/.gemini/config/sidecars/<sidecar-id>/sidecar.json (spawning a fresh background conversation via agentapi new-conversation on each cron trigger).

1. ~/.gemini/config/hooks.json & hooks/agy-lifecycle-hook.mjs (Session Orientation, PreToolUse Gates & Issue Logger)

Replace <PATH_TO_LIFECYCLE_HOOK> with ~/.gemini/config/hooks/agy-lifecycle-hook.mjs and <PATH_TO_MEMORY_JOURNAL_MCP> with your local checkout path. On Windows, prefer invoking a thin run-hook.cmd wrapper (cmd /c / absolute Node path) instead of bare node when stdin JSON piping is involved so PowerShell pipe encoding/BOM quirks cannot truncate payloads.

~/.gemini/config/hooks.json:

{
  "session-context-anchor": {
    "enabled": true,
    "SessionStart": [
      {
        "type": "command",
        "command": "node \"<PATH_TO_LIFECYCLE_HOOK>\"",
        "timeout": 15
      }
    ]
  },
  "pre-tool-guard": {
    "enabled": true,
    "PreToolUse": [
      {
        "matcher": "run_command|read_resource|write_file|edit_file|call_mcp_tool|mcp_memory-journal-mcp_.*",
        "hooks": [
          {
            "type": "command",
            "command": "node \"<PATH_TO_LIFECYCLE_HOOK>\"",
            "timeout": 15
          }
        ]
      }
    ]
  },
  "mj-mcp-issue-logger": {
    "enabled": true,
    "PostToolUse": [
      {
        "matcher": "call_mcp_tool|mcp_memory-journal-mcp_.*",
        "hooks": [
          {
            "type": "command",
            "command": "node \"<PATH_TO_LIFECYCLE_HOOK>\"",
            "timeout": 15
          }
        ]
      }
    ]
  },
  "scratch-hygiene-stop": {
    "enabled": true,
    "Stop": [
      {
        "type": "command",
        "command": "node \"<PATH_TO_LIFECYCLE_HOOK>\"",
        "timeout": 15
      }
    ]
  }
}

~/.gemini/config/hooks/agy-lifecycle-hook.mjs (portable cross-platform reference):

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MJ_CONFIG_PATH = path.resolve(__dirname, '..', 'memory-journal.config.json');
const MJ_ISSUES_LOG_PATH =
  process.env.MJ_ISSUES_LOG_PATH ?? '<PATH_TO_MEMORY_JOURNAL_MCP>/logs/agent-issues.jsonl';

function normalizePath(p) {
  return String(p || '')
    .replace(/^file:\/\/\/?/i, '')
    .replace(/%3a/gi, ':')
    .replace(/^\/([a-z])\//i, '$1:/')
    .replace(/\\/g, '/')
    .replace(/\/+$/, '')
    .toLowerCase();
}

function matchProjects(payload) {
  if (!fs.existsSync(MJ_CONFIG_PATH)) return [];
  let registry;
  try {
    registry = JSON.parse(fs.readFileSync(MJ_CONFIG_PATH, 'utf8'))?.projectRegistry;
  } catch {
    return [];
  }
  if (!registry || typeof registry !== 'object') return [];

  const searchPaths = [
    ...(payload.cwd ? [payload.cwd] : []),
    ...(Array.isArray(payload.workspacePaths) ? payload.workspacePaths : []),
  ]
    .map(normalizePath)
    .filter(Boolean);

  const matched = [];
  const seen = new Set();
  for (const sp of searchPaths) {
    for (const [name, info] of Object.entries(registry)) {
      if (seen.has(name) || !info?.path) continue;
      const regPath = normalizePath(info.path);
      if (regPath && (sp === regPath || sp.startsWith(`${regPath}/`))) {
        seen.add(name);
        matched.push({ name, projectNumber: info.project_number });
      }
    }
  }
  return matched;
}

function redactArgs(args) {
  if (!args || typeof args !== 'object') return undefined;
  const out = {};
  for (const [k, v] of Object.entries(args)) {
    if (/token|secret|password|key|auth/i.test(k)) out[k] = '[REDACTED]';
    else if (typeof v === 'string' && v.length > 240) out[k] = `${v.slice(0, 240)}...(truncated)`;
    else out[k] = v;
  }
  const str = JSON.stringify(out);
  return str.length > 600 ? `${str.slice(0, 600)}...(truncated)` : str;
}

function handleSessionStart(payload) {
  const convId = payload.conversationId || '';
  if (!convId) return {};
  const matched = matchProjects(payload);
  const parts = [`[Session Context Anchor] session_id: "${convId}"`];
  if (matched.length > 0) {
    parts.push(
      `primary_project: { workspace_id: "${matched[0].name}", project_number: ${matched[0].projectNumber} }`,
      `briefing_uri: "memory://briefing/${matched[0].name}"`,
      `repo_map_uri: "memory://repo-map/${matched[0].name}"`
    );
  }
  return { injectSteps: [{ systemMessage: { systemMessage: parts.join(' | ') } }] };
}

// Fold `A && B && C` into `A; if ($?) { B; if ($?) { C } }` so B only runs when A succeeded
// (same semantics as bash `&&`; a bare `;` would run B even after A fails).
function foldAndChain(cmd) {
  const segments = cmd.split(/\s+&&\s+/);
  let folded = segments.pop();
  while (segments.length > 0) folded = `${segments.pop()}; if ($?) { ${folded} }`;
  return folded;
}

function handlePreToolUse(payload) {
  const toolName = String(payload.toolCall?.name || '');
  const args = payload.toolCall?.args || {};
  if (toolName === 'read_resource' && (args.ServerName ?? args.serverName) === 'memory-journal-mcp') {
    const uriKey = args.Uri !== undefined ? 'Uri' : args.uri !== undefined ? 'uri' : null;
    const uriVal = uriKey ? String(args[uriKey] || '') : '';
    const bare = uriVal.match(/^memory:\/\/(?:journal\/)?(agent-id|agent-context|briefing|graph|repo-map)\/?([?#].*)?$/i);
    if (bare) {
      const rawKind = bare[1].toLowerCase();
      const kind = rawKind === 'agent-id' ? 'agent-context' : rawKind;
      const suffix = bare[2] ?? '';
      const matched = matchProjects(payload);
      if (matched.length === 1) {
        return { decision: 'allow', overwrite: { [uriKey]: `memory://${kind}/${matched[0].name}${suffix}` } };
      }
      return { decision: 'deny', reason: `Use repo-scoped memory://${kind}/<repo_name>${suffix}.` };
    }
  }
  if (
    toolName === 'call_mcp_tool' &&
    (args.ServerName ?? args.serverName) === 'memory-journal-mcp' &&
    (args.ToolName ?? args.toolName) === 'mj_execute_code'
  ) {
    const mcpArgs = args.Arguments ?? args.arguments ?? {};
    const ws = String(mcpArgs.workspace_id ?? mcpArgs.workspaceId ?? '').trim();
    if (!ws) return { decision: 'deny', reason: "mj_execute_code requires explicit 'workspace_id'." };
    const isReadonly = mcpArgs.readonly === true || mcpArgs.readOnly === true || mcpArgs.read_only === true;
    const codeText = String(mcpArgs.code ?? mcpArgs.script ?? '');
    if (!isReadonly && /(?:share_with_team|shareWithTeam)\s*[:=]\s*true\b/.test(codeText)) {
      return { decision: 'force_ask', reason: 'Confirm mirroring to the shared team database (share_with_team: true).' };
    }
  }
  const cmd = String(args.CommandLine || '');
  if (!cmd) return { decision: 'allow' };
  // Example deterministic policy: Windows PowerShell 5.1 has no `&&` pipeline-chain operator.
  // Naive split for illustration only β€” production hooks should tokenize quotes before folding.
  if (/\s&&\s/.test(cmd) && !/\bpowershell\b|\bpwsh\b|["']/i.test(cmd)) {
    return {
      decision: 'allow',
      overwrite: { CommandLine: foldAndChain(cmd) },
    };
  }
  return { decision: 'allow' };
}

function handlePostToolUse(payload) {
  const errorText = typeof payload.error === 'string' ? payload.error.trim() : '';
  if (!errorText) return {};
  const toolName = String(payload.toolCall?.name || '');
  const toolArgs = payload.toolCall?.args || {};
  const isMjDirect = toolName.startsWith('mcp_memory-journal-mcp_');
  const isMjLazy = toolName === 'call_mcp_tool' && toolArgs?.ServerName === 'memory-journal-mcp';
  if (!isMjDirect && !isMjLazy) return {};

  const logDir = path.dirname(MJ_ISSUES_LOG_PATH);
  if (fs.existsSync(logDir)) {
    fs.appendFileSync(
      MJ_ISSUES_LOG_PATH,
      `${JSON.stringify({
        timestamp: new Date().toISOString(),
        source: 'agy-post-tool-hook',
        sessionId: payload.conversationId ?? null,
        cwd: payload.cwd ?? null,
        tool: isMjLazy ? String(toolArgs?.ToolName || toolName) : toolName,
        error: errorText.slice(0, 1000),
        argsPreview: redactArgs(isMjLazy ? toolArgs?.Arguments : toolArgs),
      })}\n`,
      'utf8'
    );
  }
  return {};
}

function handleStop(payload) {
  if (payload?.continuationActive === true || (payload?.terminationReason && payload.terminationReason !== 'NO_TOOL_CALL')) {
    return {};
  }
  return {};
}

let rawInput = '';
for await (const chunk of process.stdin) rawInput += chunk;
const cleaned = rawInput.replace(/^\uFEFF/, '').trim();
const payload = cleaned ? JSON.parse(cleaned) : {};
const out =
  payload?.hookEventName === 'SessionStart'
    ? handleSessionStart(payload)
    : payload?.hookEventName === 'PreToolUse'
      ? handlePreToolUse(payload)
      : payload?.hookEventName === 'PostToolUse'
        ? handlePostToolUse(payload)
        : payload?.hookEventName === 'Stop'
          ? handleStop(payload)
          : {};
process.stdout.write(`${JSON.stringify(out)}\n`);
2. ~/.gemini/config/sidecars/optimize-journal-database/sidecar.json (CMS-02)

Replace America/New_York and <PATH_TO_MEMORY_JOURNAL_MCP> with your environment values, and select your preferred fast/data-plane model tier directly in the Antigravity Scheduled Tasks UI dropdown.

{
  "builtin": "schedule",
  "restart_policy": "always",
  "display_name": "CMS-02: NREM Memory Consolidation & Graph Defrag",
  "description": "Nightly 02:00 AM unattended maximum-depth NREM consolidation across all projects and all time: safety backup, unassigned migration, ground-truth & staleness verification, episodic-to-semantic compaction, tag/graph defrag, noise pruning, vector index parity, and physical SQLite optimization (optimizeDatabase) (Data-Plane + Closed-Loop Conditional Gate).",
  "args": [
    "CRON_TZ=America/New_York 0 2 * * *",
    "agentapi",
    "new-conversation",
    "--",
    "You are an autonomous agent executing a scheduled background task in the **Cognitive Management System (CMS)**. Before starting this task, use the `read_resource` tool from the `memory-journal-mcp` server to read the URI `memory://briefing/memory-journal-mcp` to load the project briefing. Set working directory to `<PATH_TO_MEMORY_JOURNAL_MCP>`. Make the title of this thread \"[CMS-02] NREM Memory Consolidation and Graph Defrag\". CRITICAL AUTONOMOUS EXECUTION OVERRIDE (NON-INTERACTIVE MAX-DEPTH MODE): (1) NEVER STOP FOR CONFIRMATION OR APPROVAL: You are running unattended at 02:00 AM. Ignore any interactive handover prompts. Do NOT ask the user if they want further optimization, which option to run, or how thorough it should be. (2) MAXIMUM DEPTH ACROSS ALL PROJECTS AND ALL TIME: Automatically execute ALL optimization tiers sequentially in a single continuous run (`mode: 'full'`, `autoRun: true`, `limit: 0`, `workspace_id: '*'`) across ALL registered projects and ALL historical entries (paginate with `cursor` until `hasMore === false`). (3) RESOURCE AND VALIDATION POLICY (Closed-Loop Conditional Code-vs-Docs Gate): Run data-only or docs-only optimizations without triggering builds/tests (use `--validation none` on doc-only edits). Proactively implement any deterministic code, schema, prompt, instruction, doc, or sidecar improvements noticed during the run on clean unlocked repos; ONLY when `src/`, tests, or instructions change, run targeted `eslint`, `typecheck`, targeted `vitest` (plus `build` and targeted `playwright` specs when runtime `src/` or instructions change β€” never full suites). Log unresolvable runtime bugs to `<PATH_TO_MEMORY_JOURNAL_MCP>/logs/agent-issues.jsonl` for `CMS-04` to triage at 04:45 AM. (4) SELF-IMPROVING DOC MAINTENANCE: Update connected documentation (`AGENT_README.md`, global `AGENTS.md`, this scheduled automation prompt, and `Automations.md`) explicitly if consolidation rules evolve. Execution Protocol (Execute All Phases Without Stopping): Phase 1 (Safety Backup, Retention and Full-History Unassigned Scan - Option A): Read `memory://health` to check whether `teamDatabase.configured` is true. Call `mj_execute_code` to create a timestamped backup via `await mj.backup.backupJournal({})` (abort if backup fails), prune old backups keeping the 15 most recent via `await mj.backup.cleanupBackups({ keep_count: 15 })`, and when `teamDatabase.configured` is true also run `await mj.team.teamBackup({})`. Run a full-database cursor scan across all entries and all time (`workspace_id: '*'`, paginating with `limit: 100, cursor: res.next_cursor` until `!res.hasMore` and passing `include_archived: true` when verifying archived historyβ€”do NOT stop at 500 entries) plus per-project Team DB checks (`mj.admin.listProjects({})` then `mj.team.teamGetRecent({ workspace_id, project_number, limit: 200 })`, never `'*'`) to detect any entries with `workspaceId === 'default'`, missing/zero/negative `projectNumber`, or misattributed projects. Auto-migrate misallocated entries immediately via `mj.admin.updateEntry` (or `mj.team.teamUpdateEntry`; use concrete `workspace_id` and omit `project_number` for registered targets so destination `project_number` resolves cleanly) and document root causes. Phase 2 (Ground-Truth Verification, Staleness Sweep and 7-Dimension Audit - Option B): Cross-check recent `session-summary`, `bug_fix`, `project_decision`, and `planning` entries against Git commit history (`mj.git.getCommitHistory`) and GitHub issues/PRs (`mj.github.getGithubIssues`, `mj.github.getGithubPrs`). If an entry claims an open blocker or status that was subsequently resolved in Git/GitHub, link the resolving entry via `mj.relationships.linkEntries` (always passing concrete `workspace_id` and `project_number`, never `'*'`; `createEntry` `relationships` also resolves target IDs strictly within the same database) or update `validation_status`. Check anchored entries via `mj.git.checkEntryStaleness` (batching by `entry_id` on busy repositories) and mark stale anchors via `mj.core.markAnchorsStale` where explicit overrides are needed. Across all projects and all historical entries, identify entries lacking `significance_type`, calibrated `trust_score` / `impact_score`, `validation_status`, technical subsystem `tags`, `autoContext` git lineage, or knowledge graph `relationships`. Calibrate metadata in safe batches (max 30 per `mj_execute_code` call via `mj.admin.batchUpdateEntries`, passing `auto_index: false` on metadata-only or archive-only batches). Phase 3 (Multi-Agent Domain Audit, Episodic-to-Semantic Compaction, Graph Defrag and Team Parity - Option C Mandatory): Partition projects with audit backlogs or unlinked/uncalibrated cohorts by Project Workspace Domain. Spawn parallel `self` subagents (`invoke_subagent` with `Model: 'inherit'`) when multi-project backlogs exist, or process directly via `mj_execute_code` batches when cohort size is compact. Identify dense clusters (>10 non-commit, non-summary entries older than 14 days for the same feature, audit campaign, or recurring log stream β€” including `test_entry`, `development_note`, `bug_fix`, `technical_note`, `project_decision`, `feature_implementation`, `other`, `personal_reflection`, non-summary `retrospective`, or daily maintenance logs, while keeping `keep`-tagged entries unarchived). Synthesize a single high-signal `retrospective` or `project_decision` semantic summary entry (`significance_type: 'architecture'` or `'milestone'`, `trust_score: 0.95`, `tags: ['semantic-summary', ...]`, never `'session-summary'`), link it via `evolves_from` to the raw fragments, and archive the raw fragments (`mj.admin.batchUpdateEntries` with `is_archived: true` and `auto_index: false` in batches of at most 30) so active context stays crisp while preserving full history. Link all genuine orphan entries (`mj.relationships.linkEntries`) using canonical relationship types (`evolves_from`, `references`, `implements`, `clarifies`, `response_to`, `blocked_by`, `resolved`, `caused`) always passing concrete `workspace_id` and `project_number` (never `'*'`), while leaving ephemeral auto-prune breadcrumbs unlinked. Consolidate duplicate/synonymous tags across the global tag taxonomy via `mj.admin.mergeTags`. Soft-delete zero-value transient debug/test noise (`significanceType === null`, low importance) via `mj.admin.deleteEntry` and run `mj.admin.runAutoPrune({ workspace_id: '*', target: teamDatabase.configured ? 'both' : 'personal' })` to enforce data lifecycle hygiene (5-day soft-delete, 5-day hard-delete). Check `mj.search.getVectorIndexStats({})`; if vector index count drifts from total entry count, run `mj.admin.rebuildVectorIndex({ workspace_id: '*' })`. When `teamDatabase.configured` is true, also link unlinked team entries via `mj.team.teamLinkEntries`, merge duplicate team tags via `mj.team.teamMergeTags` if needed, and verify `mj.team.teamGetVectorIndexStats({})` (`mj.team.teamRebuildVectorIndex({ workspace_id: '*' })` on drift). Finally, run `mj.admin.optimizeDatabase({ target: teamDatabase.configured ? 'both' : 'personal', vacuum: 'auto' })` for SQLite integrity/foreign-key checks, dead-tag pruning, FTS5 compaction, query planner stats, WAL checkpointing, and conditional VACUUM. Phase 4 (Log Maintenance Entry and Output 5-Part Report): Log the completed run in `memory-journal-mcp` using `mj.core.createEntry` with `entry_type: 'maintenance'`, `significance_type: 'milestone'`, `tags: ['cms', 'cms-02-nrem-consolidation', 'database-optimizer', 'maintenance']`, `trust_score: 1.0`, `impact_score: 0.6`, `validation_status: 'passed'`, and link it (`evolves_from`) to the previous `database-optimizer` / `cms-02-nrem-consolidation` entry. Output the mandatory 5-Part Markdown Report (including SQLite Physical Maintenance in Part 1, Executed Consolidation Phases in Part 4, and Closed-Loop Self-Improvement and CMS-04 Handoff in Part 5; omit the Reference Parameters Addendum) and finish the turn cleanly without asking any follow-up questions."
  ]
}
3. ~/.gemini/config/sidecars/heal-memory-journal-mcp/sidecar.json (CMS-04)
{
  "builtin": "schedule",
  "restart_policy": "always",
  "display_name": "CMS-04: REM Meta-Cognitive Supervisor & Self-Healing",
  "description": "Nightly 04:45 AM REM supervisor audit of nightly consolidation, cross-run telemetry & experience mining, self-healing code/prompt adaptation, and Targeted Code-vs-Docs Single-Pass Validation Gate (Meta-Plane).",
  "args": [
    "CRON_TZ=America/New_York 45 4 * * *",
    "agentapi",
    "new-conversation",
    "--",
    "You are an autonomous agent executing a scheduled background task in the **Cognitive Management System (CMS)**. Before starting this task, use the `read_resource` tool from the `memory-journal-mcp` server to read the URI `memory://briefing/memory-journal-mcp` to load the project briefing. Set working directory to `<PATH_TO_MEMORY_JOURNAL_MCP>`. Make the title of this thread \"[CMS-04] REM Meta-Cognitive Supervisor and Self-Healing\". Execution Protocol (Execute All Phases Without Stopping): Pre-Flight Baseline and Concurrent-Agent Isolation: Acquire cooperative repository locks where supported, capture baseline uncommitted files in `memory-journal-mcp` and active `vitest`/`playwright`/`tsc` processes before editing; NEVER overwrite files already dirtied in that baseline by another active session. Phase A (Post-NREM Supervisor Audit - cms-rem-supervisor): Audit the execution and mutations of `CMS-02` (NREM Consolidation) from the last 24 hours. Call `mj_execute_code` to inspect: (1) The latest `CMS-02` maintenance entry (`tags: ['cms-02-nrem-consolidation']` or `['database-optimizer']`). (2) All entries soft-deleted in the last 24 hours via `await mj.search.listDeletedEntries({ limit: 50, workspace_id: '*' })` and recent mutations via `await mj.admin.searchAuditLog({ limit: 100 })`. (3) Safety Rollback Check: Verify that `CMS-02` did NOT soft-delete any entry with `significanceType !== null`, `impactScore` of 0.5 or higher, or active relationships. If any high-value entry was erroneously soft-deleted, immediately restore it via `await mj.admin.restoreEntry({ entry_id, workspace_id: '*' })` and record the false-positive pattern. (4) Parity and Hygiene Check: Confirm 0 unassigned entries remain across `workspace_id: '*'` and check `await mj.search.getVectorIndexStats({})`. Phase B (Cross-Run Experience, Telemetry Mining and Closed-Loop Self-Improvement): Examine `<PATH_TO_MEMORY_JOURNAL_MCP>/logs/agent-issues.jsonl` and `logs/mcp-audit.jsonl` for tool failures, Zod validation errors, or parameter hallucinations. Review the Root-Cause Investigation section of the latest `CMS-02` entry and recent `session-summary` Unfinished / Blocked sections across projects. Beyond logged telemetry failures, proactively implement any deterministic bug fixes, workflow/prompt/tool/schema/instruction optimizations, or automation/doc improvements noticed during the run on clean unlocked repos (applying Prevent before Mitigate across the 6 healing layers: schemas/instructions, dispatcher normalizers, sandbox proxies, same-group `METHOD_ALIASES`, CLI guardrails, and environment/workflow docs) in `src/handlers/tools/schemas/hallucination-healer.ts` or tool input schemas, `src/handlers/prompts/optimizer.ts` / `cms-supervisor.ts`, and check/update `memory-journal-mcp` and wiki docs as needed/appropriate (`AGENT_README.md`, `README.md`, `DOCKER_README.md` under 25000 chars, `SECURITY.md`, bundled `skills/memory-journal-mcp/SKILL.md`, `src/constants/instructions/markdown/` followed by `pnpm run generate:instructions`, `test-server/code-map.md` via `pnpm run generate:code-map`, `test-server/tool-reference.md`, `test-server/prompts-reference.md`, affected `.wiki` pages including `Automations.md`, plus host `AGENTS.md` and your scheduled automation prompts). Phase C (Batched Self-Adaptation and Targeted Code-vs-Docs Single-Pass Validation Gate): Apply all code, schema, prompt, or workflow improvements in a single cohesive batch without touching baseline WIP files. Check working tree state relative to the Pre-Flight Baseline. Case 1 β€” Zero Changes by This Run: SKIP `pnpm run lint`, `pnpm run typecheck`, `pnpm run build`, `pnpm exec vitest run`, and `pnpm exec playwright test` completely! Case 2 β€” Docs-Only Changes (no `src/` or `tests/` code touched): skip builds/tests and commit with `--validation none`. Case 3 β€” Code, Test, or Instruction Changes: verify no competing `vitest`/`playwright`/`tsc` is active and execute the Targeted Single-Pass Gate strictly sequentially once: (1) targeted `pnpm exec eslint <modified-files>`, (2) `pnpm run typecheck`, (3) targeted `pnpm exec vitest run <affected-test-files>`, and (4) ONLY when runtime `src/` or instructions changed, `pnpm run build` then `PLAYWRIGHT_WORKERS=1 pnpm exec playwright test <affected-e2e-specs>` (never full `vitest`/`playwright` suites, `pnpm run test:e2e`, or `update-badges.ts`). Commit ONLY the explicit files modified by this run (never `--add .`) and release any cooperative locks. Phase D (Clear Issue Logs and Log REM Supervisor Entry): If `logs/agent-issues.jsonl` had entries and all were resolved/validated, truncate `<PATH_TO_MEMORY_JOURNAL_MCP>/logs/agent-issues.jsonl` safely via `node -e \"require('node:fs').truncateSync('logs/agent-issues.jsonl', 0)\"` (avoid PowerShell `Clear-Content`, which fails when open handles exist). Log the completed supervisor run in `memory-journal-mcp` using `mj.core.createEntry` with `entry_type: 'maintenance'`, `significance_type: 'milestone'`, `tags: ['cms', 'cms-04-rem-supervisor', 'meta-learning', 'maintenance']`, `trust_score: 1.0`, `impact_score: 0.6`, `validation_status: 'passed'`, and link it via `evolves_from` to the prior `cms-04-rem-supervisor` entry and via `references` to today's `cms-02-nrem-consolidation` entry."
  ]
}

Option C: Cursor Hooks & Custom Commands (.cursor/hooks.json & .cursor/commands/)

Cursor supports both MCP execution hooks (.cursor/hooks.json) and reusable markdown slash commands (.cursor/commands/):

  1. .cursor/hooks.json (inject workspace_id + project_number context at startup via sessionStart and capture client-side MCP errors via afterMCPExecution):

    {
      "version": 1,
      "hooks": {
        "sessionStart": [
          {
            "command": "node .cursor/hooks/mj-lifecycle.mjs session-start"
          }
        ],
        "afterMCPExecution": [
          {
            "command": "node .cursor/hooks/mj-lifecycle.mjs after-mcp"
          }
        ]
      }
    }

    (On session-start, return { "additional_context": "workspace_id: \"<repo>\", project_number: <n>" } matched from memory-journal.config.json; on after-mcp, inspect { tool_name, tool_input, result_json }, redact sensitive keys, and append MCP failures to <PATH_TO_MEMORY_JOURNAL_MCP>/logs/agent-issues.jsonl.)

  2. .cursor/commands/cms-02-nrem.md (runnable in Cursor chat or Background Agents via /cms-02-nrem):

    Execute the `memory-journal-mcp` `optimize-journal` workflow in full unattended mode (`mode: "full"`, `autoRun: "true"`, `limit: 0`, `workspace_id: "*"`).
    
    1. Read `memory://briefing/memory-journal-mcp` and `memory://health`.
    2. Use `mj_execute_code` to create a backup (`mj.backup.backupJournal({})`), retain 15 backups (`mj.backup.cleanupBackups({ keep_count: 15 })`), also run `mj.team.teamBackup({})` if `teamDatabase.configured` is true, and migrate any unassigned/`default` workspace entries across `workspace_id: '*'`.
    3. Verify recent entries against Git/GitHub ground truth, run `mj.git.checkEntryStaleness({})`, calibrate missing heuristic scores/tags, compact dense episodic clusters (>10 fragments older than 14 days) into semantic entries (`evolves_from` within same DB + `is_archived: true`), link orphans using concrete `workspace_id` + `project_number` (never `'*'`), merge duplicate tags, run `mj.admin.runAutoPrune({ workspace_id: '*', target: 'both' })`, verify vector index parity (`mj.search.getVectorIndexStats({})`), run Team DB parity checks when `teamDatabase.configured` is true, and call `mj.admin.optimizeDatabase({ target: 'both', vacuum: 'auto' })`.
    4. Skip builds/tests on data-only or docs-only runs; if applying observed code/prompt improvements, run targeted lint/typecheck/tests once and commit explicit paths only. Log the final 5-Part Markdown Report as a `maintenance` entry tagged `['cms', 'cms-02-nrem-consolidation', 'database-optimizer', 'maintenance']`.
  3. .cursor/commands/cms-04-rem.md (runnable via /cms-04-rem):

    Execute the `memory-journal-mcp` `cms-rem-supervisor` workflow (`lookbackHours: 24`, `autoRestore: true`).
    
    1. Record baseline uncommitted files and active `vitest`/`playwright`/`tsc` processes before editing so foreign WIP stays untouched.
    2. Read `memory://briefing/memory-journal-mcp`, and use `mj_execute_code` to audit the latest `CMS-02` report and recent soft-deleted entries (`mj.search.listDeletedEntries({ limit: 50, workspace_id: '*' })`), restoring any entry with `significanceType !== null`, `impactScore >= 0.5`, or active relationships.
    3. Inspect `logs/agent-issues.jsonl` and `logs/mcp-audit.jsonl` for recurring parameter hallucinations or validation errors, and beyond logged telemetry failures proactively implement deterministic bug fixes, prompt/tool/schema/instruction optimizations, or automation/doc improvements noticed during the run on clean unlocked repos.
    4. Diff working tree changes against baseline. If `0` files were modified by this run, skip all lint/test suites. For docs-only edits, commit with `--validation none`. Otherwise, sequentially run targeted `pnpm exec eslint <modified-files>`, `pnpm run typecheck`, targeted `pnpm exec vitest run <affected-tests>`, and (`build` + targeted `playwright` specs ONLY if `src/` or instructions changed; never full suites), commit ONLY explicit modified paths (`git add <explicit_files>` / `commit.ts --add <explicit_files>`), clear `logs/agent-issues.jsonl`, and log a `maintenance` entry tagged `['cms', 'cms-04-rem-supervisor', 'meta-learning', 'maintenance']`.

Option D: Headless CLI Scheduling (cron / Task Scheduler + Claude Code / Codex CLI)

If you use a CLI-based MCP client such as Claude Code (claude), you can schedule unattended nightly runs on macOS, Linux, or Windows WSL using standard crontab:

# CMS-02: Nightly 02:00 AM NREM Consolidation (Data-Plane / Fast Model)
0 2 * * * cd /path/to/memory-journal-mcp && claude --model claude-haiku-4-5 -p "Execute the memory-journal-mcp optimize-journal prompt with mode=full, autoRun=true, limit=0 across workspace_id='*' without stopping for confirmation." --allowedTools "mcp__memory-journal-mcp__*"

# CMS-04: Nightly 04:45 AM REM Supervisor (Meta-Plane)
45 4 * * * cd /path/to/memory-journal-mcp && claude -p "Execute the memory-journal-mcp cms-rem-supervisor prompt with lookbackHours=24, autoRestore=true. Skip lint/build/test gates if git status --porcelain is clean." --allowedTools "mcp__memory-journal-mcp__*,Bash,Read,Edit"

# Optional zero-token CLI maintenance (for headless hosts without IDE sidecars)
# Note: --dest is a filename stem inside the database's backups/ directory (.db is appended automatically)
15 2 * * * memory-journal-mcp admin backup --dest nightly
45 2 * * * memory-journal-mcp admin prune
0 3 * * 0 memory-journal-mcp admin vacuum

5. Portability Best Practices for Custom Automations

When adapting these automations for other machines, teams, or MCP clients, follow these four rules to avoid environment lock-in:

  1. Prefer MCP Tools & Code Mode Over Host Shell Scripts:
    • Use mj.git.getCommitHistory({}) (or mj.git.getCommitHistory({ uncommitted: true }) for working-tree state), mj.git.searchCommits({}), and mj.git.checkEntryStaleness({}) inside mj_execute_code rather than workspace-specific wrapper scripts whenever inspecting repository state.
  2. Use Portable Working-Tree Checks for the Conditional Gate:
    • If your environment does not include custom git-history wrapper scripts, replace host history checks with standard git status --porcelain to trigger the Dirty-Tree Conditional Single-Pass Validation Gate.
  3. Disable Interactive Handovers Explicitly in Scheduled Prompts:
    • Interactive MCP prompts (optimize-journal) normally pause after Option A/B to ask the human whether to proceed. Always pass mode: "full" and autoRun: "true" (or include the NEVER STOP FOR CONFIRMATION directive) in unattended cron jobs.
  4. Enforce Subagent & Process Hygiene:
    • In clients that support subagents, always instruct CMS-02 to terminate subagents upon completion and instruct CMS-04 to verify no competing vitest, playwright, or tsc process is active before running the Targeted Single-Pass Validation Gate (leaving full suites to interactive audits and CI).

6. Related Documentation

  • Maintenance & Optimization β€” Heuristic scoring formulas, importance decay math, and startup auto-pruning flags
  • Prompts Guide β€” Full argument reference for optimize-journal and cms-rem-supervisor
  • Code Mode β€” How mj_execute_code executes multi-step maintenance batches inside a hardened V8 worker sandbox
  • CLI Reference β€” Running memory-journal-mcp admin prune and memory-journal-mcp admin backup from OS schedulers

Memory Journal MCP

Tip

Value Proposition: Persistent project memory for AI agents, so decisions and history stay available across sessions.

🏠 Home


πŸš€ Getting Started


πŸ› οΈ Core Features


🧠 Knowledge Graph


πŸ™ GitHub Integration


πŸ€– AI Integration


πŸ” Enterprise & Architecture


πŸ”— External Links

Clone this wiki locally