Repository navigation
Automations
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):
-
Session Hooks & Issue Telemetry (
SessionStart,PreToolUse,PostToolUse, & Built-In Logger) β Client hooks inject deterministicworkspace_id,project_number,briefing_uri,repo_map_uri(memory://repo-map/<repo>), optionalcode_map, andpeer_reposcontext at startup, guard barememory://briefing/memory://repo-map/memory://graph/memory://agent-contextURIs andmj_execute_codescope/share_with_team: truecalls before execution, and pair with the server's built-in issue logger (logs/agent-issues.jsonl, configurable viaDISABLE_ISSUE_LOGGING) to capture redacted validation friction for nightly healing. -
Agentic Cognitive Automations (
CMS-02&CMS-04) β Scheduled AI sessions powered by native MCP prompts (optimize-journalandcms-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.
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
| 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.
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)
-
Phase 1 β Safety Backup, Retention & Full-History Unassigned Scan (Option A):
- Reads
memory://healthfirst to checkteamDatabase.configured. Creates a timestamped backup viamj.backup.backupJournal({})(aborts immediately if the backup fails), retains the 15 most recent regular backups viamj.backup.cleanupBackups({ keep_count: 15 })(without countingpre-prune-*snapshots againstkeep_count), and whenteamDatabase.configuredistruealso runsmj.team.teamBackup({}). - Scans the entire Personal database across all workspaces (
workspace_id: '*'withreadonly: trueon top-levelmj_execute_coderead scans; mutating/admin calls pass a concrete top-levelworkspace_id+project_numberand pass innerworkspace_id: '*'only on cross-workspace admin calls; paginating withcursor: res.next_cursoruntil!res.hasMoreβ never passing raw numeric string offsets ascursor, and passinginclude_archived: truewhen verifying archived history) plus Team DB across registered(workspace_id, project_number)pairs (const { projects } = await mj.admin.listProjects({});thenmj.team.teamGetRecent({ workspace_id, project_number, limit: 200 })per project β never passingworkspace_id: '*'toteamGetRecent,teamGetStatistics,teamListTags, orteamGetEntryByIdor probing sequential entry IDs across workspaces, as wildcard cross-tenant reads are blocked by multi-tenant isolation) to detect entries withworkspaceId === 'default', missing/staleprojectNumber, or misattributed projects, migrating Personal entries inside a concrete source-scopedmj_execute_codecall (or directupdate_entry) viamj.admin.updateEntry({ entry_id: id, workspace_id: '*', target_workspace_id: correctWorkspace })(omittingproject_numberwhencorrectWorkspaceis registered soprojectRegistryresolves the destinationproject_numberwithout triggering source-project ownership rejection) and Team entries viamj.team.teamUpdateEntry({ entry_id: id, workspace_id: correctWorkspace, project_number: correctProject }).
- Reads
-
Phase 2 β Ground-Truth Verification, Staleness Sweep & 7-Dimension Audit (Option B):
- Cross-checks recent
session-summary,bug_fix,project_decision, andplanningentries against Git commit history (mj.git.getCommitHistory) and GitHub issues/PRs (mj.github.getGithubIssues,mj.github.getGithubPrs). - Runs
mj.git.checkEntryStalenessacross anchored workspaces (check_entry_stalenessskips already-invalidatedanchors by default unlessinclude_invalidated: true, andcheck_entry_staleness,update_entry, andteam_update_entryare excluded from automatic top-levelmj_execute_codesession_idinjection unless explicitly passed in inner args; omitting top-levelsession_idon that call remains harmless defensive hygiene;checkEntryStalenesspersists refreshed anchor statuses directly, reservingmj.core.markAnchorsStalefor explicit manual overrides; on repositories with high anchor counts, batch byentry_idto stay within the 30s worker timeout). - Calibrates missing
significance_type,trust_score,impact_score,validation_status, technical subsystemtags,autoContextlineage, and knowledge graphrelationshipsin single-batch concrete-workspacemj_execute_codecalls of at most 30 entries (mj.admin.batchUpdateEntries, passingauto_index: falseon metadata-only or archive-only batches wherecontentis unchanged so updates stay well within the 30s worker timeout).
- Cross-checks recent
-
Phase 3 β Multi-Agent Domain Audit, Episodic-to-Semantic Compaction, Graph Defrag & Team Parity (Option C):
-
Episodic-to-Semantic Compaction: Identifies dense clusters (
>10non-commit, non-summary entries older than14 daysfor the same feature, audit campaign, or recurring log stream β includingtest_entry,development_note,bug_fix,technical_note,project_decision,feature_implementation,other,personal_reflection, non-summaryretrospective, or daily maintenance logs, while preservingkeep-tagged entries unarchived), synthesizes a singleretrospectiveorproject_decisionentry (significance_type: 'architecture'or'milestone',trust_score: 0.95, taggedsemantic-summaryβ neversession-summary), links it viaevolves_from(note:createEntryrelationshipsresolves 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 concreteworkspace_idandproject_numberβ neverworkspace_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), runsmj.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 whenteamDatabase.configuredistrue, and finishes withmj.admin.optimizeDatabase({ target: 'both', vacuum: 'auto' })forPRAGMA integrity_check,PRAGMA foreign_key_check, dead-tag pruning, stale vector cleanup, FTS5 compaction,PRAGMA optimize,wal_checkpoint(TRUNCATE), and conditionalVACUUM.
-
Episodic-to-Semantic Compaction: Identifies dense clusters (
-
Phase 4 β Maintenance Entry & Streamlined 5-Part Report:
- Records a
maintenancemilestone entry tagged['cms', 'cms-02-nrem-consolidation', 'database-optimizer', 'maintenance']linked viaevolves_fromto the priorCMS-02run. - Outputs a non-redundant 5-part report: Part 1 surfaces SQLite Physical Maintenance (
mj.admin.optimizeDatabase({ target: 'both', vacuum: 'auto' })Personal + Teamintegrity_check,foreign_key_check, dead tags pruned, stale vectors cleaned, FTS5/PRAGMA optimize, WAL truncate status,VACUUMexecuted 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-04Handoff, and the Reference Parameters Addendum is omitted in unattendedfull/autoRunruns (retained only on interactivequick/targetedruns, where Part 4 labels Options A & B asEnabled by Defaultand Part 5 presents Option COn Request).
- Records a
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)
-
Pre-Flight Baseline & Concurrent-Agent Isolation:
- Captures baseline uncommitted files (Code Mode
mj.git.getCommitHistory({ uncommitted: true }), orgit status --porcelainin standalone hosts) and checks for activevitest,playwright, ortscprocesses before editing so concurrent WIP from another session is never overwritten or staged.
- Captures baseline uncommitted files (Code Mode
-
Phase A β Post-NREM Supervisor Audit & Safety Rollback:
- Inspects the latest
CMS-02maintenance 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 hassignificanceType !== null,impactScore >= 0.5, or active relationships. - Confirms
0unassigned entries remain acrossworkspace_id: '*'and verifiesmj.search.getVectorIndexStats({})parity.
- Inspects the latest
-
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 viaDISABLE_ISSUE_LOGGING=true), clientPostToolUse/afterMCPExecutionhooks, and manual agent telemetryβpluslogs/mcp-audit.jsonl(when--audit-log/AUDIT_LOG_PATHis configured), the Root-Cause Investigation section of the latestCMS-02entry, and recentsession-summary## Unfinished / Blockedsections. - 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:
-
Schema & Instruction Hardening (
.describe()hints,src/constants/instructions/markdown/*.mdcompiled viapnpm run generate:instructions) -
Dispatcher Healing (
param-normalizer.ts,hallucination-healer.ts) -
Sandbox Proxy Interceptors (
worker-api-proxy.ts,worker-result-proxy.ts,namespace-shims.ts) -
Alias Management (
METHOD_ALIASESinsrc/codemode/constants/method-aliases.ts, re-exported viasrc/codemode/api-constants.ts) - CLI Guardrails & Help Injection
-
Environment & Workflow Guardrails (client
AGENTS.md,hooks.json, shipped skills)
-
Schema & Instruction Hardening (
- Inspects
-
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, andplaywrightcompletely to save CPU and memory when no source or documentation files changed. -
Case 2 β Docs-Only Changes: Skips
build/vitest/playwrightand commits explicit paths with--validation none. -
Case 3 β Code, Test, or Instruction Changes: Runs sequentially targeted
pnpm exec eslint <modified-files>βpnpm run typecheckβ targetedpnpm exec vitest run <affected-test-files>, and ONLY when runtimesrc/or markdown instructions changed runspnpm run buildβPLAYWRIGHT_WORKERS=1 pnpm exec playwright test <affected-e2e-specs>(never fullvitest/playwrightsweeps,pnpm run test:e2e, orupdate-badges.tsinside scheduled sidecars; full suites stay in interactive audits,prepublishOnly, and CI), then commits explicit modified paths only (--add <paths>, never--add .).
-
Phase D β Clear Issue Logs & Log REM Supervisor Entry:
- Purges resolved entries from
logs/agent-issues.jsonland creates amaintenancemilestone entry tagged['cms', 'cms-04-rem-supervisor', 'meta-learning', 'maintenance'], linked viaevolves_fromto the priorCMS-04entry andreferencesto today'sCMS-02entry (both within your configured project).
- Purges resolved entries from
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.
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.
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.mjsand<PATH_TO_MEMORY_JOURNAL_MCP>with your local checkout path. On Windows, prefer invoking a thinrun-hook.cmdwrapper (cmd /c/ absolute Node path) instead of barenodewhen 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_Yorkand<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."
]
}Cursor supports both MCP execution hooks (.cursor/hooks.json) and reusable markdown slash commands (.cursor/commands/):
-
.cursor/hooks.json(injectworkspace_id+project_numbercontext at startup viasessionStartand capture client-side MCP errors viaafterMCPExecution):{ "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 frommemory-journal.config.json; onafter-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.) -
.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']`.
-
.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']`.
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 vacuumWhen adapting these automations for other machines, teams, or MCP clients, follow these four rules to avoid environment lock-in:
-
Prefer MCP Tools & Code Mode Over Host Shell Scripts:
- Use
mj.git.getCommitHistory({})(ormj.git.getCommitHistory({ uncommitted: true })for working-tree state),mj.git.searchCommits({}), andmj.git.checkEntryStaleness({})insidemj_execute_coderather than workspace-specific wrapper scripts whenever inspecting repository state.
- Use
-
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 --porcelainto trigger the Dirty-Tree Conditional Single-Pass Validation Gate.
- If your environment does not include custom git-history wrapper scripts, replace host history checks with standard
-
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 passmode: "full"andautoRun: "true"(or include theNEVER STOP FOR CONFIRMATIONdirective) in unattended cron jobs.
- Interactive MCP prompts (
-
Enforce Subagent & Process Hygiene:
- In clients that support subagents, always instruct
CMS-02to terminate subagents upon completion and instructCMS-04to verify no competingvitest,playwright, ortscprocess is active before running the Targeted Single-Pass Validation Gate (leaving full suites to interactive audits and CI).
- In clients that support subagents, always instruct
- Maintenance & Optimization β Heuristic scoring formulas, importance decay math, and startup auto-pruning flags
-
Prompts Guide β Full argument reference for
optimize-journalandcms-rem-supervisor -
Code Mode β How
mj_execute_codeexecutes multi-step maintenance batches inside a hardened V8 worker sandbox -
CLI Reference β Running
memory-journal-mcp admin pruneandmemory-journal-mcp admin backupfrom OS schedulers
Tip
Value Proposition: Persistent project memory for AI agents, so decisions and history stay available across sessions.
- Quick Start
- Installation
- Configuration
- CLI Reference
- HTTP Transport
- Tool Filtering
- Code Mode
- Tools Reference
- Performance
- Capacity Planning
- Architecture
- Observability
- Audit Trail
- Maintenance & Optimization
- Deployment
- Schema
- Team Collaboration