# How TencentDB Agent Memory Manages Skills in Its Skill Library: Architecture Deep Dive

> Discover how TencentDB Agent Memory manages skills via its three-layer architecture. Explore SQLite persistence, versioning, and resource storage for atomic creation and safe editing.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: architecture
- Published: 2026-08-30

---

**TencentDB Agent Memory manages skills through a three-layer architecture that combines SQLite persistence, transactional versioning, and binary resource storage, all orchestrated by the `SkillCore` class to provide atomic version creation, full-text search, and safe concurrent editing.**

The TencentDB-Agent-Memory repository implements a robust Skill Library designed to store reusable LLM prompts and associated binary resources. Understanding how TencentDB Agent Memory manages skills in its Skill Library reveals a sophisticated system built for strong consistency, scalable search, and safe collaboration across agent teams.

## The Three-Layer Skill Library Architecture

The Skill Library is built on three tightly-coupled layers that separate metadata persistence, version coordination, and binary storage.

### Persistence Layer (`SqliteSkillStore`)

Located at [`MemoryCore/src/core/skill/skill-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-store.ts), the `SqliteSkillStore` class handles immutable metadata for every skill version. It stores skill IDs, versions, content hashes, status flags, and timestamps in SQLite, providing full-text search via **FTS5** and optional vector search capabilities. This layer serves as the single source of truth for skill metadata, ensuring the database—not the filesystem—is consulted for all `get`, `list`, and `search` operations.

### Transactional Versioning (`SkillVersioning`)

The `SkillVersioning` class in [`MemoryCore/src/core/skill/skill-versioning.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-versioning.ts) coordinates atomic version creation. It implements **copy-on-write** semantics: when creating a new version, it copies the previous version's storage, applies resource changes, writes a new database row, and rolls back entirely on error. This layer also handles TTL cleanup for expired versions, deletion workflows, and vector database usage reporting.

### Binary Resource Store (`SkillResourceStore`)

The `SkillResourceStore` at [`MemoryCore/src/core/skill/skill-resource-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-resource-store.ts) manages actual files under the path `<skill_id>/v<version>/files/…`. It enforces size limits (`maxResourceSizeBytes` and `maxSkillTotalBytes`), performs MIME type detection, and validates safe file paths to prevent directory traversal attacks.

## The SkillCore Facade: Public API Operations

The `SkillCore` class at [`MemoryCore/src/core/skill/skill-core.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-core.ts) serves as the public façade used by HTTP gateways and SDKs. It exposes eleven primary actions divided into write and read operations.

### Write Actions

SkillCore implements six write actions that mutate the Skill Library:

- `create` – Initializes a new skill with its first version
- `update` – Replaces skill content and creates a new version
- `patch` – Applies partial updates to skill metadata
- `delete` – Removes all versions and storage permanently
- `writeFiles` – Adds binary resources to a skill version
- `removeFiles` – Removes specific resources from a version

### Read Actions

For data retrieval, SkillCore provides five read actions:

- `get` – Retrieves a specific skill version
- `list` – Lists active skills for a team
- `search` – Performs full-text or vector search across skills
- `listVersions` – Shows version history for a skill
- `readFile` – Streams binary resource content

## Core Workflows and Safety Guarantees

Every operation follows strict workflows designed to maintain consistency and security.

### Parsing and Validation

All write operations begin with `SkillCore.parseAndValidate`, which uses the markdown front-matter parser in [`skill-format.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/skill-format.ts) to validate that submitted [`SKILL.md`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/SKILL.md) files contain required fields like name and description. This prevents malformed skills from entering the library.

### Versioning with Copy-on-Write

When updating a skill, `SkillVersioning.appendNextVersion` (or `createNewSkill` for initial versions) executes a coordinated transaction:

1. Fetches the current *head* (latest active version) via `store.getHead`
2. Creates a new storage directory
3. Copies previous version files
4. Applies resource additions or removals
5. Calls `store.appendVersion` to write the database row

If any step fails, the system cleans up all intermediate artifacts, ensuring atomic version creation.

### Permission Controls

Before any write operation, SkillCore invokes functions from [`skill-permission.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/skill-permission.ts):

- `assertOwner` – Verifies the requesting agent owns the skill
- `assertTeamMatch` – Ensures team isolation
- `assertVersionFresh` – Confirms the client's expected version matches the current head, preventing lost updates

### Idempotency and TTL Cleanup

The system handles idempotency through `content_hash` comparison. If `appendNextVersion` detects that the content hash and resource manifest are unchanged, it returns an `IdempotentNoOpError` and preserves the existing head.

For storage management, `SkillVersioning.cleanupExpiredVersionsForSkill` removes old non-head versions after a configurable TTL while preserving the most recent `KEEP_RECENT` versions.

## Full-Text Search and Vector Retrieval

The Skill Library implements hybrid search capabilities through `SqliteSkillStore.searchSkills`. The `buildFtsQuery` function constructs FTS5 queries that return **BM25-ranked** results with highlighted snippets. When embeddings are available, the system performs vector search and degrades gracefully to BM25-only results when embeddings are unavailable, ensuring consistent API behavior regardless of configuration.

## Working with the Skill Library: TypeScript SDK Example

The following example demonstrates the complete skill lifecycle using the TypeScript SDK from [`MemoryCore/sdk/memory-core/typescript/src/v3/skill-client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/sdk/memory-core/typescript/src/v3/skill-client.ts):

```typescript
import { SkillClient } from '@tencentdb/memory-core';

// Initialise the client (base URL of the MemoryProxy HTTP API)
const client = new SkillClient({ apiBase: 'http://localhost:3000/v3' });

async function demoSkillLifecycle() {
  // 1️⃣ Create a new skill (v1)
  const createRes = await client.createSkill({
    name: 'SummarizeArticle',
    content: `---
name: SummarizeArticle
description: Summarizes a long article into a concise paragraph.
---
You are a summarizer. {{input}}`,
    // optional: additional binary resources
    resources: [
      {
        path: 'prompt.txt',
        content: Buffer.from('Please keep the tone neutral.').toString('base64'),
        encoding: 'base64',
        mime_type: 'text/plain',
      },
    ],
  });
  console.log('Created skill ID:', createRes.skill_id);

  // 2️⃣ List all active skills for the current team
  const list = await client.listSkills({ team_id: 'team-123' });
  console.log('Active skills:', list.items.map(s => s.name));

  // 3️⃣ Update the skill (creates v2)
  const head = await client.getSkill({ skill_id: createRes.skill_id });
  const updated = await client.updateSkill({
    skill_id: head.skill_id,
    expected_version: head.version,
    content: head.content.replace('summarizer', 'expert summarizer'),
  });
  console.log('Updated to version', updated.version);

  // 4️⃣ Search the library
  const hits = await client.searchSkills({
    query: 'summarize',
    top_k: 5,
    team_id: 'team-123',
  });
  console.log('Search hits:', hits.map(h => ({ name: h.skill.name, score: h.score })));

  // 5️⃣ Read a binary resource from the latest version
  const file = await client.readFile({
    skill_id: createRes.skill_id,
    path: 'prompt.txt',
    encoding: 'utf-8',
  });
  console.log('Prompt file content:', file.content);

  // 6️⃣ Delete the skill (physical removal)
  const del = await client.deleteSkill({
    skill_id: createRes.skill_id,
    expected_version: updated.version,
  });
  console.log('Deleted?', del.archived);
}

demoSkillLifecycle().catch(console.error);

```

## Summary

- **TencentDB Agent Memory** implements its Skill Library through three architectural layers: SQLite persistence (`SqliteSkillStore`), transactional versioning (`SkillVersioning`), and binary resource storage (`SkillResourceStore`).
- The `SkillCore` class orchestrates six write actions and five read actions, enforcing security through `assertOwner`, `assertTeamMatch`, and `assertVersionFresh` checks.
- Version creation follows copy-on-write semantics with atomic transactions, ensuring that either both database rows and storage succeed, or all changes roll back.
- Full-text search utilizes FTS5 with BM25 ranking, while optional vector search provides hybrid retrieval capabilities without breaking existing clients.
- The TypeScript SDK exposes all functionality through `SkillClient`, enabling teams to create, version, search, and delete skills programmatically.

## Frequently Asked Questions

### How does TencentDB Agent Memory handle concurrent edits to the same skill?

The system uses optimistic concurrency control via `assertVersionFresh` in [`skill-permission.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/skill-permission.ts). Each write operation requires an `expected_version` parameter that must match the current head version. If another client has updated the skill since the calling client last read it, the version mismatch triggers an error, preventing lost updates and forcing the client to refresh before retrying.

### What happens when a skill update fails halfway through?

Because `SkillVersioning.appendNextVersion` in [`MemoryCore/src/core/skill/skill-versioning.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-versioning.ts) implements transactional coordination, any failure during directory creation, file copying, or database writing triggers a complete rollback. The system cleans up all intermediate storage artifacts and does not append the new version row, maintaining strong consistency between the database and filesystem.

### How does the Skill Library prevent duplicate content from creating unnecessary versions?

The versioning layer computes a `content_hash` for every skill version. When `appendNextVersion` detects that the submitted content hash and resource manifest match the existing head version exactly, it returns an `IdempotentNoOpError` and preserves the current version unchanged. This prevents database bloat from identical consecutive updates.

### What search capabilities are available for finding skills in the library?

The `SqliteSkillStore` at [`MemoryCore/src/core/skill/skill-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/src/core/skill/skill-store.ts) provides hybrid search through `buildFtsQuery`. It utilizes SQLite FTS5 for BM25-ranked full-text search with highlighted snippets. When vector embeddings are configured, the system performs semantic search and gracefully degrades to BM25-only results if embeddings are unavailable, ensuring reliable search performance across all deployments.