Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Memory scopes and trusted authorization context

Design memory scope, authenticity, permissions and recall order as data contracts, and vector similarity is only responsible for sorting.

Learning objectives: The relevance, life cycle and visibility range of memory are three independent dimensions. Threads or namespaces provide organization, and real authorization is still determined by trusted identities and current resource relationships.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Junior/mid-level AI application candidates with Python and backend fundamentals.

Memory scopes and trusted authorization context
The relevance, life cycle and visibility range of memory are three independent dimensions. Threads or namespaces provide organization, and real authorization is still determined by trusted identities and current resource relationships.

How does the mechanism work?

Step-by-step explanation
  1. After the user exits the project, how to deal with the context in the started task?

    After static namespace separation, consider changes in the authorization lifecycle.

  2. Why might namespace prefix matching expand the read range?

    The storage API's matching mechanism may expand candidates and must be separated from authorization.

  3. How to prioritize when organizational rules conflict with personal preferences?

    Multiple authorized scopes can still have conflicting semantic priorities.

Debugging · Diagnose failures

Debug · A mixed-scope cache leaks between legal members

Objectives of this level: Reproduce a real wrong-result assertion, isolate the cache-key cause and repair it without weakening current membership checks.

Visual guide · Scope comes from trusted identity

Scope comes from trusted identity

Namespaces organize candidates; current authority decides access. Caches of mixed personal/project/organization bundles must include the trusted user boundary. Select the figure to open it at full size.

Reproduce the failure in a scratch copy

The SQL recall can be correct while its cache leaks. Both t1/Alice and t1/Bob legitimately belong to p1. Therefore denial at membership is not allowed to mask this case. The bundle contains organization, project and personal rows, so a tenant/project cache key is too broad.

Save this full snippet as a separate scratch file such as memory_cache_check.py. It is self-contained: it recreates all ten rows, sessions and membership checks, runs the successful recall controls, then executes the faulty cached gateway. It has no dependency on a previous Python process or the capstone. Run it; the final user-isolation assertion is intentionally expected to fail.

import json
import sqlite3

ROWS = [
    ("r1", "t1", "user", "alice", "prefer English", 1, 200, 1),
    ("r2", "t1", "user", "bob", "prefer Chinese", 99, 200, 1),
    ("r3", "t1", "project", "p1", "use PostgreSQL", 2, 200, 1),
    ("r4", "t1", "project", "p2", "private MongoDB design", 100, 200, 1),
    ("r5", "t2", "user", "alice", "t2 private preference", 999, 200, 1),
    ("r6", "t1", "org", "t1", "human approval required", 3, 200, 1),
    ("r7", "t1", "project", "p1", "expired decision", 1000, 100, 1),
    ("r8", "t1", "project", "p1", "withdrawn decision", 999, 200, 0),
    ("r9", "t2", "project", "p1", "t2 same project ID", 9998, 200, 1),
    ("r10", "t1-admin", "user", "alice", "prefix tenant secret", 10000, 200, 1),
]
# Fixed local authenticated-session fixture; this is not a real login system.
SESSIONS = {"demo-alice": ("t1", "alice"), "demo-bob": ("t1", "bob"),
            "demo-t2-alice": ("t2", "alice")}
db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE memory(id TEXT PRIMARY KEY, tenant TEXT, scope TEXT, owner TEXT,
                    body TEXT, score INTEGER, expires INTEGER, active INTEGER);
CREATE TABLE membership(tenant TEXT, user TEXT, project TEXT, active INTEGER,
                        epoch INTEGER, PRIMARY KEY(tenant,user,project));
""")
db.executemany("INSERT INTO memory VALUES (?,?,?,?,?,?,?,?)", ROWS)
db.executemany("INSERT INTO membership VALUES (?,?,?,?,?)",
    [("t1", "alice", "p1", 1, 1), ("t1", "bob", "p1", 1, 1),
     ("t1", "bob", "p2", 1, 1), ("t2", "alice", "p1", 1, 1)])
db.commit()

def context(token, request):
    if token not in SESSIONS:
        raise PermissionError("session_required")
    if not isinstance(request, dict) or set(request) != {"project_id", "query"} or not all(isinstance(x, str) for x in request.values()):
        raise ValueError("request_shape")
    tenant, user = SESSIONS[token]
    project = request["project_id"]
    row = db.execute("SELECT active,epoch FROM membership WHERE tenant=? AND user=? AND project=?",
                     (tenant, user, project)).fetchone()
    if row is None or not row["active"]:
        raise PermissionError("project_membership_required")
    return tenant, user, project, row["epoch"]

def select_authorized(tenant, user, project, at=100):
    return [dict(r) for r in db.execute("""
        SELECT * FROM memory WHERE tenant=? AND active=1 AND expires>?
        AND ((scope='user' AND owner=?) OR (scope='project' AND owner=?)
             OR (scope='org' AND owner=?)) ORDER BY score DESC,id
        """, (tenant, at, user, project, tenant))]

def gateway(token, request, at=100):
    tenant, user, project, _ = context(token, request)
    return select_authorized(tenant, user, project, at)

def ids(rows):
    return [r["id"] for r in rows]

request = {"project_id": "p1", "query": "database"}
assert ids(gateway("demo-alice", request)) == ["r6", "r3", "r1"]
assert ids(gateway("demo-bob", request)) == ["r2", "r6", "r3"]
assert ids(gateway("demo-t2-alice", request)) == ["r9", "r5"]
for token, req, expected in [
    ("demo-alice", {"project_id": "p2", "query": "database"}, "project_membership_required"),
    ("unknown", request, "session_required"),
    ("demo-alice", {**request, "tenant_id": "t2", "user_id": "bob"}, "request_shape")]:
    try:
        gateway(token, req)
    except (PermissionError, ValueError) as exc:
        assert str(exc) == expected
    else:
        raise AssertionError(expected)
assert not {"r2", "r4", "r5", "r7", "r8", "r9", "r10"} & set(ids(gateway("demo-alice", request)))
print(json.dumps({"alice": ids(gateway("demo-alice", request)),
    "bob": ids(gateway("demo-bob", request)),
    "t2_alice": ids(gateway("demo-t2-alice", request)),
    "negative_controls": "passed"}, sort_keys=True))

# Save this entire snippet in an independent scratch file, then repair this function.
cache = {}
def cached_gateway(token, request, at=100):
    tenant, user, project, epoch = context(token, request)  # reauthorize even cache hits
    key = (tenant, project, epoch, at)  # BUG: omits user from a mixed-scope bundle
    if key not in cache:
        cache[key] = select_authorized(tenant, user, project, at)
    return cache[key]

alice = ids(cached_gateway("demo-alice", request))
bob = ids(cached_gateway("demo-bob", request))
print(json.dumps({"alice_cached": alice, "bob_cached": bob, "expected_bob": ["r2", "r6", "r3"]}, sort_keys=True), flush=True)
assert bob == ["r2", "r6", "r3"], "cache mixed two authenticated users"
# This second invariant must still pass after the key is repaired.
db.execute("UPDATE membership SET active=0,epoch=epoch+1 WHERE tenant='t1' AND user='alice' AND project='p1'")
try:
    cached_gateway("demo-alice", request)
except PermissionError as exc:
    assert str(exc) == "project_membership_required"
else:
    raise AssertionError("revocation bypassed by cache")
print("cache isolation and current revocation: passed")

Evidence → cause → repair

Before repair the last JSON shows Alice cached r6/r3/r1 and Bob receiving the same r6/r3/r1, although expected Bob is r2/r6/r3. It raises AssertionError: cache mixed two authenticated users. The ordinary SQL controls already passed, and Bob’s membership is valid. The cache hit bypasses user-specific selection because its key omits user.

Modify only the key = ... line in your copied cached_gateway: include trusted tenant, trusted user, project, current membership epoch and test time. Do not alter fixture sessions, membership, select_authorized or assertions. A fresh process reconstructs an empty cache. Rerun; Bob must get r2/r6/r3 and the same file must finish with cache isolation and current revocation: passed.

The remaining test deactivates Alice’s project membership and advances its epoch after the bundle is cached. context still runs before every cache hit, so the next call is denied. Merely adding a key component while moving authorization after cache return would create a different revocation bug. Existing cached bytes are not erased by this denial; the experiment checks use blocking, not deletion from logs, backups or remote models.

Deliver the faulty output, repaired output and a minimal diff. Explain why project-only caching is appropriate for a project-only bundle but not this mixed bundle; the bundle’s data scopes determine the cache boundary.

Continue to do advanced research experiments

Why can’t the old context continue to be used after the policy changes?

Transferring pre-retrieval filtered ideas to memory versions and recovery. Observe how existing drafts become invalid after cancellation.

Read full text and fault analysis → · Download experiment package ↓

python3 cli.py memory-put --db memory.sqlite
python3 cli.py submit --db memory.sqlite
python3 cli.py run --db memory.sqlite --lease-seconds 2 --fault after_draft
python3 cli.py memory-forget --db memory.sqlite
# 等待至少 2 秒后分别执行
python3 cli.py run --db memory.sqlite
python3 cli.py inspect --db memory.sqlite

Keep evidence and check item by item

  • The draft checkpoint already exists after the first exit.
  • Recovery after memory-forget gets failed with memory_changed_or_expired.
  • No publish checkpoint; explain the difference between fail blocking and complete deletion.

Verify local scope, version, and undo blocking; old checkpoints remain, no complete deletion of logs, backups, or checkpoints is provided.

code example

Cache validity has another dimension

Even a tenant/user/project key can serve an expired or superseded memory if its TTL and data/source version are ignored. This fixed fixture keys on test time and checks membership; production also needs memory-version invalidation and expiry-aware cache lifetime.

Acceptance task for this level

Run the self-contained faulty scratch file, repair only its cache key, and rerun unchanged assertions. Submit before/after output, the key-line diff and an explanation of the separate current-revocation test.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why test two legal p1 members rather than a user who never joined p1?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.