[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ETDHJDWYNB1ZNBHNHXDPWX":3,"skill-same:01M7ETDHJDWYNB1ZNBHNHXDPWX":56},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7ETDHJDWYNB1ZNBHNHXDPWX","target-connector",null,"This skill should be used when creating a new target connector for CocoIndex to integrate with external systems. It provides guidance on implementing TargetHandler, TargetActionSink, and related types for declarative target state synchronization with change detection and automatic cleanup.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Ftarget-connector\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: target-connector\ndescription: This skill should be used when creating a new target connector for CocoIndex to integrate with external systems. It provides guidance on implementing TargetHandler, TargetActionSink, and related types for declarative target state synchronization with change detection and automatic cleanup.\n---\n\n# Target Connector\n\n## Overview\n\nA target connector connects CocoIndex's declarative target state system to external systems. It handles synchronization by determining what changed and applying changes to the external system.\n\n## When to Use\n\nUse this skill when creating a new target connector for any external system (databases, file systems, cloud storage, APIs, etc.).\n\n## Key Data Types\n\n### What You Implement\n\n| Type | Purpose |\n| ---- | ------- |\n| `TargetHandler` | Implements `reconcile()` — compares desired state with previous tracking records. Optionally implements `attachment(att_type)` for auxiliary child states. |\n| `TargetActionSink` | Executes actions against the external system |\n| Tracking Record | Persisted state for change detection (typically a frozen dataclass) |\n| Action | Describes what operation to perform on the external system |\n\n### What CocoIndex Provides\n\n| Type | Purpose |\n| ---- | ------- |\n| `TargetStateProvider` | Factory that creates `TargetState` objects from your handler |\n| `TargetState` | Wrapper that holds the key and spec |\n| `register_root_target_states_provider()` | Registers a root handler and returns a provider |\n| `declare_target_state()` | Declares a leaf target state for reconciliation |\n| `declare_target_state_with_child()` | Declares a target state and returns a child provider |\n\n## Implementation Workflow\n\n### Root Target States\n\n1. **Define types**: Key, Spec, TrackingRecord, Action\n2. **Implement TargetHandler**: The `reconcile()` method must be non-blocking\n3. **Create TargetActionSink**: Use `TargetActionSink.from_fn()` or `from_async_fn()`. The callback receives `context_provider: ContextProvider` as its first positional argument, followed by `actions`\n4. **Register provider**: Call `register_root_target_states_provider(name, handler)`\n5. **Create user-facing API**: Wrap the provider in a user-friendly class\n\n### Non-Root (Child) Target States\n\nFor targets nested inside another target (e.g., files inside a directory):\n\n1. Parent sink returns `ChildTargetDef(handler=...)` when executed\n2. Call `declare_target_state_with_child(parent_ts)` to get an unresolved child provider\n3. CocoIndex resolves the child provider when parent's sink executes\n\n### Child Invalidation\n\nFor container targets, set `child_invalidation` in `TargetReconcileOutput` when a container change affects its children:\n\n| Value | When to Use | Effect on Children |\n| ----- | ----------- | ------------------ |\n| `None` (default) | No impact on children (e.g., only new columns added) | Normal change detection |\n| `\"destructive\"` | Container rebuilt from scratch (e.g., table dropped and recreated due to primary key change or table type switch) | All previous tracking records ignored; children treated as new and re-declared |\n| `\"lossy\"` | Data loss possible but container not fully rebuilt (e.g., column removed or type changed) | All children get `prev_may_be_missing=True`, forcing upsert even if content appears unchanged |\n\n**Pattern for two-level (table\u002Frow) connectors using `statediff.diff_composite`:**\n\n```python\n# After computing main_action and column_actions via statediff.diff_composite:\nchild_invalidation: Literal[\"destructive\", \"lossy\"] | None = None\nif main_action == \"replace\":\n    # Table dropped and recreated — all rows are destroyed.\n    child_invalidation = \"destructive\"\nelif main_action is None and any(a != \"insert\" for a in column_actions.values()):\n    # Column changes other than adding new columns may lose existing row data.\n    child_invalidation = \"lossy\"\n\nreturn coco.TargetReconcileOutput(\n    action=_TableAction(...),\n    sink=self._sink,\n    tracking_record=_TableTrackingRecord(...),\n    child_invalidation=child_invalidation,\n)\n```\n\nFor connectors without column-level diffs (e.g., a collection that is either intact or fully replaced), only `\"destructive\"` applies:\n\n```python\nchild_invalidation: Literal[\"destructive\"] | None = (\n    \"destructive\" if main_action == \"replace\" else None\n)\n```\n\n## TargetHandler Protocol\n\n```python\nclass TargetHandler(Protocol[ValueT, TrackingRecordT, OptChildHandlerT]):\n    def reconcile(\n        self,\n        key: StableKey,\n        desired_target_state: ValueT | NonExistenceType,\n        prev_possible_records: Collection[TrackingRecordT],\n        prev_may_be_missing: bool,\n        \u002F,\n    ) -> TargetReconcileOutput[Any, TrackingRecordT, OptChildHandlerT] | None:\n        ...\n\n    # Optional: override to support attachment types\n    def attachment(self, att_type: str) -> TargetHandler | None:\n        return None\n```\n\n**Parameters:**\n\n- `key`: `StableKey` — a union of `None | bool | int | str | bytes | uuid.UUID | Symbol | tuple[StableKey, ...]`\n- `desired_target_state`: What the user declared, or `NON_EXISTENCE` if no longer declared\n- `prev_possible_records`: Tracking records from previous runs (may have multiple)\n- `prev_may_be_missing`: If `True`, the target state might not exist in the external system\n\n**Returns:**\n\n- `TargetReconcileOutput(action, sink, tracking_record, child_invalidation=None)` if an action is needed (generic params: `[ActionT, TrackingRecordT, OptChildHandlerT]`)\n- `None` if no changes are required\n\nThe optional `child_invalidation` field is only relevant for container targets — see [Child Invalidation](#child-invalidation).\n\n**Important:** The `reconcile()` method must be non-blocking. It should only compare states and return an action — actual I\u002FO happens in the sink.\n\n## Best Practices\n\n### Use `ContextKey` for External Resource Identity\n\nWhen a target connector manages state in an external resource (database, object store, etc.), use a `ContextKey` string as part of the target state key — not connection parameters like host, port, or credentials.\n\n**Why:** Target state keys must be stable across runs for correct reconciliation. CocoIndex uses keys to match current declarations with previously tracked states. If the key is stable, previously tracked states are associated with the current target, so CocoIndex can correctly reconcile — e.g., deleting rows that are no longer declared. If the key changes (because a connection parameter changed), CocoIndex cannot associate previous tracked states with the current target, and treats the target as being in a cleared state — losing the ability to clean up old data.\n\n**Pattern:**\n\n```python\n# User creates a stable logical name for the resource\ndb = coco.ContextKey[asyncpg.Pool](\"my_pg\")\n\n# Target connector uses db.key (the string \"my_pg\") in the target state key\nclass _TableKey(NamedTuple):\n    db_key: str           # Stable — from ContextKey.key\n    schema_name: str | None\n    table_name: str\n\nkey = _TableKey(db_key=db.key, ...)\n\n# At action time, resolve the live connection from context_provider\npool = context_provider.get(key.db_key, asyncpg.Pool)\n```\n\nThis decouples target identity from transient connection details — changing a password, switching replicas, or rotating credentials won't invalidate tracked states.\n\n**Resolve connections at action time, never at declare time.** Target states outlive the code that declared them: when a declaration disappears or an app is dropped, CocoIndex generates delete actions in a run where the mount\u002Fdeclare code never executes — only the persisted key and the current environment's `ContextProvider` are available then. Don't capture a live connection at declare time; resolve in the sink, then pass the typed connection down to child handlers directly (store `_pool: asyncpg.Pool`, not the key string).\n\n**Reference:** See `_TableKey` in `python\u002Fcocoindex\u002Fconnectors\u002Fpostgres\u002F_target.py` and `python\u002Fcocoindex\u002Fconnectors\u002Fsurrealdb\u002F_target.py`.\n\n### Idempotent Actions\n\nActions should be idempotent:\n\n```python\n# Good\npath.mkdir(parents=True, exist_ok=True)\npath.unlink(missing_ok=True)\nawait conn.execute(\"INSERT ... ON CONFLICT DO UPDATE ...\")\n\n# Bad\npath.mkdir()  # Fails if exists\nawait conn.execute(\"INSERT ...\")  # Fails on duplicate key\n```\n\n### Handle Multiple Previous States\n\nDue to interrupted updates, `prev_possible_records` may contain multiple records:\n\n```python\nif not prev_may_be_missing and all(\n    prev.fingerprint == target_fp for prev in prev_possible_records\n):\n    return None  # Safe to skip\n```\n\n### Fingerprinting for Change Detection\n\nUse the `connectorkits.fingerprint` utilities for content-based change detection:\n\n```python\nfrom cocoindex.connectorkits.fingerprint import fingerprint_bytes, fingerprint_str, fingerprint_object\n\n# For raw bytes\nfp = fingerprint_bytes(content)\n\n# For strings\nfp = fingerprint_str(text)\n\n# For arbitrary objects (uses memo key mechanism)\nfp = fingerprint_object(obj)\n```\n\n### Shared Action Sinks\n\nCreate module-level shared sinks when all handler instances use the same action logic. The callback must accept `context_provider: ContextProvider` as its first positional argument:\n\n```python\ndef _apply_actions(\n    context_provider: ContextProvider, actions: Sequence[MyAction]\n) -> list[coco.ChildTargetDef[MyChildHandler] | None] | None:\n    for action in actions:\n        conn = context_provider.get(action.key.db_key, ConnType)\n        ...\n\n_shared_sink = coco.TargetActionSink.from_fn(_apply_actions)\n```\n\nSink identity is **value-based**: sinks whose callbacks compare equal share one\nbatching identity, meaning their actions are batched and applied together (and\na batch is the natural transaction boundary for transactional stores). For a\nsink scoped to an external resource — e.g. one sink per database so all of that\ndatabase's writes share a transaction — make the callback a frozen dataclass\nkeyed by the resource and construct it on the fly in `reconcile()`; no\nmodule-level sink registry is needed:\n\n```python\n@dataclasses.dataclass(frozen=True)\nclass _DbSink:\n    db_key: str\n\n    async def __call__(\n        self, context_provider: ContextProvider, actions: Sequence[MyAction], \u002F\n    ) -> None:\n        conn = context_provider.get(self.db_key, ConnType)\n        ...\n\n# In reconcile(): equal callbacks yield the same sink identity.\nsink = coco.TargetActionSink.from_async_fn(_DbSink(key.db_key))\n```\n\nAn idle sink identity (no live sink object, no pending actions) is released\nautomatically, so per-resource sinks do not accumulate for the process\nlifetime.\n\n### Input Safety\n\nWhen building queries from user-provided names (table, column, index) or values (record IDs, keys), you must guard against injection and ensure correctness. See [input_safety.md](input_safety.md) for patterns on identifier validation, parameterized queries, and value escaping.\n\n## Completion Checklist\n\nAfter implementing the connector code, complete these additional steps:\n\n### 1. Optional Dependencies\n\nIf the connector requires third-party packages, update `pyproject.toml`:\n\n```toml\n[project.optional-dependencies]\n# Add new optional dependency group\nmyconnector = [\"some-package>=1.0.0\"]\n\n# Add to the 'all' group\nall = [\n    # ... existing deps ...\n    \"some-package>=1.0.0\",\n]\n\n[[tool.mypy.overrides]]\n# Add to mypy ignore list if package lacks type stubs\nmodule = [\n    # ... existing modules ...\n    \"some_package\",\n    \"some_package.*\",\n]\nignore_missing_imports = true\n```\n\n### 2. Documentation\n\nCreate connector documentation at `docs\u002Fdocs\u002Fconnectors\u002F\u003Cconnector_name>.md`:\n\n- Follow the structure of existing connector docs (e.g., `postgres.md`, `sqlite.md`)\n- Include: connection setup, target state APIs, schema definition, type mappings, examples\n- Add a note about optional dependencies if applicable\n\nUpdate `docs\u002Fsidebars.ts` to include the new connector:\n\n```typescript\n{\n  type: 'category',\n  label: 'Connectors',\n  items: [\n    \u002F\u002F ... existing connectors ...\n    'connectors\u002F\u003Cconnector_name>',  \u002F\u002F Add in alphabetical order\n  ],\n},\n```\n\n### 3. Tests\n\nCreate tests at `python\u002Ftests\u002Fconnectors\u002Ftest_\u003Cconnector_name>_target.py`:\n\n**Test structure:**\n\n```python\nimport pytest\nimport cocoindex as coco\nfrom tests import common\n\n# Check for optional dependency availability\ntry:\n    import optional_package\n    HAS_OPTIONAL = True\nexcept ImportError:\n    HAS_OPTIONAL = False\n\nrequires_optional = pytest.mark.skipif(\n    not HAS_OPTIONAL, reason=\"optional-package is not installed\"\n)\n\ncoco_env = common.create_test_env(__file__)\n```\n\n**Required test cases:**\n\n| Category | Test Cases |\n| -------- | ---------- |\n| Basic CRUD | Create target, insert data, update data, delete data |\n| Schema | Different column types, schema with extra columns |\n| Lifecycle | Drop\u002Fcleanup when target no longer declared |\n| Optimization | No-op when data unchanged |\n| Multiple targets | Multiple tables\u002Fdirectories in same connection |\n| User-managed | `managed_by=\"user\"` mode if supported |\n| Optional features | Vector support, special types (skip if dependency missing) |\n\n**Test pattern:**\n\n```python\nDB_KEY = coco.ContextKey[connector.ConnectionType](\"test_db\")\n\ndef test_insert_and_update(connector_fixture: tuple[Connection, Path]) -> None:\n    conn, _ = connector_fixture\n    source_rows: list[RowType] = []\n\n    coco_env.context_provider.provide(DB_KEY, conn)\n\n    async def declare_target() -> None:\n        table = await coco.use_mount(\n            coco.component_subpath(\"setup\", \"table\"),\n            connector.declare_table_target,\n            DB_KEY,\n            \"test_table\",\n            await connector.TableSchema.from_class(RowType, primary_key=[\"id\"]),\n        )\n        for row in source_rows:\n            table.declare_row(row=row)\n\n    app = coco.App(\n        coco.AppConfig(name=\"test_insert\", environment=coco_env),\n        declare_target,\n    )\n\n    # Insert\n    source_rows.append(RowType(id=\"1\", name=\"Alice\"))\n    app.update()\n    assert read_data(conn, \"test_table\") == [{\"id\": \"1\", \"name\": \"Alice\"}]\n\n    # Update\n    source_rows[0] = RowType(id=\"1\", name=\"Alice Updated\")\n    app.update()\n    assert read_data(conn, \"test_table\") == [{\"id\": \"1\", \"name\": \"Alice Updated\"}]\n```\n\n**Optional feature tests:**\n\n```python\n@requires_optional\ndef test_vector_support(connector_with_vec: tuple[Connection, Path]) -> None:\n    \"\"\"Tests that require optional dependencies should be skipped when unavailable.\"\"\"\n    # ... test vector functionality ...\n```\n\n**Reference implementations:**\n\n- `python\u002Ftests\u002Fconnectors\u002Ftest_sqlite_target.py` - SQLite tests with vector support\n\n## Attachment Providers\n\nFor targets with auxiliary child states (e.g., indexes on a database table), see [attachments.md](attachments.md) for the full reference on implementing attachment providers.\n\n## Resources\n\nFor complete implementation details and examples, see:\n\n- `docs\u002Fdocs\u002Fadvanced_topics\u002Fcustom_target_connector.md` - Full documentation\n- `python\u002Fcocoindex\u002Fconnectors\u002Flocalfs\u002F_target.py` - File system target connector (sync API, nested directory targets)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fsqlite\u002F_target.py` - SQLite target connector (sync API, two-level table\u002Frow targets, vector support)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fpostgres\u002F_target.py` - PostgreSQL target connector (async API, two-level table\u002Frow targets, vector support, attachment providers)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fdoris\u002F_target.py` - Doris target connector (async API, two-level table\u002Frow targets, Stream Load bulk inserts)\n","# Target Connector\n\n## Overview\n\nA target connector connects CocoIndex's declarative target state system to external systems. It handles synchronization by determining what changed and applying changes to the external system.\n\n## When to Use\n\nUse this skill when creating a new target connector for any external system (databases, file systems, cloud storage, APIs, etc.).\n\n## Key Data Types\n\n### What You Implement\n\n| Type | Purpose |\n| ---- | ------- |\n| `TargetHandler` | Implements `reconcile()` — compares desired state with previous tracking records. Optionally implements `attachment(att_type)` for auxiliary child states. |\n| `TargetActionSink` | Executes actions against the external system |\n| Tracking Record | Persisted state for change detection (typically a frozen dataclass) |\n| Action | Describes what operation to perform on the external system |\n\n### What CocoIndex Provides\n\n| Type | Purpose |\n| ---- | ------- |\n| `TargetStateProvider` | Factory that creates `TargetState` objects from your handler |\n| `TargetState` | Wrapper that holds the key and spec |\n| `register_root_target_states_provider()` | Registers a root handler and returns a provider |\n| `declare_target_state()` | Declares a leaf target state for reconciliation |\n| `declare_target_state_with_child()` | Declares a target state and returns a child provider |\n\n## Implementation Workflow\n\n### Root Target States\n\n1. **Define types**: Key, Spec, TrackingRecord, Action\n2. **Implement TargetHandler**: The `reconcile()` method must be non-blocking\n3. **Create TargetActionSink**: Use `TargetActionSink.from_fn()` or `from_async_fn()`. The callback receives `context_provider: ContextProvider` as its first positional argument, followed by `actions`\n4. **Register provider**: Call `register_root_target_states_provider(name, handler)`\n5. **Create user-facing API**: Wrap the provider in a user-friendly class\n\n### Non-Root (Child) Target States\n\nFor targets nested inside another target (e.g., files inside a directory):\n\n1. Parent sink returns `ChildTargetDef(handler=...)` when executed\n2. Call `declare_target_state_with_child(parent_ts)` to get an unresolved child provider\n3. CocoIndex resolves the child provider when parent's sink executes\n\n### Child Invalidation\n\nFor container targets, set `child_invalidation` in `TargetReconcileOutput` when a container change affects its children:\n\n| Value | When to Use | Effect on Children |\n| ----- | ----------- | ------------------ |\n| `None` (default) | No impact on children (e.g., only new columns added) | Normal change detection |\n| `\"destructive\"` | Container rebuilt from scratch (e.g., table dropped and recreated due to primary key change or table type switch) | All previous tracking records ignored; children treated as new and re-declared |\n| `\"lossy\"` | Data loss possible but container not fully rebuilt (e.g., column removed or type changed) | All children get `prev_may_be_missing=True`, forcing upsert even if content appears unchanged |\n\n**Pattern for two-level (table\u002Frow) connectors using `statediff.diff_composite`:**\n\n```python\n# After computing main_action and column_actions via statediff.diff_composite:\nchild_invalidation: Literal[\"destructive\", \"lossy\"] | None = None\nif main_action == \"replace\":\n    # Table dropped and recreated — all rows are destroyed.\n    child_invalidation = \"destructive\"\nelif main_action is None and any(a != \"insert\" for a in column_actions.values()):\n    # Column changes other than adding new columns may lose existing row data.\n    child_invalidation = \"lossy\"\n\nreturn coco.TargetReconcileOutput(\n    action=_TableAction(...),\n    sink=self._sink,\n    tracking_record=_TableTrackingRecord(...),\n    child_invalidation=child_invalidation,\n)\n```\n\nFor connectors without column-level diffs (e.g., a collection that is either intact or fully replaced), only `\"destructive\"` applies:\n\n```python\nchild_invalidation: Literal[\"destructive\"] | None = (\n    \"destructive\" if main_action == \"replace\" else None\n)\n```\n\n## TargetHandler Protocol\n\n```python\nclass TargetHandler(Protocol[ValueT, TrackingRecordT, OptChildHandlerT]):\n    def reconcile(\n        self,\n        key: StableKey,\n        desired_target_state: ValueT | NonExistenceType,\n        prev_possible_records: Collection[TrackingRecordT],\n        prev_may_be_missing: bool,\n        \u002F,\n    ) -> TargetReconcileOutput[Any, TrackingRecordT, OptChildHandlerT] | None:\n        ...\n\n    # Optional: override to support attachment types\n    def attachment(self, att_type: str) -> TargetHandler | None:\n        return None\n```\n\n**Parameters:**\n\n- `key`: `StableKey` — a union of `None | bool | int | str | bytes | uuid.UUID | Symbol | tuple[StableKey, ...]`\n- `desired_target_state`: What the user declared, or `NON_EXISTENCE` if no longer declared\n- `prev_possible_records`: Tracking records from previous runs (may have multiple)\n- `prev_may_be_missing`: If `True`, the target state might not exist in the external system\n\n**Returns:**\n\n- `TargetReconcileOutput(action, sink, tracking_record, child_invalidation=None)` if an action is needed (generic params: `[ActionT, TrackingRecordT, OptChildHandlerT]`)\n- `None` if no changes are required\n\nThe optional `child_invalidation` field is only relevant for container targets — see [Child Invalidation](#child-invalidation).\n\n**Important:** The `reconcile()` method must be non-blocking. It should only compare states and return an action — actual I\u002FO happens in the sink.\n\n## Best Practices\n\n### Use `ContextKey` for External Resource Identity\n\nWhen a target connector manages state in an external resource (database, object store, etc.), use a `ContextKey` string as part of the target state key — not connection parameters like host, port, or credentials.\n\n**Why:** Target state keys must be stable across runs for correct reconciliation. CocoIndex uses keys to match current declarations with previously tracked states. If the key is stable, previously tracked states are associated with the current target, so CocoIndex can correctly reconcile — e.g., deleting rows that are no longer declared. If the key changes (because a connection parameter changed), CocoIndex cannot associate previous tracked states with the current target, and treats the target as being in a cleared state — losing the ability to clean up old data.\n\n**Pattern:**\n\n```python\n# User creates a stable logical name for the resource\ndb = coco.ContextKey[asyncpg.Pool](\"my_pg\")\n\n# Target connector uses db.key (the string \"my_pg\") in the target state key\nclass _TableKey(NamedTuple):\n    db_key: str           # Stable — from ContextKey.key\n    schema_name: str | None\n    table_name: str\n\nkey = _TableKey(db_key=db.key, ...)\n\n# At action time, resolve the live connection from context_provider\npool = context_provider.get(key.db_key, asyncpg.Pool)\n```\n\nThis decouples target identity from transient connection details — changing a password, switching replicas, or rotating credentials won't invalidate tracked states.\n\n**Resolve connections at action time, never at declare time.** Target states outlive the code that declared them: when a declaration disappears or an app is dropped, CocoIndex generates delete actions in a run where the mount\u002Fdeclare code never executes — only the persisted key and the current environment's `ContextProvider` are available then. Don't capture a live connection at declare time; resolve in the sink, then pass the typed connection down to child handlers directly (store `_pool: asyncpg.Pool`, not the key string).\n\n**Reference:** See `_TableKey` in `python\u002Fcocoindex\u002Fconnectors\u002Fpostgres\u002F_target.py` and `python\u002Fcocoindex\u002Fconnectors\u002Fsurrealdb\u002F_target.py`.\n\n### Idempotent Actions\n\nActions should be idempotent:\n\n```python\n# Good\npath.mkdir(parents=True, exist_ok=True)\npath.unlink(missing_ok=True)\nawait conn.execute(\"INSERT ... ON CONFLICT DO UPDATE ...\")\n\n# Bad\npath.mkdir()  # Fails if exists\nawait conn.execute(\"INSERT ...\")  # Fails on duplicate key\n```\n\n### Handle Multiple Previous States\n\nDue to interrupted updates, `prev_possible_records` may contain multiple records:\n\n```python\nif not prev_may_be_missing and all(\n    prev.fingerprint == target_fp for prev in prev_possible_records\n):\n    return None  # Safe to skip\n```\n\n### Fingerprinting for Change Detection\n\nUse the `connectorkits.fingerprint` utilities for content-based change detection:\n\n```python\nfrom cocoindex.connectorkits.fingerprint import fingerprint_bytes, fingerprint_str, fingerprint_object\n\n# For raw bytes\nfp = fingerprint_bytes(content)\n\n# For strings\nfp = fingerprint_str(text)\n\n# For arbitrary objects (uses memo key mechanism)\nfp = fingerprint_object(obj)\n```\n\n### Shared Action Sinks\n\nCreate module-level shared sinks when all handler instances use the same action logic. The callback must accept `context_provider: ContextProvider` as its first positional argument:\n\n```python\ndef _apply_actions(\n    context_provider: ContextProvider, actions: Sequence[MyAction]\n) -> list[coco.ChildTargetDef[MyChildHandler] | None] | None:\n    for action in actions:\n        conn = context_provider.get(action.key.db_key, ConnType)\n        ...\n\n_shared_sink = coco.TargetActionSink.from_fn(_apply_actions)\n```\n\nSink identity is **value-based**: sinks whose callbacks compare equal share one\nbatching identity, meaning their actions are batched and applied together (and\na batch is the natural transaction boundary for transactional stores). For a\nsink scoped to an external resource — e.g. one sink per database so all of that\ndatabase's writes share a transaction — make the callback a frozen dataclass\nkeyed by the resource and construct it on the fly in `reconcile()`; no\nmodule-level sink registry is needed:\n\n```python\n@dataclasses.dataclass(frozen=True)\nclass _DbSink:\n    db_key: str\n\n    async def __call__(\n        self, context_provider: ContextProvider, actions: Sequence[MyAction], \u002F\n    ) -> None:\n        conn = context_provider.get(self.db_key, ConnType)\n        ...\n\n# In reconcile(): equal callbacks yield the same sink identity.\nsink = coco.TargetActionSink.from_async_fn(_DbSink(key.db_key))\n```\n\nAn idle sink identity (no live sink object, no pending actions) is released\nautomatically, so per-resource sinks do not accumulate for the process\nlifetime.\n\n### Input Safety\n\nWhen building queries from user-provided names (table, column, index) or values (record IDs, keys), you must guard against injection and ensure correctness. See [input_safety.md](input_safety.md) for patterns on identifier validation, parameterized queries, and value escaping.\n\n## Completion Checklist\n\nAfter implementing the connector code, complete these additional steps:\n\n### 1. Optional Dependencies\n\nIf the connector requires third-party packages, update `pyproject.toml`:\n\n```toml\n[project.optional-dependencies]\n# Add new optional dependency group\nmyconnector = [\"some-package>=1.0.0\"]\n\n# Add to the 'all' group\nall = [\n    # ... existing deps ...\n    \"some-package>=1.0.0\",\n]\n\n[[tool.mypy.overrides]]\n# Add to mypy ignore list if package lacks type stubs\nmodule = [\n    # ... existing modules ...\n    \"some_package\",\n    \"some_package.*\",\n]\nignore_missing_imports = true\n```\n\n### 2. Documentation\n\nCreate connector documentation at `docs\u002Fdocs\u002Fconnectors\u002F\u003Cconnector_name>.md`:\n\n- Follow the structure of existing connector docs (e.g., `postgres.md`, `sqlite.md`)\n- Include: connection setup, target state APIs, schema definition, type mappings, examples\n- Add a note about optional dependencies if applicable\n\nUpdate `docs\u002Fsidebars.ts` to include the new connector:\n\n```typescript\n{\n  type: 'category',\n  label: 'Connectors',\n  items: [\n    \u002F\u002F ... existing connectors ...\n    'connectors\u002F\u003Cconnector_name>',  \u002F\u002F Add in alphabetical order\n  ],\n},\n```\n\n### 3. Tests\n\nCreate tests at `python\u002Ftests\u002Fconnectors\u002Ftest_\u003Cconnector_name>_target.py`:\n\n**Test structure:**\n\n```python\nimport pytest\nimport cocoindex as coco\nfrom tests import common\n\n# Check for optional dependency availability\ntry:\n    import optional_package\n    HAS_OPTIONAL = True\nexcept ImportError:\n    HAS_OPTIONAL = False\n\nrequires_optional = pytest.mark.skipif(\n    not HAS_OPTIONAL, reason=\"optional-package is not installed\"\n)\n\ncoco_env = common.create_test_env(__file__)\n```\n\n**Required test cases:**\n\n| Category | Test Cases |\n| -------- | ---------- |\n| Basic CRUD | Create target, insert data, update data, delete data |\n| Schema | Different column types, schema with extra columns |\n| Lifecycle | Drop\u002Fcleanup when target no longer declared |\n| Optimization | No-op when data unchanged |\n| Multiple targets | Multiple tables\u002Fdirectories in same connection |\n| User-managed | `managed_by=\"user\"` mode if supported |\n| Optional features | Vector support, special types (skip if dependency missing) |\n\n**Test pattern:**\n\n```python\nDB_KEY = coco.ContextKey[connector.ConnectionType](\"test_db\")\n\ndef test_insert_and_update(connector_fixture: tuple[Connection, Path]) -> None:\n    conn, _ = connector_fixture\n    source_rows: list[RowType] = []\n\n    coco_env.context_provider.provide(DB_KEY, conn)\n\n    async def declare_target() -> None:\n        table = await coco.use_mount(\n            coco.component_subpath(\"setup\", \"table\"),\n            connector.declare_table_target,\n            DB_KEY,\n            \"test_table\",\n            await connector.TableSchema.from_class(RowType, primary_key=[\"id\"]),\n        )\n        for row in source_rows:\n            table.declare_row(row=row)\n\n    app = coco.App(\n        coco.AppConfig(name=\"test_insert\", environment=coco_env),\n        declare_target,\n    )\n\n    # Insert\n    source_rows.append(RowType(id=\"1\", name=\"Alice\"))\n    app.update()\n    assert read_data(conn, \"test_table\") == [{\"id\": \"1\", \"name\": \"Alice\"}]\n\n    # Update\n    source_rows[0] = RowType(id=\"1\", name=\"Alice Updated\")\n    app.update()\n    assert read_data(conn, \"test_table\") == [{\"id\": \"1\", \"name\": \"Alice Updated\"}]\n```\n\n**Optional feature tests:**\n\n```python\n@requires_optional\ndef test_vector_support(connector_with_vec: tuple[Connection, Path]) -> None:\n    \"\"\"Tests that require optional dependencies should be skipped when unavailable.\"\"\"\n    # ... test vector functionality ...\n```\n\n**Reference implementations:**\n\n- `python\u002Ftests\u002Fconnectors\u002Ftest_sqlite_target.py` - SQLite tests with vector support\n\n## Attachment Providers\n\nFor targets with auxiliary child states (e.g., indexes on a database table), see [attachments.md](attachments.md) for the full reference on implementing attachment providers.\n\n## Resources\n\nFor complete implementation details and examples, see:\n\n- `docs\u002Fdocs\u002Fadvanced_topics\u002Fcustom_target_connector.md` - Full documentation\n- `python\u002Fcocoindex\u002Fconnectors\u002Flocalfs\u002F_target.py` - File system target connector (sync API, nested directory targets)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fsqlite\u002F_target.py` - SQLite target connector (sync API, two-level table\u002Frow targets, vector support)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fpostgres\u002F_target.py` - PostgreSQL target connector (async API, two-level table\u002Frow targets, vector support, attachment providers)\n- `python\u002Fcocoindex\u002Fconnectors\u002Fdoris\u002F_target.py` - Doris target connector (async API, two-level table\u002Frow targets, Stream Load bulk inserts)\n",{"name":5,"description":7},"main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Ftarget-connector",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill target-connector",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill target-connector",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill target-connector","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Ftarget-connector\u002FSKILL.md",true,[46,52],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"attachments.md","REFERENCE","参考文档",5608,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Ftarget-connector\u002Fattachments.md",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"input_safety.md",3197,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Ftarget-connector\u002Finput_safety.md",[57,65,70,77,84,91],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":64},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":66,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":64},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":64},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":64},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":64},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":64},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]