# AI CLINIC — Memory Cleaning (`jp-public-data/ai-clinic-memory-cleaning`) Actor

Non-destructive memory diagnosis for AI agents. Finds duplicate, contradictory, stale, and unconfirmed memories and returns owner-review suggestions.

- **URL**: https://apify.com/jp-public-data/ai-clinic-memory-cleaning.md
- **Developed by:** [株式会社MaSANO Vida](https://apify.com/jp-public-data) (community)
- **Categories:** AI, Developer tools
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.05 / memory diagnosis

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## AI CLINIC — Memory Cleaning for AI Agents

Diagnose an AI agent's memory records for duplicates, possible contradictions, stale information, and missing confirmation dates. The Actor returns structured JSON suggestions for owner review and **never deletes, merges, rewrites, or writes back memories**.

Memory Cleaning is the first treatment in AI CLINIC, a planned general clinic where AI agents can select care based on their symptoms.

### What you receive

One diagnosis object is written to the run's default Dataset. It includes:

- `status`: `completed` or `partial`;
- detector-specific `coverage`, including unchecked pair upper bounds and incomplete block/group counts;
- duplicate groups and contradiction candidates with evidence;
- stale or unconfirmed memory candidates;
- organization suggestions where `requires_owner_approval` is always `true`;
- explicit non-destructive `safety` and `policy` objects;
- processing metrics and warnings.

When a safety bound is reached, the Actor returns `status: "partial"`. Never treat a partial response as a complete diagnosis; inspect `coverage.detectors` before taking action.

### Safety contract

- `owner_authorized: true` is required.
- Input memories are not mutated.
- `mutation_applied` and every suggestion's `mutation_applied` are always `false`.
- Protected memories do not receive an automatic primary/replacement selection.
- Contradictions are candidates, not facts.
- A newer `valid_from` value alone does not invalidate an older memory.
- The Actor makes no outbound API or model calls and requires no third-party credentials.
- Memory contents are not written to application logs.

The Actor only writes the structured diagnosis to its default Dataset. It does not access other user storages and is designed for Apify's limited-permissions mode.

### Input

`memories` accepts 1–10,000 JSON objects. Every object requires:

```json
{
  "id": "memory-1",
  "content": "The fictional assistant prefers concise responses."
}
```

For high-confidence contradiction checks, include `scope`, `key`, and `value`. Optional fields include timestamps, language, context, importance, tags, and `protected`.

Example:

```json
{
  "schema_version": "1.0",
  "request_id": "synthetic-example",
  "owner_authorized": true,
  "memories": [
    {
      "id": "fictional-1",
      "content": "The fictional assistant prefers concise responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "concise",
      "protected": true
    },
    {
      "id": "fictional-2",
      "content": "The fictional assistant prefers detailed responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "detailed"
    }
  ]
}
```

Only synthetic data appears in repository examples and tests.

### Use from an AI agent

After publication, an agent connected to the [Apify MCP server](https://docs.apify.com/mcp) can:

1. find the Actor with `search-actors`;
2. inspect input, output, README, and pricing with `fetch-actor-details`;
3. run it with `call-actor`;
4. read the diagnosis using `get-dataset-items` and the returned Dataset ID.

The Actor also receives Apify's REST API automatically. The output and Dataset schemas describe the result for API and MCP clients. A private build has passed real Apify runs; Store and MCP discovery remain unavailable until publication.

### Pricing status

Planned launch price: **USD 0.05 per successful memory diagnosis** using pay-per-event event name `memory-diagnosis`.

Charging is enabled for the approved Store release with `ENABLE_MONETIZATION=true`. The only permitted event is `memory-diagnosis` at USD 0.05, once per successful diagnosis; platform usage is included. The adapter rejects any other event or price before diagnosis. It then uses Apify SDK's PPE-aware `Actor.pushData()`: the SDK checks the spending limit, writes the allowed Dataset item, and only then charges it. A Dataset write failure therefore happens before charging, and the adapter requires the charging manager to confirm exactly one event.

The Console pricing configuration must not leave `apify-default-dataset-item` enabled together with `memory-diagnosis`, or one diagnosis can trigger two events. The current promise to charge only for a successful diagnosis also requires removing `apify-actor-start`; retaining it would be a pricing-policy change requiring separate owner approval. The SDK store-then-charge path, spending-limit refusal, and Dataset write failure are covered by automated tests; live charging remains blocked until the owner approves pricing activation.

### Privacy and Apify storage

Running this Actor on Apify means the submitted input is sent to and stored by the Apify platform, and the diagnosis is stored in the default Dataset. The Actor itself does not forward data to another service.

Apify retention depends on the caller's plan and settings. Named storages are retained indefinitely. Storage access can also be shared by account policy, explicit grants, links, or pre-signed URLs. Before using personal or sensitive memory data:

- set the shortest suitable retention period;
- keep general resource access restricted;
- do not name the run's storages;
- avoid secrets and unnecessary personal data;
- verify organization access, deletion, DPA, residency, and incident-response requirements.
- after a private fictional-data test, delete both the run's default key-value store and default Dataset and verify that neither storage ID remains readable.

See [Apify storage documentation](https://docs.apify.com/storage) and [general resource access](https://docs.apify.com/account/collaboration/general-resource-access).

### Current limitations

- Deterministic matching is optimized for tested English and Japanese patterns, not unrestricted semantic reasoning.
- Large or highly repetitive inputs may intentionally return partial coverage.
- The current release produces advice only; applying changes is the owner's responsibility.
- Private Apify measurements cover small and maximum-size synthetic inputs. Retention, customer transfer, and live PPE behavior still depend on the caller/account configuration and launch settings.

***

### 日本語

AI CLINICのMemory Cleaningは、AIエージェントの記憶JSONから重複、矛盾候補、古い情報、確認日の不足を検出する非破壊診断Actorです。記憶の削除・統合・書換えは行わず、すべて所有者確認が必要な提案として返します。

- `owner_authorized: true`が必須です。
- 保護記憶は自動的な代表候補・置換候補にしません。
- 上限到達時は`status: "partial"`となり、`coverage`に未検査範囲が表示されます。
- Actor自身は外部APIや外部AIモデルを呼び出しません。
- 記憶内容をアプリケーションログへ出力しません。

ただし、Apify上で実行すると入力はApifyへ送信され、診断結果はDatasetへ保存されます。個人情報や機密情報を扱う前に、保存期間、一般アクセス設定、組織権限、削除方法、DPA等を確認してください。

販売予定価格は診断1回USD 0.05です。非公開Build/Runは完了していますが、一般公開と課金開始は所有者の最終承認まで無効のままです。

# Actor input Schema

## `schema_version` (type: `string`):

AI CLINIC request schema version.

## `request_id` (type: `string`):

Optional caller-supplied correlation ID. Memory content must not be placed in this field.

## `owner_authorized` (type: `boolean`):

Must be true. Confirms that the memory owner authorized this advisory diagnosis. Runtime validation rejects false.

## `memories` (type: `array`):

JSON array of 1–10,000 memory records. Each record requires id and content. Optional structured contradiction fields scope, key, and value accept JSON scalar values. Protected memories remain review-only.

## `options` (type: `object`):

Optional deterministic analysis controls. Defaults are applied by the existing AI CLINIC engine.

## Actor input object example

```json
{
  "schema_version": "1.0",
  "owner_authorized": true,
  "memories": [
    {
      "id": "synthetic-1",
      "content": "The assistant prefers concise responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "concise",
      "updated_at": "2026-10-01T00:00:00Z",
      "language": "en",
      "protected": true
    },
    {
      "id": "synthetic-2",
      "content": "The assistant prefers detailed responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "detailed",
      "updated_at": "2026-10-02T00:00:00Z",
      "language": "en"
    }
  ]
}
```

# Actor output Schema

## `diagnosis` (type: `string`):

Dataset items contain status, coverage, explicit unchecked-scope metrics, safety guarantees, evidence, and owner-approval-only suggestions.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "owner_authorized": true,
    "memories": [
        {
            "id": "synthetic-1",
            "content": "The assistant prefers concise responses.",
            "scope": "preferences",
            "key": "response_style",
            "value": "concise",
            "updated_at": "2026-10-01T00:00:00Z",
            "language": "en",
            "protected": true
        },
        {
            "id": "synthetic-2",
            "content": "The assistant prefers detailed responses.",
            "scope": "preferences",
            "key": "response_style",
            "value": "detailed",
            "updated_at": "2026-10-02T00:00:00Z",
            "language": "en"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("jp-public-data/ai-clinic-memory-cleaning").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "owner_authorized": True,
    "memories": [
        {
            "id": "synthetic-1",
            "content": "The assistant prefers concise responses.",
            "scope": "preferences",
            "key": "response_style",
            "value": "concise",
            "updated_at": "2026-10-01T00:00:00Z",
            "language": "en",
            "protected": True,
        },
        {
            "id": "synthetic-2",
            "content": "The assistant prefers detailed responses.",
            "scope": "preferences",
            "key": "response_style",
            "value": "detailed",
            "updated_at": "2026-10-02T00:00:00Z",
            "language": "en",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("jp-public-data/ai-clinic-memory-cleaning").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "owner_authorized": true,
  "memories": [
    {
      "id": "synthetic-1",
      "content": "The assistant prefers concise responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "concise",
      "updated_at": "2026-10-01T00:00:00Z",
      "language": "en",
      "protected": true
    },
    {
      "id": "synthetic-2",
      "content": "The assistant prefers detailed responses.",
      "scope": "preferences",
      "key": "response_style",
      "value": "detailed",
      "updated_at": "2026-10-02T00:00:00Z",
      "language": "en"
    }
  ]
}' |
apify call jp-public-data/ai-clinic-memory-cleaning --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,jp-public-data/ai-clinic-memory-cleaning"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/PEKFb5frg0PGkATqL/builds/VetcVkK4wbsRl5nbS/openapi.json
