0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AI記憶の同意を追跡するConsent Ledger

利用目的を要求し、grantまたはdenyを決定し、Ledgerへ記録して利用可否を強制する流れ

はじめに

AIエージェントへ長期記憶を持たせるとき、保存できることと使ってよいことは別問題です。会話から抽出した情報があっても、別のAI、別workspace、公開回答で再利用してよいとは限りません。consent=true の1列だけでは、誰が、何に、いつまで同意したかを説明できません。

必要なのは記憶本体と同意履歴を分けたConsent Ledgerです。検索時には user_id + agent_id + memory_space_id の境界に加え、最新の同意状態、visibility、用途を評価します。同意撤回後はvector indexに残っていても回答へ出さないfail-closed設計にします。

記憶本体と同意イベントを分ける

同意状態をMemory行へ上書きすると、以前どの条件だったか追跡できません。Consentは追記型イベントとして保存します。

type MemoryRecord = {
  memoryId: string;
  userId: string;
  agentId: string;
  memorySpaceId: string;
  sourceAi: string;
  sourceApp: string;
  contentCiphertext: string;
  createdAt: string;
};

type ConsentEvent = {
  eventId: string;
  memoryId: string;
  subjectUserId: string;
  version: number;
  action: "grant" | "restrict" | "revoke";
  purposes: ("personal_reply" | "task_execution" | "shared_workspace")[];
  visibility: "private" | "agent" | "workspace";
  effectiveAt: string;
  expiresAt?: string;
};

記憶本文は暗号化し、Ledgerには本文を書きません。ログへもmemory ID、action、purpose、時刻だけを残します。これにより監査証跡を保ちつつ、同意履歴から個人情報が漏れる範囲を抑えられます。

最新状態を決定論的に畳み込む

イベントにはmemory単位で単調増加する version を保存します。読み取り側は時刻ではなくversion順に畳み込み、同じversionの重複は不整合としてfail-closedにします。これにより、revoke後に古いgrantが遅延到着しても権限は復活しません。grantやrestrictの expiresAt が現在時刻以前なら、そのversionはdenyとして評価します。

type ConsentState = {
  allowed: boolean;
  purposes: Set<string>;
  visibility: "private" | "agent" | "workspace";
  version: number;
};

const DENY = (version: number): ConsentState => ({
  allowed: false,
  purposes: new Set(),
  visibility: "private",
  version,
});

function assertValidConsentEvent(event: ConsentEvent): void {
  if (!Number.isSafeInteger(event.version) || event.version <= 0) {
    throw new Error("invalid_consent_version");
  }
  if (!["grant", "restrict", "revoke"].includes(event.action as string)) {
    throw new Error("unknown_consent_action");
  }
  if (!Number.isFinite(Date.parse(event.effectiveAt))) {
    throw new Error("invalid_effective_at");
  }
  if (
    event.expiresAt !== undefined &&
    !Number.isFinite(Date.parse(event.expiresAt))
  ) {
    throw new Error("invalid_expires_at");
  }
}

function reduceConsent(
  events: ConsentEvent[],
  nowMs = Date.now(),
  initial: ConsentState = DENY(0),
): ConsentState {
  events.forEach(assertValidConsentEvent);
  const ordered = [...events].sort((a, b) => a.version - b.version);
  const seen = new Set<number>();

  return ordered.reduce<ConsentState>((state, event) => {
    if (seen.has(event.version)) {
      throw new Error(`duplicate_consent_version:${event.version}`);
    }
    seen.add(event.version);

    // 古い再配送は無視し、同versionの競合イベントはfail-closedにする。
    if (event.version < state.version) return state;
    if (event.version === state.version) {
      throw new Error(`consent_version_collision:${event.version}`);
    }

    const expired =
      event.expiresAt !== undefined &&
      Date.parse(event.expiresAt) <= nowMs;
    if (event.action === "revoke" || expired) return DENY(event.version);

    return {
      // restrictは列挙されたpurposeだけを残す。
      allowed: event.purposes.length > 0,
      purposes: new Set(event.purposes),
      visibility: event.visibility,
      version: event.version,
    };
  }, initial);
}

versionは同じmemoryのLedgerへappendするときに、条件付き書き込みで採番します。初期値をdenyにするのも重要です。Ledger取得失敗、version重複、parse失敗、未知actionは許可ではなく停止へ倒します。

検索は境界条件を先に掛ける

vector検索の後でuser IDを絞る設計は危険です。候補生成の段階からtenant境界を必須条件にし、さらに同意フィルタを通します。

def recall(query, ctx):
    assert ctx.user_id and ctx.agent_id and ctx.memory_space_id
    candidates = vector_store.search(
        query=query,
        filters={
            "user_id": ctx.user_id,
            "agent_id": ctx.agent_id,
            "memory_space_id": ctx.memory_space_id,
        },
        limit=30,
    )
    return [m for m in candidates if consent_allows(m.memory_id, ctx.purpose, ctx.visibility)][:5]

共有記憶は暗黙継承せず、shared_workspace purposeへの明示grantを必要とします。別AIへの持ち出しもsourceとdestinationを記録し、利用者がどこで使われたか確認できるようにします。

撤回をindexへ反映する

撤回時にembeddingを即削除できれば理想ですが、非同期処理やバックアップで遅れます。そこで二重の防御を置きます。

  1. Consent Ledgerのrevokeを同期書き込みする
  2. recall時に最新Consentを必ず評価する
  3. 非同期workerがvector indexとcacheを削除する
  4. 削除Receiptを保存する
async function revokeMemory(memoryId: string, userId: string) {
  const event = await consentStore.append({ memoryId, userId, action: "revoke" });
  await denyCache.set(memoryId, { version: event.version, revokedAt: event.effectiveAt });
  await deletionQueue.enqueue({ memoryId, consentVersion: event.version });
  return { accepted: true, eventId: event.eventId };
}

deny cacheは許可cacheより優先します。削除workerが失敗しても、検索結果には出ません。再試行は同じmemory IDとconsent versionで冪等に行います。

テストで混在と撤回を再現する

正常なgrantだけでは不十分です。別user、別agent、別space、期限切れ、撤回直後、Ledger障害を試します。

import { describe, expect, it } from "vitest";

it("別memory_spaceの記憶を返さない", async () => {
  const result = await recall("約束", context({ memorySpaceId: "private-a" }));
  expect(result.every((m) => m.memorySpaceId === "private-a")).toBe(true);
});

it("撤回済みembeddingが残っていても回答へ出さない", async () => {
  vectorStore.seed(revokedMemory);
  consentStore.seed(revokeEvent(revokedMemory.memoryId));
  expect(await recall("住所", ownerContext)).toEqual([]);
});

it("revokeより古いgrantが遅延到着しても復活しない", () => {
  const revoked = reduceConsent([
    grantEvent({ version: 7, purposes: ["personal_reply"] }),
    revokeEvent({ version: 8 }),
  ]);
  const state = reduceConsent([
    grantEvent({ version: 6, purposes: ["shared_workspace"] }),
  ], Date.now(), revoked);
  expect(state.allowed).toBe(false);
  expect(state.version).toBe(8);
});

it("現在stateと同versionの競合eventはfail-closed", () => {
  const current = {
    allowed: true,
    purposes: new Set(["personal_reply"]),
    visibility: "agent" as const,
    version: 8,
  };
  expect(() =>
    reduceConsent([revokeEvent({ version: 8 })], Date.now(), current),
  ).toThrow("consent_version_collision:8");
});

it("期限切れgrantはdeny", () => {
  const state = reduceConsent([
    grantEvent({ version: 9, expiresAt: "2026-07-01T00:00:00Z" }),
  ], Date.parse("2026-07-02T00:00:00Z"));
  expect(state.allowed).toBe(false);
  expect(state.version).toBe(9);
});

it.each([
  grantEvent({ version: 10, expiresAt: "not-a-date" }),
  grantEvent({ version: 0 }),
  { ...grantEvent({ version: 11 }), action: "future_action" } as unknown as ConsentEvent,
])("不正なLedger eventはfail-closed", (event) => {
  expect(() => reduceConsent([event])).toThrow();
});

it("Consent取得失敗はdeny", async () => {
  consentStore.failOnce();
  await expect(recall("好み", ownerContext)).rejects.toThrow("consent_unavailable");
});

監査テストでは、本文やsecretがログに出ていないことも確認します。IDだけでも個人を直接示す場合は内部surrogate IDを使います。

可搬性と同意を一緒に運ぶ

記憶を別AIへ持ち出せても、同意条件が失われたら安全ではありません。export bundleにはmemory本体、provenance、最新Consent snapshot、Ledger hash、schema versionを含めます。import側は署名とschemaを検証し、未知purposeはdenyにします。

この設計なら、ChatGPT、Claude、Geminiなど利用先が変わっても、記憶だけでなく「どの条件で使えるか」も持ち運べます。可搬性を単なるデータコピーではなく、利用境界の再現として定義できます。

まとめ

長期記憶では、保存・検索・同意・削除を一つのbooleanにまとめないことが重要です。追記型Consent Ledger、検索時の境界filter、revoke優先の二重防御で、撤回を即時に回答へ反映できます。

AIパートナーが育つほど記憶は価値を持ちます。その価値を守るには、利用者が所有し、持ち出し先でも同意条件を維持できる設計が必要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?