From 99988da5c448500b565fb2d399be1620a418d0cb Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 11 Nov 2026 01:53:04 +0800 Subject: [PATCH 01/27] feat(memory): make keyed remember_memory writes idempotent Add an optional idempotency_key to remember_memory. A retry with the same key and content replays the original creation; different content returns 409 idempotency_conflict. Keys live 24 hours on the database clock in a per-Scope, per-principal namespace and are stored as digests only. Adds migration v1_5_2_001 for SQLite and MySQL-dialect backends, exposes the field over HTTP, the SDK, and MCP, keeps it hidden in Dify, and documents the behavior in both locales. Closes #2521 --- desktop/src-tauri/src/transport/api.rs | 1 + .../src-tauri/src/transport/operations.json | 2 +- desktop/src-tauri/src/transport/wire.rs | 11 + desktop/ui/src/generated/api.d.ts | 4 +- desktop/ui/src/generated/ipc.ts | 6 +- desktop/ui/src/generated/operations.ts | 2 +- docs/en/docs/operate/database-migrations.md | 15 +- docs/en/docs/operate/observability.md | 5 + docs/en/docs/operate/troubleshoot.md | 5 +- docs/en/docs/workflows/atomic-memory.md | 28 ++ docs/en/rfcs/1437_source_artifact_rest_api.md | 9 + docs/en/rfcs/1809-atomic-memory.md | 172 ++++++- docs/zh/docs/operate/database-migrations.md | 15 +- docs/zh/docs/operate/observability.md | 4 + docs/zh/docs/operate/troubleshoot.md | 4 +- docs/zh/docs/workflows/atomic-memory.md | 24 + docs/zh/rfcs/1437_source_artifact_rest_api.md | 8 + docs/zh/rfcs/1809-atomic-memory.md | 142 +++++- .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../plugin/powercontext_dify/contract.json | 14 + .../dify/plugin/powercontext_dify/policy.py | 2 + .../dify/tests/test_plugin_contract.py | 2 + .../dsh/plugins/powercontext/lib/index.js | 1 + .../references/scope-memory.md | 2 + .../plugins/powercontext/src/diagnostics.ts | 3 + .../powercontext/tests/diagnostics.spec.ts | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + .../references/scope-memory.md | 2 + openapi/powercontext.yaml | 11 +- release/upgrade-support.json | 4 +- .../persistence/atomic_memory_idempotency.py | 197 ++++++++ .../migrations/server_resources/manifest.json | 16 +- .../mysql/versions/v1_5_2_001.py | 24 + .../schemas/mysql-v1_5_2_001.json | 370 ++++++++++++++ .../schemas/sqlite-v1_5_2_001.json | 6 + .../v1_5_2_001_atomic_memory_idempotency.py | 30 ++ .../server_sources/1.4.0/manifest.json | 16 +- .../builtin/persistence/records.py | 149 +++++- .../builtin/persistence/tables.py | 21 + src/powercontext/builtin/records.py | 10 + .../builtin/runtime/application.py | 46 +- src/powercontext/http/_generated/models.py | 9 + src/powercontext/http/_generated/schema.py | 61 ++- src/powercontext/server/app.py | 1 + src/powercontext/server/mcp.py | 5 +- .../test_atomic_description_vector_layout.py | 16 +- .../test_atomic_evidence_upgrade_history.py | 4 +- .../test_full_server_migrations.py | 3 +- .../test_mysql_initialization_preflight.py | 2 +- .../test_mysql_migration_runner.py | 16 +- .../test_portable_storage_migration.py | 18 +- .../test_release140_server_migrations.py | 3 +- .../test_atomic_memory_description_upgrade.py | 4 +- tests/e2e/test_remember_memory_idempotency.py | 472 ++++++++++++++++++ tests/e2e/test_source_citation_locators.py | 3 +- tests/e2e/test_source_write.py | 2 +- .../native/test_oceanbase_engine_recovery.py | 2 +- .../native/test_personal_service_lifecycle.py | 2 +- tests/pydantic_ai_adapter/test_toolset.py | 1 + tests/release_upgrades/README.md | 2 +- tests/test_managed_atomic_maintenance.py | 4 +- tests/test_managed_processing_maintenance.py | 2 +- tests/test_mcp.py | 3 +- tests/test_migration_revision_names.py | 6 +- .../test_registered_source_maintenance_cli.py | 2 +- 73 files changed, 1953 insertions(+), 95 deletions(-) create mode 100644 src/powercontext/builtin/persistence/atomic_memory_idempotency.py create mode 100644 src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_5_2_001.py create mode 100644 src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_5_2_001.json create mode 100644 src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_5_2_001.json create mode 100644 src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_5_2_001_atomic_memory_idempotency.py create mode 100644 tests/e2e/test_remember_memory_idempotency.py diff --git a/desktop/src-tauri/src/transport/api.rs b/desktop/src-tauri/src/transport/api.rs index 8cacb3a510..f12fae2f3a 100644 --- a/desktop/src-tauri/src/transport/api.rs +++ b/desktop/src-tauri/src/transport/api.rs @@ -506,6 +506,7 @@ impl ServerApi { reason: None, expected_revision: None, description: None, + idempotency_key: None, }; let body = serde_json::to_value(request) .map_err(|_| ApiFailure::before(SafeError::InvalidInput))?; diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index 915c139259..b056ae772b 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "93b733bda25ab4db0e883f63a2571334c7c1dfb3af68a18b330384fd344c2d4c", + "contractSha256": "e0e147b69008320adfe9d8d46183fa73b3f3ede6f815205fdf51b920438e14d7", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/src-tauri/src/transport/wire.rs b/desktop/src-tauri/src/transport/wire.rs index d199661f9f..cf5e18a417 100644 --- a/desktop/src-tauri/src/transport/wire.rs +++ b/desktop/src-tauri/src/transport/wire.rs @@ -2349,6 +2349,16 @@ pub struct RememberMemoryRequest { skip_serializing_if = "Option::is_none" )] pub description: Option>, + /// Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + #[ts(optional)] + #[ts(type = "string | null")] + #[serde( + rename = "idempotency_key", + default, + with = "::serde_with::rust::double_option", + skip_serializing_if = "Option::is_none" + )] + pub idempotency_key: Option>, } impl RememberMemoryRequest { @@ -2361,6 +2371,7 @@ impl RememberMemoryRequest { reason: None, expected_revision: None, description: None, + idempotency_key: None, } } } diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index 888efc0493..17e242fd78 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -1154,7 +1154,7 @@ export interface paths { put?: never; /** * Create Atomic Memory through the legacy remember input - * @description Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. + * @description Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. With idempotency_key, a retry of the same creation within 24 hours replays the original response, and reuse of the key for different content returns 409 idempotency_conflict with details.kind memory_idempotency_key. */ post: operations["remember_memory"]; delete?: never; @@ -5299,6 +5299,8 @@ export interface components { expected_revision?: number | null; /** @description Optional supplied single-line summary. When omitted, the Server stores a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. */ description?: string | null; + /** @description Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. */ + idempotency_key?: string | null; }; RetireMemoryEntryRequest: { scope_id: string; diff --git a/desktop/ui/src/generated/ipc.ts b/desktop/ui/src/generated/ipc.ts index d758833197..db415776b7 100644 --- a/desktop/ui/src/generated/ipc.ts +++ b/desktop/ui/src/generated/ipc.ts @@ -355,7 +355,11 @@ text: string, reason?: string | null, expected_revision?: number | null, /** * Optional supplied single-line summary. When omitted, the Server stores a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. */ -description?: string | null, }; +description?: string | null, +/** + * Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + */ +idempotency_key?: string | null, }; export type ResolvedUsagePeriod = { preset: StatsPeriod, start_date: string, end_date: string, timezone: Timezone, }; export type Role = "leader" | "standby"; export type ScopeDescriptor = { scope_id: string, title: string, summary: string, parent_scope_id?: string | null, context_references: Array, external_references: Array, version: number, }; diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index dc02c35b11..323a17900c 100644 --- a/desktop/ui/src/generated/operations.ts +++ b/desktop/ui/src/generated/operations.ts @@ -15,7 +15,7 @@ */ // Generated from openapi/powercontext.yaml. Do not edit. -export const contractSha256 = "93b733bda25ab4db0e883f63a2571334c7c1dfb3af68a18b330384fd344c2d4c"; +export const contractSha256 = "e0e147b69008320adfe9d8d46183fa73b3f3ede6f815205fdf51b920438e14d7"; export const operations = { "get_liveness": { "method": "GET", diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index 33f94f2e89..ea2395cfa0 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -17,8 +17,8 @@ The design follows [RFC #1771](https://github.com/oceanbase/powercontext/pull/17 The full Server framework uses two normalization checkpoints before its shared migration chain for the PowerContext 1.5.1 target (stored compatibility IDs shown below): -- **1.3.0:** `s1300 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004`. -- **1.4.0:** `r1400 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004` through a separate frozen source bridge. +- **1.3.0:** `s1300 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004 → v1_5_2_001`. +- **1.4.0:** `r1400 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004 → v1_5_2_001` through a separate frozen source bridge. Application release numbers and schema revisions are distinct. The 1.4.0 release is not the `s1400` checkpoint: its existing Candidate schema is current, but its Topic attempt storage still needs the registered bridge. @@ -91,6 +91,8 @@ Revision `v1_4_1_004` registers `pc_access_owner_recovery` for durable Artifact Revision `v1_4_1_005` adds nullable `pc_atomic_memory_current.description` metadata for text and vector profiles. Existing managed databases require explicit migration; startup does not alter this column. The additive revision leaves historical Artifact bytes unchanged and existing descriptions null until a new write or explicit projection rebuild copies authoritative metadata. +Revision `v1_5_2_001` registers `pc_atomic_memory_idempotency`, the retry receipts for keyed `remember_memory` creations, with an index on their expiry time. Existing managed databases require explicit migration before Server startup; the migration creates an empty table and rewrites no existing data. A receipt stores SHA-256 digests of the key namespace and the created content, the bound Artifact revision and the creation state version; it stores neither the raw key, the principal ID nor the memory body. Receipts expire 24 hours after creation and are removed in bounded batches. See [Atomic Memory](../workflows/atomic-memory.md) for retry behavior. + Revision `v1_5_0_004` registers `pc_artifact_source_locators`, an optional relation keyed by the existing Artifact Revision and Source-edge ordinal. Existing managed databases require explicit migration before Server startup. The migration preserves existing lineage rows, exact identities and historical payloads without rewriting them or backfilling locators. Atomic Memory embeddings remain unchanged; no re-embedding is required. See [Source citation locators](../workflows/sources.md) for locator behavior. Revision `v1_4_1_006` registers `pc_source_write_plugins` for persisted Source write plugin declarations. @@ -163,12 +165,13 @@ Sequence `000` identifies a registered historical baseline; upgrade steps start | `v1_5_0_002` | 1.5.0 | 2 | `v1_5_0_002` | Retained Source evidence and historical validation | | `v1_5_0_003` | 1.5.0 | 3 | `v1_5_0_003` | Disposable exact-revision evidence projection | | `v1_5_0_004` | 1.5.0 | 4 | `v1_5_0_004` | Source citation position locators | +| `v1_5_2_001` | 1.5.2 | 1 | `v1_5_2_001` | Keyed remember_memory retry receipts | -Both registered source paths reach `v1_5_0_004`; only 1.3.0 is selected for CI upgrade acceptance: +Both registered source paths reach `v1_5_2_001`; only 1.3.0 is selected for CI upgrade acceptance: ```text -1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 +1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_2_001 +1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_2_001 ``` `status` and `plan` show `source_migration`, `target_migration` and `pending_migrations` @@ -190,7 +193,7 @@ existing plans and original backups usable. Partial prototype bundles keep their For a new Server migration, use the release-based name directly as its Alembic `revision` and register its schema, domain steps and recovery checkpoints as usual. `down_revision` must reference -the actual preceding ID (`v1_5_0_004` when appending directly to the current head), even if that ID has +the actual preceding ID (`v1_5_2_001` when appending directly to the current head), even if that ID has a display alias. The framework follows this registered chain, not lexical name ordering. Already registered names and release assignments stay immutable; a version bump must not rename history. diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index 2f9bd0b159..71568e4a4e 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -92,6 +92,11 @@ declaration bodies, or requested content. Its `unit` is the retained fact (`sour `evidence_mismatch`. Integrity causes are emitted at `WARNING`; expected historical gaps stay at `INFO` or `DEBUG`. Integrity causes such as `manifest_conflict` are alertable and distinct from an absent declaration. +The `atomic_memory.idempotency.cleanup_failed` event reports that a keyed `remember_memory` creation committed but +the bounded removal of expired retry keys that follows it failed. The creation and its response are unaffected, and a +later keyed creation retries the removal. It is emitted at `WARNING` with `operation` `remember_memory`, `unit` +`atomic-memory`, `outcome` `failure`, and `exception_type`; it never carries keys, principals, or memory content. + Server roles are `all` (API and supervisor), `api`, and `background`; child processes use `worker`. Explicit logging configuration without a deployment role uses `server`. JSON identity fields correspond to trace resource attributes `service.name`, `service.version`, `service.instance.id`, and `powercontext.service.role`. `service_version` is absent diff --git a/docs/en/docs/operate/troubleshoot.md b/docs/en/docs/operate/troubleshoot.md index 0171e17eb1..9a4e9d4bf5 100644 --- a/docs/en/docs/operate/troubleshoot.md +++ b/docs/en/docs/operate/troubleshoot.md @@ -261,7 +261,8 @@ so the previous database remains available for recovery: If the source predates the three Skill lifecycle tables (`pc_skill_packages`, `pc_agent_skill_targets`, and `pc_skill_publications`), the Profile tables, `pc_topic_memory_work_budgets`, `pc_topic_memory_work_blocks`, `pc_recall_effort_daily`, `pc_receipt_migration_review`, `pc_context_bootstrap_receipts`, - `pc_decision_observations`, or `pc_artifact_source_locators`, remove the absent tables from their respective layers. + `pc_decision_observations`, `pc_artifact_source_locators`, or `pc_atomic_memory_idempotency`, remove the absent + tables from their respective layers. When a work-budget table exists, restore it together with Cursors so failure allowances survive the migration. Restore work-attempt records as well to preserve block identities, diagnostics and accepted retry receipts. @@ -269,7 +270,7 @@ so the previous database remains available for recovery: ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_write_plugins,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_artifact_family_schemas,pc_artifact_vector_spaces,pc_artifact_search_states' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_write_plugins,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_artifact_family_schemas,pc_artifact_vector_spaces,pc_artifact_search_states,pc_atomic_memory_idempotency' \ -f ``` diff --git a/docs/en/docs/workflows/atomic-memory.md b/docs/en/docs/workflows/atomic-memory.md index fee09467b3..40e7388e50 100644 --- a/docs/en/docs/workflows/atomic-memory.md +++ b/docs/en/docs/workflows/atomic-memory.md @@ -52,6 +52,34 @@ Submit complete content to `PUT /v1/scopes/S/artifacts/atomic-memory/M`, sending Success creates the next content revision. Missing `If-Match` returns `428 precondition_required`; a stale value returns `412 revision_conflict`. Read and reconcile the content before submitting again. +## Retry remember_memory safely + +`POST /v1/memory/remember` (`remember_memory`) creates a new memory on every call. To retry a call whose response was +lost without creating a duplicate, send an `idempotency_key`: 1 to 256 printable ASCII characters other than space. +Generate a fresh unguessable key, such as a UUID, for each logical write, and reuse it only to retry that write: + +```json +{ + "scope_id": "S", + "kind": "preference", + "text": "Prefer short pull requests.", + "idempotency_key": "3f0c8f5e-7a51-4c1e-9a43-0f1e2b7d9c60" +} +``` + +Keys are scoped to the Scope and the authenticated principal; with access control disabled, all callers share one +namespace per Scope. Within 24 hours of the creation, a request with the same key and the same stored content returns +the original response: the same `ArtifactRef` of revision 1 and the state recorded at creation, even if the memory has +since been revised, forgotten or merged. Read current state through the Atomic Memory read operations. Content is the +same when the normalized `text`, `kind`, `description` (an omitted description equals the default derived from the +text) and content schema match; `reason` is not compared. The same key with different content returns +`409 idempotency_conflict` with `error.details.kind: "memory_idempotency_key"` and writes nothing; use a new key for +the new content. After 24 hours the key behaves as unused and creates a new memory. + +Each replay rechecks the caller's current authorization. The server stores only digests of the key namespace and +content, never the raw key or memory body. Neither the server, the Python SDK nor the MCP tool generates keys or +retries automatically, and `expected_revision` keeps its existing behavior. + ## Current state and forgetting `GET /v1/scopes/S/artifacts/atomic-memory/M/state` returns the current exact `artifact` reference, `state`, diff --git a/docs/en/rfcs/1437_source_artifact_rest_api.md b/docs/en/rfcs/1437_source_artifact_rest_api.md index 0c1906e191..3346284209 100644 --- a/docs/en/rfcs/1437_source_artifact_rest_api.md +++ b/docs/en/rfcs/1437_source_artifact_rest_api.md @@ -475,6 +475,12 @@ return `422` instead of being ignored. creates a new resource. After a client timeout, the caller must confirm the result from business context and cannot assume that retry is idempotent. +Explicit Atomic Memory creation through `remember_memory` is outside these operations and is the only Atomic Memory +creation path with an idempotency key. The "Idempotent explicit creation" section of +[RFC 1809](1809-atomic-memory.md) defines its optional `idempotency_key` request body field, namespace, request +digest, replay, and retention. That field does not apply to Source Create or Artifact Create, and no operation accepts +an `Idempotency-Key` header. Creating an Atomic Memory through Artifact Create remains non-idempotent. + ## Status and error model | Status | Scenario | @@ -510,6 +516,9 @@ The common error body is: Errors must not reveal whether a resource in another Scope exists. Permission and invisibility scenarios return `403` or `404` according to the common security policy. +For `remember_memory`, an idempotency key already bound to a different request returns `409` with the existing code +`idempotency_conflict` and `details.kind` set to `memory_idempotency_key`. No new error code is introduced for it. + ## OpenAPI contract `openapi/powercontext.yaml` is the sole source of truth for the HTTP contract. The principal schemas are: diff --git a/docs/en/rfcs/1809-atomic-memory.md b/docs/en/rfcs/1809-atomic-memory.md index 5787447722..801cad2a64 100644 --- a/docs/en/rfcs/1809-atomic-memory.md +++ b/docs/en/rfcs/1809-atomic-memory.md @@ -193,6 +193,163 @@ During restoration, the server checks current content versions, states, and merg transaction. A preview identifier adds validation against the preview; requests without one use current state. The checked conditions must still hold at commit, without overwriting intervening updates. +## Idempotent explicit creation + +`remember_memory` is the only Atomic Memory creation entry point that accepts an idempotency key. It lets a caller +that lost a response retry one explicit creation without creating a second memory. Requests without a key keep their +existing behavior: every successful call creates a new memory. Revision, forgetting, restoration, merging, extraction, +Source processing, and RFC 1437's generic Artifact Create accept no key. The server never deduplicates by content and +never retries on a caller's behalf. + +### Request field and namespace + +`RememberMemoryRequest` adds optional `idempotency_key`: 1 to 256 printable ASCII characters other than space, +matching `^[!-~]{1,256}$`. The server compares keys byte for byte without trimming, case folding, or other +normalization. Omitting the field or passing `null` means no key. A key that does not match the pattern is rejected +with `422` under the common request-validation policy before any lookup or write: `invalid_request`, or +`invalid_access_request` when enforced access control validates the request body first. + +A key is unique within one namespace: the operation `remember_memory`, `scope_id`, and the authenticated principal's +type and ID. When access control is disabled, the principal component is empty, so all callers of that deployment share +one namespace per Scope. The same key in another Scope, from another principal, or for another operation names an +independent write. The HTTP API, Python SDK, and MCP tool carry the field unchanged; none of them generates keys or +retries automatically. Callers generate a fresh unguessable key, such as a UUID, for each logical write and reuse it +only to retry that write. The MCP server instructions and the shared Skill reference give models the same guidance, +and tell them to use a new key after a conflict. The Dify `pc_remember` tool does not expose the field. + +The server stores only a SHA-256 digest of the namespace and key, never the raw key or the principal ID in clear. + +### Request digest + +The request digest identifies a logical write by the revision 1 content it produces. Version 1 is the lowercase +hexadecimal SHA-256 of the RFC 8785 serialization of a JSON object with exactly these four members, matching the +`AtomicMemoryContent` the writer would store: + +- `schema` is `powercontext.atomic-memory.v1`. +- `kind` is the submitted value, unchanged, as the writer stores it. +- `text` is the result of the writer's `normalize_text`: Unicode NFC, then removal of leading and trailing whitespace. +- `description` is the submitted value when present. When the field is omitted or `null`, it is the default + description the writer derives from the normalized text. + +The object has no `creation` member, because an explicit creation never carries merge metadata. Strings are hashed as +they would be stored: apart from `text`, no Unicode normalization is applied, so a helper that normalizes every string +must not compute this digest. Changing the member set or the behavior of `normalize_text` or of the default +description requires a new digest version. + +Omitting `description`, passing `null`, and passing exactly the default description therefore produce one digest, +because they store the same content. `reason` is not part of the written content and is ignored. `expected_revision` +must be omitted or `null`; a non-null value is rejected before lookup. `scope_id` and the principal belong to the +namespace, not the digest. + +The Source written for revision 1 records the command of the request that performed the creation. A retry whose text +differs only by normalization replays that creation and does not rewrite its Source. Each key record stores its digest +version. A new digest version applies only to new keys; the server keeps computing every version that can still appear +within the retention period. + +### Results + +| Lookup in the key's namespace | Result | +| --- | --- | +| No unexpired record | Create the memory as without a key, and bind the key in the same transaction. | +| Record with the same digest | Replay the original result. Prepare no Embedding and write nothing. | +| Record with a different digest | Return `409 idempotency_conflict` with details `{"kind": "memory_idempotency_key"}`. Write nothing. | + +A replay returns the same `MemoryMutationResponse` as the original creation: `changed: true` and one record with the +exact `ArtifactRef` of revision 1, its `kind` and `text`, `state: active`, the state version recorded at creation, and +`merged_into_id: null`. Content comes from the immutable revision 1, and the creation-time state comes from the key +record. A creation currently always yields revision 1, state version 0, and no merge target; the key record stores the +revision and state version so that a replay does not depend on that invariant. Later revision, forgetting, merging, +restoration, or retirement does not change the replay, and a replay never substitutes the current head. Callers read +current state through the Atomic Memory read operations. + +For a keyed creation, the original response is built through the same exact-revision read, so a revision committed +concurrently between creation and response changes neither result. Requests without a key keep their existing response +construction. The response carries no replay marker; a caller that must distinguish a replay compares the returned +identity with its own records. + +### Authorization + +The `scope.contribute` check runs before key lookup, as for any creation. A denied caller receives `403` without +learning whether the key exists. Because the principal is part of the namespace, another principal cannot hit or probe +a key. + +A replay reads revision 1 with the caller's current context through the same authorized exact-revision read as Get +Artifact Revision for the `atomic-memory` Family. If the caller can no longer read that memory, for example after its +access was revoked, the request returns that read's error under the common security policy: `403 forbidden` for a +denial, or `503 artifact_owner_pending` while ownership is not yet established. `404 artifact_not_found` occurs only if +revision 1 cannot be found, which does not happen in normal operation because revision 1 is immutable and is never +physically deleted. It neither discloses the record nor creates a new memory, and the key stays bound until it expires. + +A conflict discloses only that the caller's own key in that Scope was already used for different content. Other +operations also return `idempotency_conflict`, so callers identify this case by `details.kind`. + +### Atomicity and failures + +Request validation, authorization, writer validation, and digest computation finish before lookup. Lookup is one +primary-key read in its own read transaction and uses the database clock. Only a miss proceeds to the existing +preparation outside the write transaction, including Embedding generation. + +The write transaction first deletes the record for the same namespace only if its `expires_at` is not later than the +current database time, so a live key committed concurrently is never removed. It then inserts the key record, writes +the Sources, revision 1, governance state, Owner, and search and evidence projections as before, and commits everything +together. The key record holds the namespace digest, request digest and its version, +`scope_id`, `artifact_id`, revision, creation-time state version, `created_at`, and `expires_at`. It stores no memory +body. + +- A validation, authorization, or preparation failure, or cancellation before commit, leaves no key, Source, + Artifact, Owner, or projection. A retry with the key runs the creation again. +- A failure inside the write transaction rolls back the key with everything else. +- A response lost after commit, including a cancellation whose outcome the caller cannot observe, leaves the key bound. + A retry replays the committed result. +- Concurrent requests with one key race on the key record's primary key. The loser rolls back, rereads the key in a + new transaction, and returns the replay or conflict from the table above. If the reread finds no record, the + integrity error was unrelated and is returned unchanged. The loser's prepared Embedding is discarded. + +Uniqueness comes from the database constraint rather than an in-process lock, so it holds across connections, +processes, and Server instances on SQLite and on OceanBase/seekdb. + +### Retention and cleanup + +A key is retained for 24 hours from the database time at which its creating transaction inserts it. Replays do not +extend retention. A record whose `expires_at` is not later than the current database time is treated as absent: the +same key then starts a new creation and replaces the expired record inside that creation's transaction. A caller must +not expect a replay after 24 hours. + +After a keyed creation commits, the server deletes at most 32 expired records in a separate short transaction: one +range read on the `expires_at` index with a limit of 32, then one delete by primary key that rechecks expiry. Cleanup +failure does not change the creation result. Each keyed creation adds one record and removes up to 32 expired ones, so +an expired backlog shrinks while keyed writes continue. Requests without a key do not touch the table. No operation +scans the whole table: lookup and binding use the primary key, and cleanup uses the expiry index. + +### Storage and upgrade + +Key records live in the new table `pc_atomic_memory_idempotency`, with the namespace digest as the primary key and a +secondary index on `expires_at`. Fixed-width digests keep the key within MySQL-compatible index limits. A new revision +of the server-resource migration chain adds the table with SQLite and MySQL schemas, manifest resources, and SQLite +fingerprint. Published revisions do not change. + +At Server startup, an empty persistent SQLite or seekdb database is initialized through the full revision chain, +including the new revision. OceanBase requires an explicit `powercontext server db-migrate` job even for an empty +database. A managed database at an earlier revision makes Server startup fail with a migration-required error until +`powercontext server db-migrate apply` succeeds; startup never upgrades it implicitly. Only unmanaged storage, such as +in-memory SQLite, creates the table from the built-in table registry. Restarting or applying the upgrade again +preserves existing records. + +### Acceptance + +| Scenario | Expected result | +| --- | --- | +| Same key and digest | One Artifact and Source, plus one Owner when access control is enabled; every response equals the first. | +| Same key, different digest | `409 idempotency_conflict`; the original memory, Source, Owner, and projections are unchanged. | +| No key; one key in another Scope or from another principal; different keys | Independent creations. | +| `description` omitted, `null`, or equal to the default; text differing only by NFC or outer whitespace | One digest; replay. | +| Concurrent requests on separate connections or processes | Exactly one creation; the others replay or conflict by digest. | +| Failure or cancellation before commit; response lost after commit | No orphaned rows; a retry creates once or replays the commit. | +| Restart, then later revision, forgetting, merging, or retirement | The replay still returns revision 1 and the creation-time state. | +| Revoked access; another principal | No disclosure and no write: the exact-read error, or an independent namespace. | +| Retention boundary and expired-key reuse | Expired at `expires_at`; reuse creates a new memory; cleanup removes at most 32 indexed records per keyed write. | +| Fresh database; upgraded managed database | Real Server startup and `db-migrate` succeed; repeated startup or upgrade keeps records. | + ## Upgrade and compatibility Existing deployments upgrade offline under [RFC #1771](https://github.com/oceanbase/powercontext/pull/1771). Its unified @@ -231,7 +388,7 @@ Atomic identities and revisions: the new `ArtifactRef`. - `list` and `search` query Atomic Memory in the Scope using the new model's listing, state, and search semantics. - `remember` supports simple creation only, without legacy entry updates, collection revision appends, or evidence - referring to old objects. + referring to old objects. It accepts an optional idempotency key, as described in Idempotent explicit creation. - `flush` continues extraction into Atomic Memory using the preserved Source processing progress. All other legacy entry points explicitly stop accepting the old model. These include generic `family=memory` @@ -266,6 +423,8 @@ already migrated to Atomic Memory. revisions do not automatically roll back. - Old clients must update their references and calls. Five legacy server entry points still need adapters, while online reading and tracing of old collections end. +- Idempotent creation adds a key table and a fixed 24-hour retention period. A retry after expiry creates a second + memory, and a replay reports creation-time state rather than current state. # Rationale and alternatives @@ -289,6 +448,13 @@ retained history, correction, and undo to handle mistakes without requiring user each contradiction for users to resolve would accumulate maintenance work. The model updates current memories using time, with history and restoration supporting correction, without a separate unresolved-conflict workflow. +**Idempotency key on explicit creation only.** A lost `remember_memory` response is the case in which a caller cannot +tell whether its write happened. Content-based deduplication would merge writes the caller intended to keep separate, +and a cross-Family idempotency framework would have to define replay for revision, merge, and restoration, whose +results depend on current state. A digest over stored content treats requests that write the same memory as the same +request. Replaying revision 1 with its creation-time state keeps a retry's result independent of later changes; +replaying the current head would let a retry return content the caller never wrote. + # Prior art - [RFC 1345](1345_scope_organization_and_agent_integration.md) and [1549](1549_artifact_family_unification.md) provide @@ -309,8 +475,8 @@ time, with history and restoration supporting correction, without a separate unr and merged? This RFC defines Atomic Memory behavior; adoption and adaptation by other families remain separate decisions. Physical deletion of Atomic content history, automatic merging across Scopes, and whole-Scope snapshot rollback are -outside this proposal. Table schemas, API parameters, locking, and transaction implementation belong in the implementation -design. Migration follows RFC #1771. +outside this proposal. Apart from the idempotent creation protocol above, table schemas, API parameters, locking, and +transaction implementation belong in the implementation design. Migration follows RFC #1771. # Future possibilities diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 2cb714a390..4f91d6778c 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -14,8 +14,8 @@ description: 了解数据库迁移命令、备份策略、服务启停及当前 完整 Server 框架使用两个归一化检查点接入共享迁移链: -- **1.3.0:**`s1300 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004`。 -- **1.4.0:**通过独立冻结的来源桥接,执行 `r1400 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004`。 +- **1.3.0:**`s1300 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004 → v1_5_2_001`。 +- **1.4.0:**通过独立冻结的来源桥接,执行 `r1400 → s1400 → s1401 → s1402 → v1_4_1_004 → v1_4_1_005 → v1_4_1_006 → v1_5_0_001 → v1_5_0_002 → v1_5_0_003 → v1_5_0_004 → v1_5_2_001`。 应用发布版本与 schema revision 分别编号。1.4.0 发行包不等于 `s1400` 检查点:其 Candidate 结构已经是当前格式, 但 Topic 尝试状态仍需登记的桥接。两条路径保留既有引用和历史,到达相同的受管目标结构;原有资源摘要分别保留, @@ -74,6 +74,8 @@ payload 身份及待处理 intent。兼容的当前任务原样保留,不套 `v1_4_1_006` 登记 `pc_source_write_plugins`,用于持久保存 Source write 插件声明。 +修订 `v1_5_2_001` 登记 `pc_atomic_memory_idempotency`,即带键 `remember_memory` 创建的重试回执,并为过期时间建立索引。已有受管数据库必须在 Server 启动前显式迁移;迁移只创建空表,不重写任何既有数据。回执保存键命名空间与所创建内容的 SHA-256 摘要、所绑定的 Artifact revision 及创建时的 state version,不保存原始键、principal ID 或记忆正文。回执在创建 24 小时后过期,并按有界批次清理。重试行为参见 [Atomic Memory](../workflows/atomic-memory.md)。 + 修订 `v1_5_0_004` 登记可选关系表 `pc_artifact_source_locators`,以既有 Artifact Revision 和 Source 边序号为键。已有受管数据库必须在 Server 启动前显式迁移。迁移保留既有血缘行、精确身份及历史负载,不重写这些记录,也不回填定位信息。Atomic Memory 的历史向量保持不变,无需重新生成 embedding。定位信息的行为参见 [Source 引用位置](../workflows/sources.md)。 `v1_5_0_001` 增加 Artifact 插件注册字段、family schema、检索状态和投影、索引覆盖与变更跟踪,以及向量空间和索引登记。 @@ -135,12 +137,13 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 | `v1_5_0_002` | 1.5.0 | 第二步 | `v1_5_0_002` | 保留 Source 证据及历史验证 | | `v1_5_0_003` | 1.5.0 | 第三步 | `v1_5_0_003` | 可丢弃的精确 revision 证据投影 | | `v1_5_0_004` | 1.5.0 | 第四步 | `v1_5_0_004` | Source 引用位置定位信息 | +| `v1_5_2_001` | 1.5.2 | 第一步 | `v1_5_2_001` | 带键 remember_memory 的重试回执 | -两条已登记来源路径都升级到 `v1_5_0_004`;CI 升级验收只选择 1.3.0: +两条已登记来源路径都升级到 `v1_5_2_001`;CI 升级验收只选择 1.3.0: ```text -1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 +1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_2_001 +1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_2_001 ``` `status` 和 `plan` 在原有机器字段之前显示 `source_migration`、`target_migration`、 @@ -159,7 +162,7 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 这样可以继续使用已有计划和原始备份。局部原型 bundle 保留自己的独立编号。 后续新增 Server 迁移直接使用该命名作为 Alembic `revision`,并正常登记结构、领域步骤和恢复检查点。 -`down_revision` 必须引用前一步的实际 ID;若直接追加在当前 head 之后,引用 `v1_5_0_004`,即使它已有展示别名。 +`down_revision` 必须引用前一步的实际 ID;若直接追加在当前 head 之后,引用 `v1_5_2_001`,即使它已有展示别名。 框架按照登记的链执行,不按名称字典序推算。已登记的名称和所属发布版本保持不变,版本升级不能重命名历史。 ## 初始化与维护职责 diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index ae973506dd..314f18d26a 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -90,6 +90,10 @@ Code 专用诊断字段仅在 `code.*` events 中输出。 已登记的完整性原因以 `WARNING` 输出;可预期的历史缺口保持 `INFO` 或 `DEBUG`。`manifest_conflict` 这类完整性原因 可告警,并与“从未声明”区分开。 +`atomic_memory.idempotency.cleanup_failed` 事件表示带键的 `remember_memory` 创建已提交,但随后对过期重试键的 +有界清理失败。创建结果与响应不受影响,之后的带键创建会再次清理。该事件以 `WARNING` 输出,`operation` 为 +`remember_memory`,`unit` 为 `atomic-memory`,`outcome` 为 `failure`,并带 `exception_type`;不携带键、主体或记忆内容。 + Server role 为 `all`(API 与 supervisor)、`api` 或 `background`,child process 使用 `worker`。 显式配置 logging 但没有指定 deployment role 时使用 `server`。JSON identity 字段对应 trace resource attributes: `service.name`、`service.version`、`service.instance.id` 和 `powercontext.service.role`。 diff --git a/docs/zh/docs/operate/troubleshoot.md b/docs/zh/docs/operate/troubleshoot.md index d5fada4e30..46a6c97f53 100644 --- a/docs/zh/docs/operate/troubleshoot.md +++ b/docs/zh/docs/operate/troubleshoot.md @@ -252,7 +252,7 @@ collation,但不会包含数据库 URL 或凭据。 源数据库早于三张 Skill 生命周期表(`pc_skill_packages`、`pc_agent_skill_targets` 和 `pc_skill_publications`)、Profile 表、`pc_topic_memory_work_budgets`、`pc_topic_memory_work_blocks`、 `pc_recall_effort_daily`、`pc_receipt_migration_review`、`pc_context_bootstrap_receipts` 或 - `pc_decision_observations` 或 `pc_artifact_source_locators` 时,应从对应层删除缺失的表。 + `pc_decision_observations`、`pc_artifact_source_locators` 或 `pc_atomic_memory_idempotency` 时,应从对应层删除缺失的表。 如果存在 work-budget 表,必须与 Cursor 一起恢复,保留已消耗的失败额度,避免迁移后重置累计成本。 work-attempt 表也应一起恢复,保留阻塞身份、诊断信息与已接受的重试回执。 @@ -260,7 +260,7 @@ collation,但不会包含数据库 URL 或凭据。 ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_write_plugins,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_artifact_family_schemas,pc_artifact_vector_spaces,pc_artifact_search_states' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_write_plugins,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_artifact_family_schemas,pc_artifact_vector_spaces,pc_artifact_search_states,pc_atomic_memory_idempotency' \ -f ``` diff --git a/docs/zh/docs/workflows/atomic-memory.md b/docs/zh/docs/workflows/atomic-memory.md index 2efa2a3d6f..1ab34495d3 100644 --- a/docs/zh/docs/workflows/atomic-memory.md +++ b/docs/zh/docs/workflows/atomic-memory.md @@ -50,6 +50,30 @@ Atomic Memory 将每条事实、偏好或决策保存为独立的 `atomic-memory 成功后正文产生下一条 revision。缺少 `If-Match` 返回 `428 precondition_required`, 过期返回 `412 revision_conflict`。重新读取并协调正文后再提交。 +## 安全重试 remember_memory + +`POST /v1/memory/remember`(`remember_memory`)每次调用都会创建一条新记忆。若响应丢失,需要重试而不产生重复记忆, +可发送 `idempotency_key`:1 到 256 个除空格外的可打印 ASCII 字符。每次逻辑写入生成一个新的、不可猜测的键(例如 UUID), +且只在重试该次写入时复用: + +```json +{ + "scope_id": "S", + "kind": "preference", + "text": "Prefer short pull requests.", + "idempotency_key": "3f0c8f5e-7a51-4c1e-9a43-0f1e2b7d9c60" +} +``` + +键的作用域是 Scope 与已认证的 principal;关闭访问控制时,所有调用方在同一 Scope 内共享一个命名空间。创建后 24 小时内, +相同键且存储内容相同的请求返回原始响应:同一 revision 1 的 `ArtifactRef` 与创建时记录的状态,即使该记忆随后被修订、遗忘或合并。 +当前状态请通过 Atomic Memory 读取操作获取。规范化后的 `text`、`kind`、`description`(省略时等同于由正文派生的默认描述) +及正文 schema 一致即视为内容相同;`reason` 不参与比较。相同键配不同内容返回 `409 idempotency_conflict`, +`error.details.kind` 为 `"memory_idempotency_key"`,且不写入任何数据;新内容请使用新键。24 小时后该键视为未使用,会创建新记忆。 + +每次重放都会重新检查调用方当前的授权。服务端只保存键命名空间与内容的摘要,不保存原始键或记忆正文。服务端、Python SDK +和 MCP 工具都不会自动生成键或自动重试;`expected_revision` 保持原有行为。 + ## 当前状态与遗忘 `GET /v1/scopes/S/artifacts/atomic-memory/M/state` 返回当前精确 `artifact` 引用、`state`、 diff --git a/docs/zh/rfcs/1437_source_artifact_rest_api.md b/docs/zh/rfcs/1437_source_artifact_rest_api.md index ab1cb259db..0fa1a9410c 100644 --- a/docs/zh/rfcs/1437_source_artifact_rest_api.md +++ b/docs/zh/rfcs/1437_source_artifact_rest_api.md @@ -451,6 +451,11 @@ Path 中已经确定的身份字段不在 body 中重复接收。Create Source `content_digest` 只覆盖 canonical `content`,不覆盖身份或 lineage。Source 和 Artifact Create 每次成功都创建新 资源;客户端超时后应先根据业务上下文确认结果,不能假定重试幂等。 +通过 `remember_memory` 显式创建 Atomic Memory 不属于上述操作,是唯一带幂等键的 Atomic Memory 创建路径。 +[RFC 1809](1809-atomic-memory.md) 的“幂等的显式创建”一节定义其可选 request body 字段 `idempotency_key`、 +命名空间、请求摘要、重放和保留期。该字段不适用于 Source Create 或 Artifact Create,任何操作都不接受 +`Idempotency-Key` header;通过 Artifact Create 创建 Atomic Memory 仍然不幂等。 + ## 状态和错误模型 | 状态码 | 场景 | @@ -485,6 +490,9 @@ Path 中已经确定的身份字段不在 body 中重复接收。Create Source 错误不得泄漏其他 Scope 的资源是否存在;权限不足与资源不可见按统一安全策略返回 `403` 或 `404`。 +对 `remember_memory`,幂等键已绑定到不同请求时,返回 `409` 和现有错误码 `idempotency_conflict`,并将 +`details.kind` 设为 `memory_idempotency_key`;不为此新增错误码。 + ## OpenAPI contract `openapi/powercontext.yaml` 是 HTTP 契约唯一事实来源。主要 schema: diff --git a/docs/zh/rfcs/1809-atomic-memory.md b/docs/zh/rfcs/1809-atomic-memory.md index 7fd6dfddc2..e20a8b9727 100644 --- a/docs/zh/rfcs/1809-atomic-memory.md +++ b/docs/zh/rfcs/1809-atomic-memory.md @@ -163,6 +163,136 @@ RFC 1718 针对完整 manifest 设置的集合容量限制不适用于新 Family 执行恢复时,服务端在写入事务内检查当前正文版本、状态和合并关系。带预览标识时,还要检查是否符合预览; 不带标识时,按当前状态处理。检查结果须在提交时仍然成立,不能覆盖期间发生的更新。 +## 幂等的显式创建 + +`remember_memory` 是唯一接受幂等键的 Atomic Memory 创建入口,供丢失响应的调用方重试同一次显式创建, +而不会产生第二条记忆。不带键的请求保持原有行为:每次成功调用都创建一条新记忆。修订、遗忘、恢复、合并、 +抽取、Source 处理以及 RFC 1437 的通用 Artifact Create 都不接受幂等键。服务端不按内容去重,也不替调用方 +自动重试。 + +### 请求字段与命名空间 + +`RememberMemoryRequest` 新增可选字段 `idempotency_key`:1 到 256 个除空格外的可打印 ASCII 字符,即匹配 +`^[!-~]{1,256}$`。服务端逐字节比较,不去除首尾空白、不折叠大小写,也不做其他规范化。省略该字段或传 +`null` 表示不带键。不符合格式的键在任何查找或写入之前,按公共请求校验策略以 `422` 拒绝:错误码为 +`invalid_request`;若启用访问控制并由鉴权步骤先校验请求体,则为 `invalid_access_request`。 + +键在一个命名空间内唯一:操作 `remember_memory`、`scope_id`,以及已认证主体的类型和 ID。未启用访问控制时, +主体部分为空,同一部署的所有调用方在每个 Scope 内共用一个命名空间。同一个键用在其他 Scope、来自其他主体 +或用于其他操作时,表示相互独立的写入。HTTP API、Python SDK 和 MCP 工具原样传递该字段,都不生成键,也不 +自动重试。调用方为每次逻辑写入生成新的、不可猜测的键(例如 UUID),只在重试这次写入时复用。MCP 服务说明和共享 Skill +参考向模型给出同样的指引,并要求遇到冲突后改用新键。Dify 的 `pc_remember` 工具不暴露该字段。 + +服务端只保存命名空间与键的 SHA-256 摘要,不保存原始键或明文主体 ID。 + +### 请求摘要 + +请求摘要用写入产生的第 1 版正文标识一次逻辑写入。第 1 版摘要是一个 JSON 对象按 RFC 8785 序列化后的 +SHA-256,以小写十六进制表示。该对象恰好包含以下四个成员,与写入方将要保存的 `AtomicMemoryContent` 一致: + +- `schema` 为 `powercontext.atomic-memory.v1`。 +- `kind` 取提交值,不做改动,与写入方保存的值一致。 +- `text` 取写入方 `normalize_text` 的结果:先做 Unicode NFC,再去除首尾空白。 +- `description` 有提交值时取提交值;省略或为 `null` 时,取写入方根据规范化正文生成的默认描述。 + +对象不含 `creation` 成员,因为显式创建从不携带合并元数据。字符串按将要保存的形式参与计算:除 `text` 外不做 +Unicode 规范化,因此不得使用会规范化所有字符串的辅助函数计算该摘要。成员集合、`normalize_text` 或默认描述 +的行为发生任何变化,都必须使用新的摘要版本。 + +因此,省略 `description`、传 `null`、传与默认描述完全相同的值,会保存相同正文,得到同一个摘要。`reason` +不属于写入正文,不参与摘要。`expected_revision` 必须省略或为 `null`;非 `null` 值在查找前即被拒绝。 +`scope_id` 和主体属于命名空间,不进入摘要。 + +第 1 版写入的 Source 记录执行创建的那次请求的命令。正文只在规范化上有差异的重试会重放该次创建,不改写 +其 Source。每条键记录保存其摘要版本;新的摘要版本只用于新键,服务端在保留期内继续支持计算所有可能出现 +的版本。 + +### 结果 + +| 在键的命名空间中查找 | 结果 | +| --- | --- | +| 没有未过期记录 | 按不带键的方式创建记忆,并在同一事务中绑定该键。 | +| 记录的摘要相同 | 重放原始结果;不准备 Embedding,不写入任何数据。 | +| 记录的摘要不同 | 返回 `409 idempotency_conflict`,details 为 `{"kind": "memory_idempotency_key"}`;不写入任何数据。 | + +重放返回与原始创建相同的 `MemoryMutationResponse`:`changed: true`,以及一条记录,包含第 1 版的精确 +`ArtifactRef`、其 `kind` 和 `text`、`state: active`、创建时记录的状态版本,以及 `merged_into_id: null`。 +正文来自不可变的第 1 版,创建时状态来自键记录。目前每次创建都产生第 1 版、状态版本 0 且没有合并目标; +键记录仍保存版本号和状态版本,使重放不依赖这一不变量。之后的修订、遗忘、合并、恢复或退役都不改变重放结果,重放 +也绝不以当前 head 替代。调用方通过 Atomic Memory 的读取操作获取当前状态。 + +对带键的创建,原始响应同样通过精确版本读取构造,因此在创建与响应之间并发提交的修订不会改变任一结果。 +不带键的请求保持原有的响应构造方式。响应不带重放标记;需要区分重放的调用方,应将返回的身份与自身记录比较。 + +### 鉴权 + +`scope.contribute` 检查在查找键之前执行,与普通创建相同。被拒绝的调用方收到 `403`,无从得知键是否存在。 +主体属于命名空间,因此其他主体既不会命中,也无法探测某个键。 + +重放以调用方当前上下文,经由与 `atomic-memory` Family 的 Get Artifact Revision 相同的鉴权精确版本读取, +读取第 1 版。若调用方已不能读取该记忆(例如访问权已被撤销),请求返回该读取在公共安全策略下的错误:拒绝访问时 +为 `403 forbidden`,所有权尚未建立时为 `503 artifact_owner_pending`。只有找不到第 1 版时才返回 +`404 artifact_not_found`;第 1 版不可变且不会被物理删除,正常运行中不会出现这种情况。它既不泄露记录,也不创建新记忆;该键在过期前保持绑定。 + +冲突只表明调用方自己在该 Scope 中的键已用于不同内容。其他操作也会返回 `idempotency_conflict`,调用方通过 +`details.kind` 识别这种情况。 + +### 原子性与失败处理 + +请求校验、鉴权、写入方校验和摘要计算都在查找之前完成。查找是一次主键读取,在独立的读事务中执行,并使用 +数据库时钟。只有未命中时,才进入写事务之外原有的准备步骤,包括生成 Embedding。 + +写事务先删除同一命名空间的记录,但仅当其 `expires_at` 不晚于当前数据库时间,因此不会删除并发提交的有效键; +再插入键记录;随后照常写入 Source、第 1 版、治理状态、 +Owner 以及检索和证据投影,并一起提交。键记录包含命名空间摘要、请求摘要及其版本、`scope_id`、 +`artifact_id`、版本号、创建时状态版本、`created_at` 和 `expires_at`,不保存记忆正文。 + +- 校验、鉴权或准备失败,或在提交前取消,不留下键、Source、Artifact、Owner 或投影;用该键重试会重新执行创建。 +- 写事务内的失败会把键与其他数据一起回滚。 +- 提交后响应丢失(包括调用方无法观察结果的取消)时,键保持绑定;重试会重放已提交的结果。 +- 使用同一键的并发请求在键记录的主键上竞争。失败方回滚后,在新事务中重新读取该键,并按上表返回重放或冲突。 + 若重新读取未找到记录,说明完整性错误与键无关,原样返回该错误。失败方已准备的 Embedding 被丢弃。 + +唯一性由数据库约束而非进程内锁保证,因此在 SQLite 和 OceanBase/seekdb 上,跨连接、跨进程和跨 Server +实例均成立。 + +### 保留与清理 + +键自创建事务插入它时的数据库时间起保留 24 小时,重放不延长保留期。若记录的 `expires_at` 不晚于当前数据库 +时间,即视为不存在:同一个键将开始一次新的创建,并在该次创建的事务中替换过期记录。调用方不应期望 24 小时 +之后还能重放。 + +带键的创建提交后,服务端在独立的短事务中最多删除 32 条过期记录:先在 `expires_at` 索引上做一次上限为 32 的 +范围读取,再按主键删除并复核过期条件。清理失败不影响创建结果。每次带键创建新增一条记录、最多删除 32 条 +过期记录,因此只要带键写入持续发生,过期积压就会减少。不带键的请求不访问该表。所有操作都不扫描全表:查找 +和绑定使用主键,清理使用过期时间索引。 + +### 存储与升级 + +键记录保存在新表 `pc_atomic_memory_idempotency` 中,以命名空间摘要为主键,并在 `expires_at` 上建立二级 +索引。定长摘要使主键满足 MySQL 兼容数据库的索引长度限制。服务端资源迁移链新增一个版本创建该表,包含 +SQLite 和 MySQL 结构、manifest 资源以及 SQLite 指纹;已发布的版本不作修改。 + +Server 启动时,空的持久化 SQLite 或 seekdb 数据库会执行完整的版本链完成初始化,其中包括新版本。OceanBase +即使是空库,也需要显式运行 `powercontext server db-migrate` 作业。处于更早版本的托管数据库会使 Server 启动 +失败并报告需要迁移,直到 `powercontext server db-migrate apply` 成功;启动过程不会隐式升级。只有非托管存储 +(例如内存 SQLite)会根据内置表注册创建该表。重启或重复执行升级都保留已有记录。 + +### 验收 + +| 场景 | 预期结果 | +| --- | --- | +| 相同键和摘要 | 只有一个 Artifact 和 Source,启用访问控制时另有一个 Owner;每次响应都与第一次相同。 | +| 相同键、不同摘要 | `409 idempotency_conflict`;原记忆、Source、Owner 和投影不变。 | +| 不带键;同一键用于其他 Scope 或来自其他主体;不同的键 | 各自独立创建。 | +| `description` 省略、为 `null` 或等于默认值;正文只在 NFC 或首尾空白上不同 | 摘要相同;重放。 | +| 在不同连接或进程上并发请求 | 只创建一次;其他请求按摘要重放或冲突。 | +| 提交前失败或取消;提交后响应丢失 | 没有孤立行;重试只创建一次,或重放已提交结果。 | +| 重启后,再经历修订、遗忘、合并或退役 | 重放仍返回第 1 版及创建时状态。 | +| 访问权被撤销;其他主体 | 不泄露、不写入:返回精确读取的错误,或属于独立命名空间。 | +| 保留期边界与过期键复用 | 在 `expires_at` 时过期;复用会创建新记忆;每次带键写入借助索引最多清理 32 条记录。 | +| 全新数据库;升级后的托管数据库 | 真实 Server 启动和 `db-migrate` 成功;重复启动或升级保留记录。 | + ## 升级与兼容 现有部署按照 [RFC #1771](https://github.com/oceanbase/powercontext/pull/1771) 停服升级。数据库结构变更、 @@ -190,7 +320,7 @@ server 仅保留 `memory.get/list/search/remember/flush` 五个旧入口的适 - `get` 可用旧集合 ID 和 entry ID 定位对应 Atomic 的当前 head;精确历史读取改用新的 `ArtifactRef`。 - `list` 和 `search` 查询 Scope 中的 Atomic Memory,采用新模型的列表、状态和检索语义。 -- `remember` 仅适配简单新增,不保留旧条目更新、集合追加版本或旧对象依据。 +- `remember` 仅适配简单新增,不保留旧条目更新、集合追加版本或旧对象依据;可选接受幂等键,见“幂等的显式创建”。 - `flush` 使用保留的 Source 处理进度,继续向 Atomic Memory 抽取。 其他旧入口明确停止支持,包括通用 `family=memory` 操作、旧标签目标及其 ETag、旧 access selector、集合 @@ -214,6 +344,7 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me - 按时间自动处理冲突可能采纳有误的新内容,时间缺失时尤其依赖 Source 顺序;纠正通过后续演化、编辑或恢复完成。 - 撤销合并后,结果记忆上的后续修订退出正常检索;已经引用这些版本的其他制品不会自动回滚。 - 旧客户端需要调整引用和调用方式;五个旧服务入口仍需适配,旧集合在线读取和追溯不再提供。 +- 幂等创建增加一张键表和固定 24 小时的保留期。过期后重试会创建第二条记忆,重放报告的是创建时状态而非当前状态。 # 设计理由与替代方案 @@ -233,6 +364,11 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me **冲突按时间自动处理。** 原子记忆持续大量产生,把每次矛盾留给用户判断会积累维护工作。模型按时间更新当前 记忆,历史与恢复能力承担纠错需要,不建立独立的待处理冲突流程。 +**只在显式创建上提供幂等键。** `remember_memory` 的响应丢失时,调用方无法判断写入是否发生。按内容去重会 +合并调用方有意分开的写入;跨 Family 的幂等框架则需要为修订、合并和恢复定义重放,而它们的结果依赖当前状态。 +按保存正文计算摘要,可以把写入同一条记忆的请求视为同一请求。重放第 1 版及其创建时状态,使重试结果不受之后 +变更的影响;重放当前 head 则可能让重试返回调用方从未写入的内容。 + # 先例 - [RFC 1345](1345_scope_organization_and_agent_integration.md) 和 [1549](1549_artifact_family_unification.md) @@ -251,8 +387,8 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me - 其他制品是否也采用这四种状态?现有 `deprecated` 状态如何对应“遗忘”和“被合并”?Atomic Memory 的行为 在本提案中明确,其他制品是否统一及如何改造另行讨论。 -本提案不包含 Atomic 正文历史的物理删除、跨 Scope 自动合并或整个 Scope 的快照回滚。具体表结构、接口参数、 -锁与事务实现放在实现方案中;迁移遵守 RFC #1771。 +本提案不包含 Atomic 正文历史的物理删除、跨 Scope 自动合并或整个 Scope 的快照回滚。除上文幂等创建协议外,具体表结构、 +接口参数、锁与事务实现放在实现方案中;迁移遵守 RFC #1771。 # 后续可能性 diff --git a/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/dify/plugin/powercontext_dify/contract.json b/integrations/dify/plugin/powercontext_dify/contract.json index 5f8bda476c..e2d83d4ea8 100644 --- a/integrations/dify/plugin/powercontext_dify/contract.json +++ b/integrations/dify/plugin/powercontext_dify/contract.json @@ -4257,6 +4257,20 @@ "type": "null" } ] + }, + "idempotency_key": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[!-~]{1,256}$", + "description": "Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key." + }, + { + "type": "null" + } + ] } } }, diff --git a/integrations/dify/plugin/powercontext_dify/policy.py b/integrations/dify/plugin/powercontext_dify/policy.py index 587383686d..16c6c35b25 100644 --- a/integrations/dify/plugin/powercontext_dify/policy.py +++ b/integrations/dify/plugin/powercontext_dify/policy.py @@ -19,6 +19,8 @@ "scope_id", "tag_filter", "expected_revision", + # A Dify tool call cannot carry one logical write's key across its retries. + "idempotency_key", "max_bytes", "include_code", "include_reuse", diff --git a/integrations/dify/tests/test_plugin_contract.py b/integrations/dify/tests/test_plugin_contract.py index 16a3c67230..8876d38958 100644 --- a/integrations/dify/tests/test_plugin_contract.py +++ b/integrations/dify/tests/test_plugin_contract.py @@ -231,6 +231,7 @@ def test_sdk_registers_exact_catalog_and_json_text_inputs(registry): "scope_id", "tag_filter", "expected_revision", + "idempotency_key", "max_bytes", "include_code", "assembly", @@ -256,6 +257,7 @@ def test_sdk_registers_exact_catalog_and_json_text_inputs(registry): ("pc_prepare_context", {"query": "scope"}, "bootstrap_receipt_id", "receipt-1"), ("pc_search", {"query": "scope"}, "tag_filter", {"tags": ["private"]}), ("pc_remember", {"kind": "decision", "text": "Retain."}, "expected_revision", 1), + ("pc_remember", {"kind": "decision", "text": "Retain."}, "idempotency_key", "retry-1"), ], ) def test_server_controlled_parameters_are_rejected_at_the_sdk_boundary( diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 8527d0fc98..69e3b15ebd 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -2332,6 +2332,7 @@ const PUBLIC_ERROR_CODES = new Set([ "scope_idempotency_conflict", "scope_binding_target_missing", "artifact_publication_conflict", + "idempotency_conflict", "connector_checkpoint_conflict", "generation_conflict", "external_skill_snapshot_unavailable", diff --git a/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/dsh/plugins/powercontext/src/diagnostics.ts b/integrations/dsh/plugins/powercontext/src/diagnostics.ts index 575d57040c..7a363a5cf1 100644 --- a/integrations/dsh/plugins/powercontext/src/diagnostics.ts +++ b/integrations/dsh/plugins/powercontext/src/diagnostics.ts @@ -48,6 +48,9 @@ const PUBLIC_ERROR_CODES = new Set([ 'invalid_cursor', 'cursor_expired', 'precondition_required', 'capacity_exceeded', 'source_conflict', 'candidate_conflict', 'artifact_conflict', 'candidate_terminal', 'scope_version_conflict', 'scope_idempotency_conflict', 'scope_binding_target_missing', 'artifact_publication_conflict', + // remember_memory returns it when an idempotency_key is reused for different content; + // the caller recovers by choosing a new key, so it must reach the caller as itself. + 'idempotency_conflict', 'connector_checkpoint_conflict', 'generation_conflict', 'external_skill_snapshot_unavailable', 'handoff_report_inconsistent', 'invalid_request', 'invalid_scope_relationship', 'invalid_source_ingestion', 'invalid_lifecycle', 'artifact_publication_unsupported', diff --git a/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts b/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts index e0be684775..0da93eb841 100644 --- a/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts @@ -107,6 +107,8 @@ describe('published error code filter', () => { expect(publicErrorCode('cursor_expired')).toBe('cursor_expired') expect(publicErrorCode('precondition_required')).toBe('precondition_required') expect(publicErrorCode('capacity_exceeded')).toBe('capacity_exceeded') + // A reused remember_memory idempotency_key with different content needs a new key. + expect(publicErrorCode('idempotency_conflict')).toBe('idempotency_conflict') }) it('drops a code that is not published, so internal codes cannot cross the boundary', () => { diff --git a/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/openapi/powercontext.yaml b/openapi/powercontext.yaml index 6729737386..53a2148564 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -2325,7 +2325,7 @@ paths: tags: [memory] summary: Create Atomic Memory through the legacy remember input description: >- - Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. + Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. With idempotency_key, a retry of the same creation within 24 hours replays the original response, and reuse of the key for different content returns 409 idempotency_conflict with details.kind memory_idempotency_key. operationId: remember_memory x-powercontext-feature-contracts: [memory.explicit] x-powercontext-access: {action: scope.contribute, resource: {type: scope, scope-id-from: scope_id}} @@ -12497,6 +12497,15 @@ components: a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. nullable: true + idempotency_key: + type: string + minLength: 1 + maxLength: 256 + pattern: ^[!-~]{1,256}$ + description: Optional retry key, unique per operation, Scope and authenticated principal. Generate + a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are + compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + nullable: true RetireMemoryEntryRequest: type: object additionalProperties: false diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 39f03a6060..cfa1e159a2 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "90defa76dc50ab00a3890fab117ff0e5900c103ceb14eb188bc06c38f0349e0c", - "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources." + "persistence_sha256": "bd1a705987378197b4baaaaf9cc187b0563cd7a75285d67a1898f187ffe99b02", + "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. Revision v1_5_2_001 adds pc_atomic_memory_idempotency after v1_5_0_004 on both registered source releases and all vector/Code profiles. Explicit maintenance creates the empty table and its expiry index; fresh databases receive it through the registered bootstrap. A row holds only SHA-256 namespace and request digests, the bound Artifact identity, revision and creation state version, and database-clock creation and expiry times; raw keys, principal IDs and memory bodies are not stored. A keyed remember_memory creation commits its receipt in the same transaction as the Memory, and expired receipts are removed in bounded batches after commit. Requests without a key, Artifact history, earlier revision resources, fingerprints, checksums and existing row encodings are unchanged. Local SQLite migration, retry and concurrency tests do not constitute native seekDB/OceanBase or installed-release acceptance; the upgrade-required policy, required automatic matrix and publication restrictions remain unchanged." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/persistence/atomic_memory_idempotency.py b/src/powercontext/builtin/persistence/atomic_memory_idempotency.py new file mode 100644 index 0000000000..3b7d9cc50e --- /dev/null +++ b/src/powercontext/builtin/persistence/atomic_memory_idempotency.py @@ -0,0 +1,197 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Retry receipts for keyed ``remember_memory`` creations. + +A receipt binds one namespace (operation, Scope, principal and caller key) to the +digest of the revision 1 content its creation stored. Only SHA-256 digests are +persisted: never the raw key, the principal ID, or the memory body. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from datetime import timedelta +from hashlib import sha256 + +import rfc8785 +from sqlalchemy import delete, insert, select +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent +from powercontext.builtin.artifacts.atomic_memory.summary import default_description +from powercontext.builtin.artifacts.memory.canonical import canonical_error_code, normalize_text +from powercontext.builtin.artifacts.memory.errors import InvalidMemoryCandidateError +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.supervision import database_utc_now +from powercontext.builtin.persistence.tables import ATOMIC_MEMORY_IDEMPOTENCY_TABLE as TABLE + +KEY_PATTERN = re.compile(r"[!-~]{1,256}") +RETENTION = timedelta(hours=24) +CLEANUP_BATCH = 32 +DIGEST_VERSION = 1 +OPERATION = "remember_memory" + + +@dataclass(frozen=True, slots=True) +class MemoryIdempotencyKey: + """One keyed request: its namespace and the content it would store.""" + + namespace_digest: str + content: AtomicMemoryContent + + +@dataclass(frozen=True, slots=True) +class MemoryIdempotencyReceipt: + """The creation a key is bound to, with the state recorded at creation.""" + + artifact_id: str + revision: int + state_version: int + + +@dataclass(frozen=True, slots=True) +class _StoredReceipt: + digest_version: int + request_digest: str + receipt: MemoryIdempotencyReceipt + live: bool + + +def namespace_digest(scope_id: str, principal: tuple[str, str] | None, key: str) -> str: + """Digest the key's namespace; an absent principal shares one namespace per Scope.""" + + principal_type, principal_id = principal if principal is not None else ("", "") + return sha256(rfc8785.dumps([OPERATION, scope_id, principal_type, principal_id, key])).hexdigest() + + +def request_digest(content: AtomicMemoryContent, version: int = DIGEST_VERSION) -> str | None: + """Digest the revision 1 content the Atomic writer stores for this request. + + Only ``text`` is normalized, exactly as the writer normalizes it; other strings are + hashed as submitted. Returns ``None`` for a version this binary cannot compute. + """ + + if version != 1: + return None + try: + text = normalize_text(content.text) + except (TypeError, ValueError) as error: + raise InvalidMemoryCandidateError( + "canonical", str(error), canonical_code=canonical_error_code(error) + ) from error + return sha256( + rfc8785.dumps({ + "schema": content.schema_, + "kind": content.kind, + "text": text, + "description": content.description if content.description is not None else default_description(text), + }) + ).hexdigest() + + +class MemoryIdempotencyConflict(Exception): + """The key is bound to a creation of different content.""" + + +async def find_receipt(database: AsyncDatabase, key: MemoryIdempotencyKey) -> _StoredReceipt | None: + """Read the key's record, live or expired, in its own read transaction.""" + + async with database.transaction() as connection: + now = await database_utc_now(connection) + row = ( + await connection.execute( + select( + TABLE.c.digest_version, + TABLE.c.request_digest, + TABLE.c.artifact_id, + TABLE.c.revision, + TABLE.c.state_version, + TABLE.c.expires_at, + ).where(TABLE.c.namespace_digest == key.namespace_digest) + ) + ).one_or_none() + if row is None: + return None + return _StoredReceipt( + digest_version=int(row.digest_version), + request_digest=str(row.request_digest), + receipt=MemoryIdempotencyReceipt( + artifact_id=str(row.artifact_id), revision=int(row.revision), state_version=int(row.state_version) + ), + live=row.expires_at > now, + ) + + +def replay(stored: _StoredReceipt, key: MemoryIdempotencyKey) -> MemoryIdempotencyReceipt: + """Return the bound creation for the same content, or raise a conflict.""" + + if request_digest(key.content, stored.digest_version) != stored.request_digest: + raise MemoryIdempotencyConflict + return stored.receipt + + +async def bind_receipt( + connection: AsyncConnection, + key: MemoryIdempotencyKey, + scope_id: str, + receipt: MemoryIdempotencyReceipt, + *, + replace_expired: bool, +) -> None: + """Claim the key inside the creating transaction. + + An expired record is removed only when the lookup saw one, and only while it is still + expired, so a live key committed concurrently is never removed. A concurrent claim of + the same key fails on the primary key. + """ + + now = await database_utc_now(connection) + if replace_expired: + await connection.execute( + delete(TABLE).where(TABLE.c.namespace_digest == key.namespace_digest, TABLE.c.expires_at <= now) + ) + await connection.execute( + insert(TABLE).values( + namespace_digest=key.namespace_digest, + digest_version=DIGEST_VERSION, + request_digest=request_digest(key.content), + scope_id=scope_id, + artifact_id=receipt.artifact_id, + revision=receipt.revision, + state_version=receipt.state_version, + created_at=now, + expires_at=now + RETENTION, + ) + ) + + +async def remove_expired_receipts(database: AsyncDatabase) -> None: + """Delete at most one bounded batch of expired records through the expiry index.""" + + async with database.transaction() as connection: + now = await database_utc_now(connection) + expired = ( + await connection.scalars( + select(TABLE.c.namespace_digest) + .where(TABLE.c.expires_at <= now) + .order_by(TABLE.c.expires_at) + .limit(CLEANUP_BATCH) + ) + ).all() + if expired: + await connection.execute( + delete(TABLE).where(TABLE.c.namespace_digest.in_(expired), TABLE.c.expires_at <= now) + ) diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json index b6ec054ab1..1c776fe3bd 100644 --- a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json @@ -48,6 +48,10 @@ "v1_5_0_004": [ "schemas/sqlite-v1_5_0_004.json", "schemas/mysql-v1_5_0_004.json" + ], + "v1_5_2_001": [ + "schemas/sqlite-v1_5_2_001.json", + "schemas/mysql-v1_5_2_001.json" ] }, "sqlite_baselines": { @@ -86,6 +90,9 @@ ], "v1_5_0_004": [ "cfafc8c1d4f0207e5d04febca1e3f9f9a91948d15fb85678de3765d8e772efdc" + ], + "v1_5_2_001": [ + "31f944d42fe907c48c47081a4a19a9ea16355772e925a7a1ca8b58e763ac1997" ] }, "affected_objects": [ @@ -147,6 +154,7 @@ "pc_atomic_memory_evidence", "pc_atomic_memory_evidence_history", "pc_atomic_memory_evidence_schema", + "pc_atomic_memory_idempotency", "pc_candidate_heads", "pc_candidate_versions", "pc_connector_checkpoints", @@ -336,6 +344,11 @@ "artifact_storage", "portable_storage", "atomic_memory_evidence_projection" + ], + "v1_5_2_001": [ + "artifact_storage", + "portable_storage", + "atomic_memory_evidence_projection" ] }, "retained_fingerprints": { @@ -357,7 +370,8 @@ "schemas/mysql-v1_5_0_001.json", "schemas/mysql-v1_5_0_002.json", "schemas/mysql-v1_5_0_003.json", - "schemas/mysql-v1_5_0_004.json" + "schemas/mysql-v1_5_0_004.json", + "schemas/mysql-v1_5_2_001.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_5_2_001.py b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_5_2_001.py new file mode 100644 index 0000000000..5ac8a62108 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_5_2_001.py @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Add keyed remember_memory receipts through the shared DDL executor.""" + +from alembic import context + +revision = "v1_5_2_001" +down_revision = "v1_5_0_004" + + +def upgrade() -> None: + context.config.attributes["execute_revision"](revision) diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_5_2_001.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_5_2_001.json new file mode 100644 index 0000000000..91a2ab6b21 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_5_2_001.json @@ -0,0 +1,370 @@ +{ + "format": "powercontext.mysql-state-layouts.v1", + "revisions": { + "v1_5_2_001": { + "statements": [ + "CREATE TABLE pc_atomic_memory_idempotency (\n\tnamespace_digest VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tdigest_version INTEGER NOT NULL, \n\trequest_digest VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tscope_id VARCHAR(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tartifact_id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\trevision INTEGER NOT NULL, \n\tstate_version INTEGER NOT NULL, \n\tcreated_at DATETIME(6) NOT NULL, \n\texpires_at DATETIME(6) NOT NULL, \n\tPRIMARY KEY (namespace_digest), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_digest_version CHECK (digest_version > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_revision CHECK (revision > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_state_version CHECK (state_version >= 0)\n)", + "CREATE INDEX ix_pc_atomic_memory_idempotency_expires_at ON pc_atomic_memory_idempotency (expires_at)" + ], + "changes": [ + { + "pc_atomic_memory_idempotency": { + "columns": { + "namespace_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "digest_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "request_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "scope_id": { + "type": [ + "varchar", + [ + "256" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "artifact_id": { + "type": [ + "varchar", + [ + "128" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "revision": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "state_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "created_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "expires_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + } + }, + "primary_key": [ + [ + "namespace_digest", + null, + "asc" + ] + ], + "foreign_keys": [], + "checks": { + "ck_pc_atomic_memory_idempotency_digest_version": { + "expression": [ + "binary", + ">", + [ + "column", + "digest_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_revision": { + "expression": [ + "binary", + ">", + [ + "column", + "revision" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_state_version": { + "expression": [ + "binary", + ">=", + [ + "column", + "state_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + } + }, + "indexes": {} + } + }, + { + "pc_atomic_memory_idempotency": { + "columns": { + "namespace_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "digest_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "request_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "scope_id": { + "type": [ + "varchar", + [ + "256" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "artifact_id": { + "type": [ + "varchar", + [ + "128" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "revision": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "state_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "created_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "expires_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + } + }, + "primary_key": [ + [ + "namespace_digest", + null, + "asc" + ] + ], + "foreign_keys": [], + "checks": { + "ck_pc_atomic_memory_idempotency_digest_version": { + "expression": [ + "binary", + ">", + [ + "column", + "digest_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_revision": { + "expression": [ + "binary", + ">", + [ + "column", + "revision" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_state_version": { + "expression": [ + "binary", + ">=", + [ + "column", + "state_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + } + }, + "indexes": { + "ix_pc_atomic_memory_idempotency_expires_at": { + "columns": [ + [ + "expires_at", + null, + "asc" + ] + ], + "unique": false + } + } + } + } + ] + } + } +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_5_2_001.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_5_2_001.json new file mode 100644 index 0000000000..78d7ed7a98 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_5_2_001.json @@ -0,0 +1,6 @@ +{ + "create": [ + "CREATE TABLE pc_atomic_memory_idempotency (\n\tnamespace_digest VARCHAR(64) NOT NULL, \n\tdigest_version INTEGER NOT NULL, \n\trequest_digest VARCHAR(64) NOT NULL, \n\tscope_id VARCHAR(256) NOT NULL, \n\tartifact_id VARCHAR(128) NOT NULL, \n\trevision INTEGER NOT NULL, \n\tstate_version INTEGER NOT NULL, \n\tcreated_at DATETIME NOT NULL, \n\texpires_at DATETIME NOT NULL, \n\tPRIMARY KEY (namespace_digest), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_digest_version CHECK (digest_version > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_revision CHECK (revision > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_state_version CHECK (state_version >= 0)\n)", + "CREATE INDEX ix_pc_atomic_memory_idempotency_expires_at ON pc_atomic_memory_idempotency (expires_at)" + ] +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_5_2_001_atomic_memory_idempotency.py b/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_5_2_001_atomic_memory_idempotency.py new file mode 100644 index 0000000000..dfd484a74e --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_5_2_001_atomic_memory_idempotency.py @@ -0,0 +1,30 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Register retry receipts for keyed remember_memory creations.""" + +import json +from pathlib import Path + +from alembic import op + +revision = "v1_5_2_001" +down_revision = "v1_5_0_004" + + +def upgrade(): + statements = json.loads((Path(__file__).parents[1] / "schemas/sqlite-v1_5_2_001.json").read_text(encoding="utf-8")) + connection = op.get_bind() + for statement in statements["create"]: + connection.exec_driver_sql(statement) diff --git a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json index f02495e3a8..b739c29b5a 100644 --- a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json @@ -47,6 +47,10 @@ "v1_5_0_004": [ "schemas/sqlite-v1_5_0_004.json", "schemas/mysql-v1_5_0_004.json" + ], + "v1_5_2_001": [ + "schemas/sqlite-v1_5_2_001.json", + "schemas/mysql-v1_5_2_001.json" ] }, "sqlite_baselines": { @@ -85,6 +89,9 @@ ], "v1_5_0_004": [ "cfafc8c1d4f0207e5d04febca1e3f9f9a91948d15fb85678de3765d8e772efdc" + ], + "v1_5_2_001": [ + "31f944d42fe907c48c47081a4a19a9ea16355772e925a7a1ca8b58e763ac1997" ] }, "affected_objects": [ @@ -146,6 +153,7 @@ "pc_atomic_memory_evidence", "pc_atomic_memory_evidence_history", "pc_atomic_memory_evidence_schema", + "pc_atomic_memory_idempotency", "pc_candidate_heads", "pc_candidate_versions", "pc_connector_checkpoints", @@ -340,6 +348,11 @@ "artifact_storage", "portable_storage", "atomic_memory_evidence_projection" + ], + "v1_5_2_001": [ + "artifact_storage", + "portable_storage", + "atomic_memory_evidence_projection" ] }, "retained_fingerprints": { @@ -361,7 +374,8 @@ "schemas/mysql-v1_5_0_001.json", "schemas/mysql-v1_5_0_002.json", "schemas/mysql-v1_5_0_003.json", - "schemas/mysql-v1_5_0_004.json" + "schemas/mysql-v1_5_0_004.json", + "schemas/mysql-v1_5_2_001.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/records.py b/src/powercontext/builtin/persistence/records.py index 4c06951b4b..3724e18392 100644 --- a/src/powercontext/builtin/persistence/records.py +++ b/src/powercontext/builtin/persistence/records.py @@ -16,6 +16,7 @@ from __future__ import annotations +import logging from collections.abc import Awaitable, Callable, Mapping, Sequence from contextlib import aclosing from datetime import UTC, datetime @@ -24,14 +25,28 @@ from uuid import uuid4 import rfc8785 -from pydantic import JsonValue, TypeAdapter, ValidationError +from pydantic import BaseModel, JsonValue, TypeAdapter, ValidationError from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncConnection +from powercontext._logging import log_safely from powercontext.artifacts import Artifact, ArtifactRef, StableHandle from powercontext.builtin.artifacts.atomic_memory.errors import AtomicMemoryConflictError +from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent from powercontext.builtin.persistence.artifact_handles import ArtifactHandleRepository from powercontext.builtin.persistence.artifacts import ArtifactRepository, with_artifact_content +from powercontext.builtin.persistence.atomic_memory_idempotency import ( + MemoryIdempotencyConflict, + MemoryIdempotencyKey, + MemoryIdempotencyReceipt, + bind_receipt, + find_receipt, + namespace_digest, + remove_expired_receipts, + replay, + request_digest, +) from powercontext.builtin.persistence.cursor_codec import SignedCursorCodec from powercontext.builtin.persistence.custom_artifacts import StoredArtifactContent, custom_artifact_repository from powercontext.builtin.persistence.database import AsyncDatabase @@ -101,6 +116,8 @@ from powercontext.errors import RevisionConflictError from powercontext.sources import SourceMaterialization, SourceObservation, SourceRef +logger = logging.getLogger(__name__) + Clock = Callable[[], datetime] IdFactory = Callable[[str], str] @@ -419,18 +436,94 @@ async def create_atomic_memories( """Prepare all standalone additions, then commit their Sources and Owners together.""" if not contents: raise InvalidBaseAccessRequestError("entries", "must contain at least one memory") - writer = self._family_writers.get("atomic-memory") - if not isinstance(writer, AtomicMemoryManagementWriter): - raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "batch creation") + writer = self._atomic_creation_writer() commands = [] for content in contents: command = writer.validate_create(content) artifact_id = self._id_factory("atomic-memory") commands.append((artifact_id, command)) + prepared = await self._prepare_atomic_creations(writer, scope_id, commands, execution_context) + async with self._database.transaction() as connection: + return await self._commit_atomic_creations(connection, writer, scope_id, prepared) + + async def create_keyed_atomic_memory( + self, + scope_id: str, + content: dict[str, JsonValue], + *, + idempotency_key: str, + principal: tuple[str, str] | None, + execution_context=None, + ) -> MemoryIdempotencyReceipt: + """Create one memory bound to a retry key, or return the creation the key already names. + + Validation and the request digest finish before the key lookup. Only a miss prepares + projections; the key record commits in the same transaction as the creation. + """ + writer = self._atomic_creation_writer() + command = cast(AtomicMemoryContent, writer.validate_create(content)) + key = MemoryIdempotencyKey(namespace_digest(scope_id, principal, idempotency_key), command) + request_digest(command) + stored = await find_receipt(self._database, key) + if stored is not None and stored.live: + return _replay_receipt(stored, key, scope_id) + artifact_id = self._id_factory("atomic-memory") + prepared = await self._prepare_atomic_creations(writer, scope_id, ((artifact_id, command),), execution_context) + receipt = MemoryIdempotencyReceipt(artifact_id=artifact_id, revision=1, state_version=0) + try: + async with self._database.transaction() as connection: + await bind_receipt(connection, key, scope_id, receipt, replace_expired=stored is not None) + (created,) = await self._commit_atomic_creations(connection, writer, scope_id, prepared) + if (created.artifact_id, created.revision) != (receipt.artifact_id, receipt.revision): + raise RuntimeError("an Atomic Memory creation did not produce revision 1") # noqa: TRY003 + except IntegrityError: + # A concurrent request committed the key first; its creation wins. + concurrent = await find_receipt(self._database, key) + if concurrent is None or not concurrent.live: + raise + return _replay_receipt(concurrent, key, scope_id) + try: + await remove_expired_receipts(self._database) + except Exception as error: + log_safely( + logger, + logging.WARNING, + "Expired memory idempotency keys were not removed", + extra={ + "event": "atomic_memory.idempotency.cleanup_failed", + "operation": "remember_memory", + "unit": "atomic-memory", + "outcome": "failure", + "exception_type": type(error).__name__, + }, + ) + return receipt + + def _atomic_creation_writer(self) -> AtomicMemoryManagementWriter: + writer = self._family_writers.get("atomic-memory") + if not isinstance(writer, AtomicMemoryManagementWriter): + raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "batch creation") + return writer + + async def _prepare_atomic_creations( + self, + writer: AtomicMemoryManagementWriter, + scope_id: str, + commands: Sequence[tuple[str, BaseModel]], + execution_context, + ) -> tuple[tuple[str, BaseModel, AtomicMemoryManagementPrepared], ...]: values = await writer.prepare_creates(scope_id, commands, execution_context=execution_context) - prepared = tuple( + return tuple( (artifact_id, command, value) for (artifact_id, command), value in zip(commands, values, strict=True) ) + + async def _commit_atomic_creations( + self, + connection: AsyncConnection, + writer: AtomicMemoryManagementWriter, + scope_id: str, + prepared: tuple[tuple[str, BaseModel, AtomicMemoryManagementPrepared], ...], + ) -> tuple[ArtifactCreated, ...]: source_values = [] for artifact_id, command, _ in prepared: payload = cast(dict[str, JsonValue], command.model_dump(mode="json", by_alias=True, exclude_none=True)) @@ -453,27 +546,24 @@ async def create_atomic_memories( ), ) ) - created = [] - async with self._database.transaction() as connection: - stored_sources = await self._sources.add_many_with_status(connection, scope_id, source_values) - stored_values = tuple(stored for stored, _ in stored_sources) - source_read_set = await self._sources.preload( - connection, - scope_id, - tuple(stored.ref for stored in stored_values), - known=stored_values, - ) - artifacts = await writer.create_many( - connection, - scope_id, - tuple( - (artifact_id, value, stored.ref) - for (artifact_id, _, value), stored in zip(prepared, stored_values, strict=True) - ), - source_read_set=source_read_set, - ) - created.extend(_artifact_created(scope_id, artifact) for artifact in artifacts) - return tuple(created) + stored_sources = await self._sources.add_many_with_status(connection, scope_id, source_values) + stored_values = tuple(stored for stored, _ in stored_sources) + source_read_set = await self._sources.preload( + connection, + scope_id, + tuple(stored.ref for stored in stored_values), + known=stored_values, + ) + artifacts = await writer.create_many( + connection, + scope_id, + tuple( + (artifact_id, value, stored.ref) + for (artifact_id, _, value), stored in zip(prepared, stored_values, strict=True) + ), + source_read_set=source_read_set, + ) + return tuple(_artifact_created(scope_id, artifact) for artifact in artifacts) async def get_artifact( self, scope_id: str, family: str, artifact_id: str, /, *, execution_context=None @@ -949,6 +1039,13 @@ def _artifact_record( ) +def _replay_receipt(stored, key: MemoryIdempotencyKey, scope_id: str) -> MemoryIdempotencyReceipt: + try: + return replay(stored, key) + except MemoryIdempotencyConflict: + raise BaseValueConflictError("memory_idempotency_key", scope_id) from None + + def _artifact_created(scope_id: str, artifact: Artifact[Any]) -> ArtifactCreated: return ArtifactCreated( scope_id=scope_id, diff --git a/src/powercontext/builtin/persistence/tables.py b/src/powercontext/builtin/persistence/tables.py index 6068aae67a..cef56c020d 100644 --- a/src/powercontext/builtin/persistence/tables.py +++ b/src/powercontext/builtin/persistence/tables.py @@ -1104,6 +1104,26 @@ def _entry_text_type(): ) +# Keyed remember_memory receipts. Only digests of the namespace and request are +# stored; expired rows are disposable and cleaned through the expiry index. +ATOMIC_MEMORY_IDEMPOTENCY_TABLE = Table( + "pc_atomic_memory_idempotency", + SHARED_METADATA, + Column("namespace_digest", identity_string(64), primary_key=True), + Column("digest_version", Integer, nullable=False), + Column("request_digest", identity_string(64), nullable=False), + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), nullable=False), + Column("artifact_id", identity_string(MAX_ARTIFACT_ID_LENGTH), nullable=False), + Column("revision", Integer, nullable=False), + Column("state_version", Integer, nullable=False), + Column("created_at", DateTime(timezone=False).with_variant(DATETIME(fsp=6), "mysql"), nullable=False), + Column("expires_at", DateTime(timezone=False).with_variant(DATETIME(fsp=6), "mysql"), nullable=False), + CheckConstraint("digest_version > 0", name="ck_pc_atomic_memory_idempotency_digest_version"), + CheckConstraint("revision > 0", name="ck_pc_atomic_memory_idempotency_revision"), + CheckConstraint("state_version >= 0", name="ck_pc_atomic_memory_idempotency_state_version"), + Index("ix_pc_atomic_memory_idempotency_expires_at", "expires_at"), +) + SHARED_TABLES = ( ARTIFACT_FAMILY_SCHEMAS_TABLE, SOURCE_JOURNAL_HEADS_TABLE, @@ -1139,6 +1159,7 @@ def _entry_text_type(): SKILL_PACKAGES_TABLE, AGENT_SKILL_TARGETS_TABLE, SKILL_PUBLICATIONS_TABLE, + ATOMIC_MEMORY_IDEMPOTENCY_TABLE, ) diff --git a/src/powercontext/builtin/records.py b/src/powercontext/builtin/records.py index 9cb8106e37..1bb952930e 100644 --- a/src/powercontext/builtin/records.py +++ b/src/powercontext/builtin/records.py @@ -315,6 +315,16 @@ async def create_atomic_memories( self, scope_id: str, contents: tuple[dict[str, JsonValue], ...], *, execution_context: Any = None ) -> tuple[ArtifactCreated, ...]: ... + async def create_keyed_atomic_memory( + self, + scope_id: str, + content: dict[str, JsonValue], + *, + idempotency_key: str, + principal: tuple[str, str] | None, + execution_context: Any = None, + ) -> Any: ... + async def bind_artifact_handle( self, scope_id: str, diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index c952627f3b..5bda6643d1 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -42,6 +42,8 @@ from powercontext.builtin.artifacts.atomic_memory.models import ( AtomicMemoryContent, AtomicMemoryMutationResult, + AtomicMemoryRecord, + AtomicMemoryState, ) from powercontext.builtin.artifacts.experience import ( EXPERIENCE_INCUBATION_WINDOW_LIMIT, @@ -160,11 +162,13 @@ ArtifactGovernance, ArtifactLifecycleState, ) +from powercontext.builtin.persistence.atomic_memory_idempotency import KEY_PATTERN as IDEMPOTENCY_KEY_PATTERN from powercontext.builtin.persistence.bootstrap_receipts import ( BootstrapReceiptRepository, StoredBootstrapReceipt, ) from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.errors import RepositoryNotFoundError from powercontext.builtin.persistence.skill_publications import SkillPublication from powercontext.builtin.publication import ArtifactPublicationApplication from powercontext.builtin.records import ( @@ -174,6 +178,8 @@ ArtifactRevisionPage, ArtifactWrite, BaseValueConflictError, + BaseValueNotFoundError, + InvalidBaseAccessRequestError, LogicalArtifactRecord, RecordService, ScopeSummaryPage, @@ -3830,13 +3836,21 @@ async def search(self, query: str, *, _trace: bool = True, **kwargs): }) return result - async def create(self, contents: Sequence[AtomicMemoryContent], /, *, context=None) -> AtomicMemoryMutationResult: - """Create explicit Atomic Memories in one all-or-nothing batch.""" + async def create( + self, contents: Sequence[AtomicMemoryContent], /, *, idempotency_key: str | None = None, context=None + ) -> AtomicMemoryMutationResult: + """Create explicit Atomic Memories in one all-or-nothing batch. + + With ``idempotency_key``, exactly one memory is created per key namespace; a retry + of the same content returns revision 1 with the state recorded at its creation. + """ values = tuple(content.model_dump(mode="json", by_alias=True, exclude_none=True) for content in contents) async with self._runtime._scoped_operation( self.scope_id, embedding_purpose=ModelUsagePurpose.MEMORY_INDEXING, ): + if idempotency_key is not None: + return await self._create_keyed(values, idempotency_key, context) created = await self._runtime._records().create_atomic_memories( self.scope_id, values, execution_context=context ) @@ -3845,6 +3859,34 @@ async def create(self, contents: Sequence[AtomicMemoryContent], /, *, context=No changed=True, records=records, primary_artifact_id=records[0].artifact.artifact_id ) + async def _create_keyed(self, values, idempotency_key: str, context) -> AtomicMemoryMutationResult: + if len(values) != 1: + raise InvalidBaseAccessRequestError("idempotency_key", "applies to exactly one memory") + if not IDEMPOTENCY_KEY_PATTERN.fullmatch(idempotency_key): + raise InvalidBaseAccessRequestError( + "idempotency_key", "must be 1 to 256 printable ASCII characters, no spaces" + ) + principal = None if context is None or context.principal is None else context.principal + receipt = await self._runtime._records().create_keyed_atomic_memory( + self.scope_id, + values[0], + idempotency_key=idempotency_key, + principal=None if principal is None else (principal.type, principal.id), + execution_context=context, + ) + # Both a new creation and a replay read the exact revision with the caller's + # current authorization, so a concurrent later revision changes neither result. + try: + exact = await self._scoped.get(receipt.artifact_id, revision=receipt.revision, context=context) + except RepositoryNotFoundError: + raise BaseValueNotFoundError( + "artifact", (self.scope_id, "atomic-memory", receipt.artifact_id, receipt.revision) + ) from None + record = AtomicMemoryRecord( + artifact=exact.artifact, state=AtomicMemoryState(state_version=receipt.state_version) + ) + return AtomicMemoryMutationResult(changed=True, records=(record,), primary_artifact_id=receipt.artifact_id) + async def flush(self, /, *, limit: int | None = None, context=None) -> MemoryFlushResult: """Process the next scoped Source window into Atomic Memory.""" return await self._runtime._flush_sources(self.scope_id, limit=limit, context=context) diff --git a/src/powercontext/http/_generated/models.py b/src/powercontext/http/_generated/models.py index 8eafeaf718..67fe7a7324 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -2673,6 +2673,15 @@ class RememberMemoryRequest(BaseModel): pattern="^[^\\r\\n\\u0085\\u2028\\u2029]*\\S[^\\r\\n\\u0085\\u2028\\u2029]*$", ), ] = None + idempotency_key: Annotated[ + StrictStr | None, + Field( + description="Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key.", + max_length=256, + min_length=1, + pattern="^[!-~]{1,256}$", + ), + ] = None class RetireMemoryEntryRequest(BaseModel): diff --git a/src/powercontext/http/_generated/schema.py b/src/powercontext/http/_generated/schema.py index 933b17e3a1..908cee3bc8 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -2630,7 +2630,13 @@ "or pass null. Non-null legacy " "collection revision preconditions are " "unsupported before any write. Response " - "records use true Atomic ArtifactRefs.", + "records use true Atomic ArtifactRefs. " + "With idempotency_key, a retry of the " + "same creation within 24 hours replays " + "the original response, and reuse of " + "the key for different content returns " + "409 idempotency_conflict with " + "details.kind memory_idempotency_key.", "operationId": "remember_memory", "requestBody": { "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RememberMemoryRequest"}}}, @@ -12874,6 +12880,59 @@ "model.", "nullable": True, }, + "idempotency_key": { + "type": "string", + "maxLength": 256, + "minLength": 1, + "pattern": "^[!-~]{1,256}$", + "description": "Optional " + "retry " + "key, " + "unique " + "per " + "operation, " + "Scope " + "and " + "authenticated " + "principal. " + "Generate " + "a " + "fresh " + "unguessable " + "value " + "for " + "each " + "logical " + "write " + "and " + "reuse " + "it " + "only " + "to " + "retry " + "that " + "write. " + "Keys " + "are " + "compared " + "byte " + "for " + "byte " + "and " + "retained " + "for " + "24 " + "hours. " + "Omit " + "it " + "or " + "pass " + "null " + "for " + "no " + "key.", + "nullable": True, + }, }, "additionalProperties": False, "type": "object", diff --git a/src/powercontext/server/app.py b/src/powercontext/server/app.py index 8ecbc2f615..65c29c7e9c 100644 --- a/src/powercontext/server/app.py +++ b/src/powercontext/server/app.py @@ -3533,6 +3533,7 @@ async def remember_memory( raise BaseOperationNotSupportedError("artifact_family", "memory", "collection revision precondition") result = await _scoped_atomic_memory(application, request.scope_id).create( (AtomicMemoryContent(kind=request.kind, text=request.text, description=request.description),), + idempotency_key=request.idempotency_key, context=_atomic_execution_context(http_request, REMEMBER_MEMORY.operation_id), ) return mapping.mutation_response(result) diff --git a/src/powercontext/server/mcp.py b/src/powercontext/server/mcp.py index 3a108f350e..69b9819e43 100644 --- a/src/powercontext/server/mcp.py +++ b/src/powercontext/server/mcp.py @@ -132,7 +132,10 @@ Never treat an Atomic revision as an old collection revision. Legacy citation revise/retire, collection capacity, and collection changes are unsupported. For an explicit future save (remember this / 记住这个供以后使用), call remember_memory with expected_revision omitted or -null and verify its Atomic records. A non-null legacy collection revision precondition is unsupported. Use merge_atomic_memories, +null and verify its Atomic records. A non-null legacy collection revision precondition is unsupported. +To retry a save whose outcome is unknown, resend the same content with the same idempotency_key. Generate a fresh +unguessable key, such as a UUID, for each new save and reuse it only for that save's retries; after +idempotency_conflict, use a new key. Use merge_atomic_memories, change_atomic_memory_lifecycle and restoration previews/restorations only for explicitly requested state changes; current revision and state_version inputs must come from reads. Automatic Source capture is not an explicit Memory write, and enabled hooks do not establish successful recall or persistence. diff --git a/tests/builtin/persistence/test_atomic_description_vector_layout.py b/tests/builtin/persistence/test_atomic_description_vector_layout.py index 7b05f1ddaf..68911030dd 100644 --- a/tests/builtin/persistence/test_atomic_description_vector_layout.py +++ b/tests/builtin/persistence/test_atomic_description_vector_layout.py @@ -43,7 +43,7 @@ def test_managed_sqlite_vector_schema_includes_registered_nullable_description(t database = tmp_path / "vector.db" runner = SQLiteMigrationRunner(database, bundle, configuration=configuration) result = runner.apply(plan_id=runner.plan().plan_id, accepted=True, maintenance_confirmed=True) - assert result.revision == "v1_5_0_004" + assert result.revision == "v1_5_2_001" with closing(sqlite3.connect(database)) as connection: columns = {row[1]: row for row in connection.execute("PRAGMA table_info(pc_atomic_memory_current)")} assert columns["description"][2:4] == ("VARCHAR(200)", 0) @@ -156,11 +156,19 @@ def test_description_upgrade_preserves_registered_owner_recovery_and_evidence(tm upgraded = SQLiteMigrationRunner(database, current, configuration=configuration) plan = upgraded.plan() assert plan.source_revision == "v1_4_1_004" - assert plan.target_revision == "v1_5_0_004" - assert plan.revisions == ("v1_4_1_005", "v1_4_1_006", "v1_5_0_001", "v1_5_0_002", "v1_5_0_003", "v1_5_0_004") + assert plan.target_revision == "v1_5_2_001" + assert plan.revisions == ( + "v1_4_1_005", + "v1_4_1_006", + "v1_5_0_001", + "v1_5_0_002", + "v1_5_0_003", + "v1_5_0_004", + "v1_5_2_001", + ) assert plan.domain_steps == ("artifact_storage", "atomic_memory_evidence", "atomic_memory_evidence_projection") assert upgraded.evidence_path.read_bytes() == original_evidence_bytes - assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == "v1_5_0_004" + assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == "v1_5_2_001" assert upgraded.verify().state == "ready" evidence = json.loads(upgraded.evidence_path.read_text(encoding="utf-8")) for revision, checksum in original_evidence["release_checksums"].items(): diff --git a/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py b/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py index 0d9f2bc9a6..c18cfd9f0c 100644 --- a/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py +++ b/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py @@ -167,6 +167,7 @@ def test_evidence_upgrade_accepts_upstream_history_and_preserves_data(tmp_path, EVIDENCE_REVISION, PROJECTION_REVISION, "v1_5_0_004", + "v1_5_2_001", ) assert plan.domain_steps == ( "artifact_storage", @@ -194,6 +195,7 @@ def test_evidence_upgrade_accepts_upstream_history_and_preserves_data(tmp_path, EVIDENCE_REVISION, PROJECTION_REVISION, "v1_5_0_004", + "v1_5_2_001", } ready = reopened.plan() assert ready.state == "ready" @@ -247,7 +249,7 @@ def test_evidence_projection_upgrade_preserves_registered_evidence_revision(tmp_ before = old.evidence_path.read_bytes() upgraded = SQLiteMigrationRunner(database, current, configuration=config) plan = upgraded.plan() - assert plan.revisions == (PROJECTION_REVISION, "v1_5_0_004") + assert plan.revisions == (PROJECTION_REVISION, "v1_5_0_004", "v1_5_2_001") assert plan.domain_steps == ("atomic_memory_evidence_projection",) assert old.evidence_path.read_bytes() == before assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == current.head diff --git a/tests/builtin/persistence/test_full_server_migrations.py b/tests/builtin/persistence/test_full_server_migrations.py index 74af6392ae..c8388f957c 100644 --- a/tests/builtin/persistence/test_full_server_migrations.py +++ b/tests/builtin/persistence/test_full_server_migrations.py @@ -73,7 +73,7 @@ def dump(path): def test_complete_upgrade_preserves_history_backup_and_repeated_apply(source): before = dump(source.database) plan = source.plan() - assert plan.source_revision == "s1300" and plan.target_revision == "v1_5_0_004" + assert plan.source_revision == "s1300" and plan.target_revision == "v1_5_2_001" assert plan.revisions == ( "s1400", "s1401", @@ -85,6 +85,7 @@ def test_complete_upgrade_preserves_history_backup_and_repeated_apply(source): "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", + "v1_5_2_001", ) assert dump(source.database) == before result = apply(source) diff --git a/tests/builtin/persistence/test_mysql_initialization_preflight.py b/tests/builtin/persistence/test_mysql_initialization_preflight.py index 87abc9190a..0c3eb96e42 100644 --- a/tests/builtin/persistence/test_mysql_initialization_preflight.py +++ b/tests/builtin/persistence/test_mysql_initialization_preflight.py @@ -253,7 +253,7 @@ def test_evidence_recovery_resumes_before_final_schema_marker(tmp_path, monkeypa before = database.read_bytes(), journal.path.read_bytes() plan = runner.plan() assert plan.state == "recovery_required" and plan.source_revision == predecessor - assert plan.revisions == ("v1_5_0_002", "v1_5_0_003", "v1_5_0_004") + assert plan.revisions == ("v1_5_0_002", "v1_5_0_003", "v1_5_0_004", "v1_5_2_001") assert (database.read_bytes(), journal.path.read_bytes()) == before assert connection.exec_driver_sql("SELECT schema_version FROM pc_atomic_memory_evidence_schema").all() == [] diff --git a/tests/builtin/persistence/test_mysql_migration_runner.py b/tests/builtin/persistence/test_mysql_migration_runner.py index 2894087ff8..85280c2200 100644 --- a/tests/builtin/persistence/test_mysql_migration_runner.py +++ b/tests/builtin/persistence/test_mysql_migration_runner.py @@ -706,7 +706,7 @@ def test_oceanbase_server_upgrade_with_separate_code_cache_preserves_history( ) assert runner.plan(backup_policy="manual").source_revision == "s1300" result = _apply(runner, policy="manual") - assert result.readiness_scope == "server" and result.revision == "v1_5_0_004" + assert result.readiness_scope == "server" and result.revision == "v1_5_2_001" assert runner.verify().state == "ready" prepare_server_storage(settings) assert not _apply(runner, policy="manual").changed @@ -837,7 +837,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("v1_5_0_004", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_5_2_001", "dedicated", b'{"history":"unchanged"}') (main_path,) = backend.evidence_directory.glob("*/maintenance.json") evidence = json.loads(main_path.read_text()) @@ -847,7 +847,7 @@ def inspect_history(connection, identity, guard): for inspect in (runner.plan, runner.verify, runner.apply): with pytest.raises(MigrationError, match="checksum_conflict"): inspect() - assert backend.connections().run(inspect_history) == ("v1_5_0_004", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_5_2_001", "dedicated", b'{"history":"unchanged"}') assert { path: path.read_bytes() for path in backend.evidence_directory.rglob("maintenance.json") } == original_evidence @@ -914,7 +914,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("v1_5_0_004", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_5_2_001", b'{"history":"unchanged"}') def test_mysql_registered_projection_repair_preserves_authority_and_revision(backend: _BackendTarget) -> None: @@ -982,7 +982,7 @@ def inspect_content(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_content) == ("v1_5_0_004", content, "Preserve immutable nebula evidence.") + assert backend.connections().run(inspect_content) == ("v1_5_2_001", content, "Preserve immutable nebula evidence.") @pytest.mark.parametrize("origin", ("empty", "released")) @@ -1146,7 +1146,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan _load_full_server_baseline(backend) runner = _full_server_runner(backend) original = runner.plan(backup_policy="manual") - assert original.source_revision == "s1300" and original.target_revision == "v1_5_0_004" + assert original.source_revision == "s1300" and original.target_revision == "v1_5_2_001" _interrupt_after_ddl(runner, interruption) journals = list(backend.evidence_directory.rglob("maintenance.json")) assert len(journals) == 1 @@ -1168,7 +1168,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan result = _apply(resumed, policy="manual") - assert result.readiness_scope == "server" and result.revision == "v1_5_0_004" + assert result.readiness_scope == "server" and result.revision == "v1_5_2_001" assert result.backup_state == "user_confirmed" assert result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" @@ -1248,7 +1248,7 @@ def client_active(connection: Connection | None, _identity: BackendIdentity, _gu # interruption. An arbitrary remote failure cannot be acknowledged blindly. resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_5_0_004" + assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_5_2_001" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journals[0].read_text(encoding="utf-8")) diff --git a/tests/builtin/persistence/test_portable_storage_migration.py b/tests/builtin/persistence/test_portable_storage_migration.py index d016bed258..f5f610cc3a 100644 --- a/tests/builtin/persistence/test_portable_storage_migration.py +++ b/tests/builtin/persistence/test_portable_storage_migration.py @@ -127,8 +127,9 @@ def test_registered_s1401_upgrade_preserves_completed_evidence_and_matches_fresh "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", + "v1_5_2_001", ) - assert apply(upgraded).revision == "v1_5_0_004" + assert apply(upgraded).revision == "v1_5_2_001" assert upgraded.verify().state == "ready" assert not apply(upgraded).changed fresh = SQLiteMigrationRunner(tmp_path / "fresh.db", bundle, configuration=config) @@ -187,11 +188,20 @@ def test_source_write_plugin_upgrade_preserves_data_and_registration(tmp_path, v bundle = server_bundle(embedding_profile=embedding) upgraded = SQLiteMigrationRunner(database, bundle, configuration=config) assert upgraded.plan().revisions == ( - ("v1_4_1_005", "v1_4_1_006", "v1_5_0_001", "v1_5_0_002", "v1_5_0_003", "v1_5_0_004") + ("v1_4_1_005", "v1_4_1_006", "v1_5_0_001", "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", "v1_5_2_001") if include_owner - else ("v1_4_1_004", "v1_4_1_005", "v1_4_1_006", "v1_5_0_001", "v1_5_0_002", "v1_5_0_003", "v1_5_0_004") + else ( + "v1_4_1_004", + "v1_4_1_005", + "v1_4_1_006", + "v1_5_0_001", + "v1_5_0_002", + "v1_5_0_003", + "v1_5_0_004", + "v1_5_2_001", + ) ) - assert apply(upgraded).revision == "v1_5_0_004" + assert apply(upgraded).revision == "v1_5_2_001" definition = b'{"configuration":{"id":"tickets","entry":"tickets"}}' with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("SELECT title FROM pc_scopes").fetchall() == [("preserved",)] diff --git a/tests/builtin/persistence/test_release140_server_migrations.py b/tests/builtin/persistence/test_release140_server_migrations.py index fd95f653eb..54161e4a4a 100644 --- a/tests/builtin/persistence/test_release140_server_migrations.py +++ b/tests/builtin/persistence/test_release140_server_migrations.py @@ -157,6 +157,7 @@ def test_registered_sources_choose_distinct_lineages(tmp_path, release, expected "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", + "v1_5_2_001", ) @@ -371,7 +372,7 @@ def connect(): finally: engine.dispose() - assert _apply(runner).revision == "v1_5_0_004" + assert _apply(runner).revision == "v1_5_2_001" assert runner.verify().state == "ready" assert not _apply(runner).changed app = create_server_app( diff --git a/tests/e2e/test_atomic_memory_description_upgrade.py b/tests/e2e/test_atomic_memory_description_upgrade.py index 48db983ef8..ce6d044c87 100644 --- a/tests/e2e/test_atomic_memory_description_upgrade.py +++ b/tests/e2e/test_atomic_memory_description_upgrade.py @@ -85,9 +85,9 @@ def test_nonempty_released_memory_upgrades_without_rewriting_history(tmp_path, r ) result = _apply(runner) - assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_5_0_004" + assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_5_2_001" verified = runner.verify() - assert verified.state == "ready" and verified.readiness_scope == "server" and verified.revision == "v1_5_0_004" + assert verified.state == "ready" and verified.readiness_scope == "server" and verified.revision == "v1_5_2_001" assert not _apply(runner).changed with closing(sqlite3.connect(runner.database)) as connection: assert ( diff --git a/tests/e2e/test_remember_memory_idempotency.py b/tests/e2e/test_remember_memory_idempotency.py new file mode 100644 index 0000000000..f46f920260 --- /dev/null +++ b/tests/e2e/test_remember_memory_idempotency.py @@ -0,0 +1,472 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Keyed remember_memory retries create one memory and replay its original result.""" + +from __future__ import annotations + +import asyncio +import multiprocessing +import sqlite3 +from contextlib import asynccontextmanager, closing +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +import pytest + +from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent +from powercontext.builtin.persistence.family_management import AtomicMemoryManagementWriter +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.records import InvalidBaseAccessRequestError +from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_runtime +from powercontext.builtin.scope import ScopeDraft +from powercontext.client import PowerContextClient +from powercontext.http import RememberMemoryRequest +from powercontext.server.authentication import AuthenticationResult, ProviderReadiness +from powercontext.server.authz import PrincipalRef +from powercontext.server.authz.composition import open_builtin_access_control +from powercontext.server.factory import create_server_app +from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings +from tests.e2e.server_storage import prepare_server_database + +ADMIN = PrincipalRef(type="service", id="admin") + + +def _settings(database: Path, **options) -> ServerSettings: + return ServerSettings( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), + mcp=McpConfig(enabled=False), + metrics=MetricsConfig(enabled=False), + **options, + ) + + +@asynccontextmanager +async def _open(database: Path): + app = create_server_app(settings=_settings(database)) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client, + ): + yield client + + +async def _default_scope(client: httpx.AsyncClient) -> str: + sdk = PowerContextClient("http://testserver", http_client=client, trust_transport_security=True) + return (await sdk.get_default_scope()).scope_id + + +def _count(database: Path, sql: str, *parameters) -> int: + with closing(sqlite3.connect(database)) as connection: + return connection.execute(sql, parameters).fetchone()[0] + + +def _memories(database: Path) -> int: + return _count(database, "SELECT COUNT(DISTINCT artifact_id) FROM pc_artifacts WHERE family = 'atomic-memory'") + + +def _sources(database: Path) -> int: + return _count(database, "SELECT COUNT(*) FROM pc_sources") + + +async def _remember(client: httpx.AsyncClient, scope_id: str, text: str, key: str | None = None, **fields): + body = {"scope_id": scope_id, "kind": "preference", "text": text, **fields} + if key is not None: + body["idempotency_key"] = key + return await client.post("/v1/memory/remember", json=body) + + +def test_keyed_retry_replays_original_creation(tmp_path: Path) -> None: + database = tmp_path / "replay.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + key = f"retry-{uuid4()}" + first = await _remember(client, scope_id, "Cafe\N{COMBINING ACUTE ACCENT} order is oat milk", key) + assert first.status_code == 200, first.text + created = first.json() + assert created["changed"] is True + record = created["records"][0] + assert record["artifact"]["revision"] == 1 + assert (record["state"], record["state_version"], record["merged_into_id"]) == ("active", 0, None) + memories, sources = _memories(database), _sources(database) + + # Equivalent stored content replays: NFC, outer whitespace, the default description, and reason. + retries: tuple[tuple[str, dict[str, str | None]], ...] = ( + ("Cafe\N{COMBINING ACUTE ACCENT} order is oat milk", {}), + (" Café order is oat milk \n", {}), + ("Café order is oat milk", {"description": None}), + ("Café order is oat milk", {"description": "Café order is oat milk"}), + ("Café order is oat milk", {"reason": "retry after a lost response"}), + ) + for text, retry in retries: + replayed = await _remember(client, scope_id, text, key, **retry) + assert replayed.status_code == 200, replayed.text + assert replayed.json() == created + sdk = PowerContextClient("http://testserver", http_client=client, trust_transport_security=True) + through_sdk = await sdk.remember_memory( + RememberMemoryRequest( + scope_id=scope_id, kind="preference", text="Café order is oat milk", idempotency_key=key + ) + ) + assert through_sdk.model_dump(mode="json") == created + assert (_memories(database), _sources(database)) == (memories, sources) + + # Keys are independent of each other, and requests without a key keep creating. + other = await _remember(client, scope_id, "Café order is oat milk", f"retry-{uuid4()}") + assert other.json()["records"][0]["artifact"]["artifact_id"] != record["artifact"]["artifact_id"] + for _ in range(2): + unkeyed = await _remember(client, scope_id, "Café order is oat milk") + assert unkeyed.status_code == 200, unkeyed.text + # A keyed creation answers exactly as an unkeyed creation of the same content. + unkeyed_record = unkeyed.json()["records"][0] + assert {**unkeyed_record, "artifact": None} == {**record, "artifact": None} + assert unkeyed_record["artifact"].keys() == record["artifact"].keys() + assert _memories(database) == memories + 3 + + with closing(sqlite3.connect(database)) as connection: + rows = connection.execute("SELECT * FROM pc_atomic_memory_idempotency").fetchall() + assert len(rows) == 2 + assert not any(key in str(value) for row in rows for value in row) + + asyncio.run(scenario()) + + +def test_replay_returns_creation_state_after_the_memory_changes(tmp_path: Path) -> None: + database = tmp_path / "state.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Deploy on Tuesdays", "deploy-day") + assert first.status_code == 200, first.text + record = first.json()["records"][0] + forgotten = await client.post( + "/v1/atomic-memory/lifecycle", + json={ + "scope_id": scope_id, + "target": {"artifact": record["artifact"], "state_version": record["state_version"]}, + "state": "forgotten", + }, + ) + assert forgotten.status_code == 200, forgotten.text + replayed = await _remember(client, scope_id, "Deploy on Tuesdays", "deploy-day") + assert replayed.status_code == 200, replayed.text + assert replayed.json() == first.json() + assert _memories(database) == 1 + + asyncio.run(scenario()) + + +def test_reused_key_with_different_content_conflicts_without_writing(tmp_path: Path) -> None: + database = tmp_path / "conflict.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Use pnpm", "tooling") + assert first.status_code == 200, first.text + memories, sources = _memories(database), _sources(database) + for text, fields in ( + ("Use npm", {}), + ("Use pnpm", {"kind": "fact"}), + ("Use pnpm", {"description": "Package manager choice"}), + ): + conflict = await _remember(client, scope_id, text, "tooling", **fields) + assert conflict.status_code == 409, conflict.text + error = conflict.json()["error"] + assert error["code"] == "idempotency_conflict" + assert error["details"] == {"kind": "memory_idempotency_key"} + assert (_memories(database), _sources(database)) == (memories, sources) + replayed = await _remember(client, scope_id, "Use pnpm", "tooling") + assert replayed.json() == first.json() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("key", ["", "has space", "tab\tkey", "é", "k" * 257]) +def test_invalid_key_is_rejected_before_any_write(tmp_path: Path, key: str) -> None: + database = tmp_path / "invalid.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + before = _sources(database) + rejected = await _remember(client, scope_id, "Never stored", key) + assert rejected.status_code == 422, rejected.text + assert rejected.json()["error"]["code"] == "invalid_request" + assert (_memories(database), _sources(database)) == (0, before) + + asyncio.run(scenario()) + + +def test_in_process_create_applies_the_same_key_rule() -> None: + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + for key in ("", "has space", "é", "k" * 257): + with pytest.raises(InvalidBaseAccessRequestError): + await memory.create(content, idempotency_key=key) + assert (await memory.list()).items == () + first = await memory.create(content, idempotency_key="sdk-1") + assert await memory.create(content, idempotency_key="sdk-1") == first + + asyncio.run(scenario()) + + +def test_keyed_request_keeps_expected_revision_rejection(tmp_path: Path) -> None: + database = tmp_path / "expected.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + unkeyed = await _remember(client, scope_id, "Never stored", expected_revision=1) + keyed = await _remember(client, scope_id, "Never stored", "precondition", expected_revision=1) + assert unkeyed.status_code != 200 + assert (keyed.status_code, keyed.json()["error"]["code"]) == ( + unkeyed.status_code, + unkeyed.json()["error"]["code"], + ) + assert _memories(database) == 0 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 0 + + asyncio.run(scenario()) + + +def test_expired_key_starts_a_new_creation_and_cleanup_is_bounded(tmp_path: Path) -> None: + database = tmp_path / "expiry.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Prefer short PRs", "expiring") + assert first.status_code == 200, first.text + live = await _remember(client, scope_id, "Prefer squash merges", "still-live") + assert live.status_code == 200, live.text + with closing(sqlite3.connect(database)) as connection: + expiring = connection.execute( + "SELECT * FROM pc_atomic_memory_idempotency WHERE artifact_id = ?", + (first.json()["records"][0]["artifact"]["artifact_id"],), + ).fetchone() + connection.execute("UPDATE pc_atomic_memory_idempotency SET expires_at = '2000-01-01 00:00:00.000000'") + connection.execute( + "UPDATE pc_atomic_memory_idempotency SET expires_at = '2999-01-01 00:00:00.000000' WHERE artifact_id = ?", + (live.json()["records"][0]["artifact"]["artifact_id"],), + ) + for index in range(40): + connection.execute( + "INSERT INTO pc_atomic_memory_idempotency VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (f"{index:064x}", *expiring[1:7], "2000-01-01 00:00:00.000000", "2000-01-01 00:00:00.000000"), + ) + connection.commit() + expired_before = _count( + database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at < '2001-01-01 00:00:00'" + ) + + recreated = await _remember(client, scope_id, "Prefer short PRs", "expiring") + assert recreated.status_code == 200, recreated.text + recreated_id = recreated.json()["records"][0]["artifact"]["artifact_id"] + assert recreated_id != first.json()["records"][0]["artifact"]["artifact_id"] + assert (await _remember(client, scope_id, "Prefer short PRs", "expiring")).json() == recreated.json() + assert (await _remember(client, scope_id, "Prefer squash merges", "still-live")).json() == live.json() + + expired_after = _count( + database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at < '2001-01-01 00:00:00'" + ) + assert expired_before == 41 + # The recreation replaced its own expired key, and its cleanup removed part of the + # other backlog: a bounded batch, not a full scan. + assert 0 < expired_after < expired_before - 1 + assert ( + _count( + database, + "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at > '2001-01-01 00:00:00'", + ) + == 2 + ) + + asyncio.run(scenario()) + + +def test_concurrent_keyed_requests_create_exactly_once(tmp_path: Path, monkeypatch) -> None: + database = tmp_path / "race.db" + original = AtomicMemoryManagementWriter.prepare_creates + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + barrier = asyncio.Barrier(3) + + async def prepare_together(self, *args, **kwargs): + # Every request has missed the lookup before any of them writes. + await barrier.wait() + return await original(self, *args, **kwargs) + + monkeypatch.setattr(AtomicMemoryManagementWriter, "prepare_creates", prepare_together) + responses = await asyncio.gather(*(_remember(client, scope_id, "Race once", "race") for _ in range(3))) + assert [response.status_code for response in responses] == [200, 200, 200], [r.text for r in responses] + assert responses[0].json() == responses[1].json() == responses[2].json() + assert _memories(database) == 1 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 1 + + asyncio.run(scenario()) + + +def _remember_in_process(database: str, scope_id: str, text: str, barrier, results) -> None: + async def run() -> None: + original = AtomicMemoryManagementWriter.prepare_creates + + async def prepare_together(self, *args, **kwargs): + await asyncio.to_thread(barrier.wait, 120) + return await original(self, *args, **kwargs) + + AtomicMemoryManagementWriter.prepare_creates = prepare_together + async with _open(Path(database)) as client: + response = await _remember(client, scope_id, text, "cross-process") + results.put((response.status_code, response.json())) + + asyncio.run(run()) + + +@pytest.mark.parametrize("texts", [("Same body",) * 3, ("Body A", "Body B", "Body A")], ids=["same", "mixed"]) +def test_keyed_requests_from_separate_processes_create_exactly_once(tmp_path: Path, texts) -> None: + database = tmp_path / "processes.db" + + async def prepare() -> str: + async with _open(database) as client: + return await _default_scope(client) + + scope_id = asyncio.run(prepare()) + context = multiprocessing.get_context("spawn") + barrier = context.Barrier(len(texts)) + results = context.Queue() + workers = [ + context.Process(target=_remember_in_process, args=(str(database), scope_id, text, barrier, results)) + for text in texts + ] + for worker in workers: + worker.start() + outcomes = [results.get(timeout=300) for _ in workers] + for worker in workers: + worker.join(timeout=60) + assert worker.exitcode == 0 + assert _memories(database) == 1 + succeeded = [body for status, body in outcomes if status == 200] + assert succeeded and all(body == succeeded[0] for body in succeeded) + winner = succeeded[0]["records"][0]["text"] + assert len(succeeded) == texts.count(winner) + conflicts = [body for status, body in outcomes if status != 200] + assert len(conflicts) == len(texts) - texts.count(winner) + assert all(body["error"]["details"] == {"kind": "memory_idempotency_key"} for body in conflicts) + + +class _Authentication: + async def authenticate(self, request): + identity = request.headers.get("authorization", "Bearer admin").removeprefix("Bearer ") + return AuthenticationResult(subject=ADMIN if identity == "admin" else PrincipalRef(type="user", id=identity)) + + async def readiness(self): + return ProviderReadiness(ready=True) + + +async def _grant(client: httpx.AsyncClient, scope_id: str, principal: str) -> dict[str, Any]: + response = await client.post( + "/v1/access/bindings/create", + json={ + "subject": {"type": "user", "id": principal}, + "resource": {"type": "scope", "scope_id": scope_id}, + "role": "scope.contributor", + "idempotency_key": f"{principal}-contributor", + }, + ) + assert response.status_code == 201, response.text + return response.json() + + +def test_access_controlled_keys_are_per_principal_and_replays_reauthorize(tmp_path: Path) -> None: + database = tmp_path / "access.db" + + async def scenario() -> None: + server_settings = _settings( + database, + runtime=RuntimeConfig(artifact_processing_families=()), + access=AccessControlConfig(mode="enforced", deployment_id="idempotency"), + ) + await asyncio.to_thread(prepare_server_database, server_settings) + async with open_builtin_access_control( + server_settings.database, bootstrap_administrators=(ADMIN,), deployment_id="idempotency" + ) as access: + app = create_server_app( + settings=server_settings, + authentication_provider=_Authentication(), + access_control=access, + scheduler_path=tmp_path / "scheduler.db", + ) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + created = await client.post( + "/v1/scopes", json={"title": "Keys", "summary": "Idempotent writes", "idempotency_key": "keys"} + ) + assert created.status_code == 201, created.text + scope_id = created.json()["scope_id"] + alice_grant = await _grant(client, scope_id, "alice") + await _grant(client, scope_id, "bob") + alice = {"Authorization": "Bearer alice"} + bob = {"Authorization": "Bearer bob"} + body = {"scope_id": scope_id, "kind": "note", "text": "Private plan", "idempotency_key": "shared"} + + first = await client.post("/v1/memory/remember", json=body, headers=alice) + assert first.status_code == 200, first.text + again = await client.post("/v1/memory/remember", json=body, headers=alice) + assert again.json() == first.json() + other = await client.post("/v1/memory/remember", json=body, headers=bob) + assert other.status_code == 200, other.text + assert other.json()["records"][0]["artifact"] != first.json()["records"][0]["artifact"] + + invalid = await client.post( + "/v1/memory/remember", json={**body, "idempotency_key": "bad key"}, headers=alice + ) + assert invalid.status_code == 422 + assert invalid.json()["error"]["code"] in {"invalid_request", "invalid_access_request"} + + revoked = await client.post( + "/v1/access/bindings/revoke", + json={ + "binding_id": alice_grant["binding_id"], + "expected_version": alice_grant["version"], + "idempotency_key": "revoke-alice", + }, + ) + assert revoked.status_code == 200, revoked.text + denied = await client.post("/v1/memory/remember", json=body, headers=alice) + assert denied.status_code == 403 + assert "Private plan" not in denied.text + assert _memories(database) == 2 + + with closing(sqlite3.connect(database)) as connection: + rows = connection.execute("SELECT * FROM pc_atomic_memory_idempotency").fetchall() + assert len(rows) == 2 + assert not any( + secret in str(value) for row in rows for value in row for secret in ("shared", "alice", "bob") + ) + + asyncio.run(scenario()) diff --git a/tests/e2e/test_source_citation_locators.py b/tests/e2e/test_source_citation_locators.py index 4a21fd5c2a..324ff8c999 100644 --- a/tests/e2e/test_source_citation_locators.py +++ b/tests/e2e/test_source_citation_locators.py @@ -69,11 +69,12 @@ def test_locators_survive_upgrade_reopen_http_and_mcp(tmp_path): # Reconstruct the previous registered layout, preserving its real historical evidence. with sqlite3.connect(database) as connection: connection.execute("DROP TABLE pc_artifact_source_locators") + connection.execute("DROP TABLE pc_atomic_memory_idempotency") connection.execute("UPDATE pc_schema_revision SET version_num = 'v1_5_0_003'") runner = deployment_runner(_settings(database)) plan = runner.plan() - assert plan.revisions == ("v1_5_0_004",) + assert plan.revisions == ("v1_5_0_004", "v1_5_2_001") runner.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True) locators = [ diff --git a/tests/e2e/test_source_write.py b/tests/e2e/test_source_write.py index c3e0d29fa1..3d4d325069 100644 --- a/tests/e2e/test_source_write.py +++ b/tests/e2e/test_source_write.py @@ -76,7 +76,7 @@ async def scenario(): plan = runner.plan() if baseline: assert plan.source_revision == "v1_5_0_003" - assert plan.revisions == ("v1_5_0_004",) + assert plan.revisions == ("v1_5_0_004", "v1_5_2_001") runner.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True) async with running_server(tmp_path) as (admin, url, _process): assert await load_write_cli(deployment / "write.yml", url) == loaded diff --git a/tests/native/test_oceanbase_engine_recovery.py b/tests/native/test_oceanbase_engine_recovery.py index 5e9ae7da8d..64f083e307 100644 --- a/tests/native/test_oceanbase_engine_recovery.py +++ b/tests/native/test_oceanbase_engine_recovery.py @@ -175,7 +175,7 @@ def ping(connection, _identity, _guard): _apply(_full_server_runner(backend), policy="manual") resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.revision == "v1_5_0_004" and result.readiness_scope == "server" + assert result.state == "ready" and result.revision == "v1_5_2_001" and result.readiness_scope == "server" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journal.read_text()) diff --git a/tests/native/test_personal_service_lifecycle.py b/tests/native/test_personal_service_lifecycle.py index af304fa261..3b8d27e1cc 100644 --- a/tests/native/test_personal_service_lifecycle.py +++ b/tests/native/test_personal_service_lifecycle.py @@ -401,7 +401,7 @@ def test_native_public_migration_switches_an_installed_130_service( if failure in {"startup", "switch"}: assert applied.exit_code == 1, applied.output assert result["error"] == "service_start_failed" - assert result["database_state"] == "ready" and result["revision"] == "v1_5_0_004" + assert result["database_state"] == "ready" and result["revision"] == "v1_5_2_001" assert adapter.manager_state() in {ManagerState.INACTIVE, ManagerState.FAILED} phase = "switching" if failure == "switch" else "start_failed" assert json.loads(controller.maintenance_path.read_text())["phase"] == phase diff --git a/tests/pydantic_ai_adapter/test_toolset.py b/tests/pydantic_ai_adapter/test_toolset.py index 0a9ee2068f..d008e11dcf 100644 --- a/tests/pydantic_ai_adapter/test_toolset.py +++ b/tests/pydantic_ai_adapter/test_toolset.py @@ -98,6 +98,7 @@ async def scenario() -> Any: "reason": "shared contract", "expected_revision": None, "description": None, + "idempotency_key": None, } assert "assembly" not in client.prepare_requests[0].model_fields_set assert client.prepare_requests[0].model_dump(mode="json", exclude_unset=True) == { diff --git a/tests/release_upgrades/README.md b/tests/release_upgrades/README.md index 585b218324..4972549801 100644 --- a/tests/release_upgrades/README.md +++ b/tests/release_upgrades/README.md @@ -8,7 +8,7 @@ embedded seekDB Code configurations. Missing full migration integration (#2154) The declared target release is **1.5.1**. Public migration output maps the two source baselines to `v1_3_0_000` / `v1_4_0_000` and the shared steps to `v1_4_1_001`–`v1_4_1_006`, followed by -`v1_5_0_001`–`v1_5_0_004`. The suite checks these names while retaining the original revision IDs in execution +`v1_5_0_001`–`v1_5_0_004` and `v1_5_2_001`. The suite checks these names while retaining the original revision IDs in execution and recovery evidence. The `automatic_sources` policy uses `strategy: "fixed-version"` and `source_version: "1.3.0"`. diff --git a/tests/test_managed_atomic_maintenance.py b/tests/test_managed_atomic_maintenance.py index 50992d4929..82267df017 100644 --- a/tests/test_managed_atomic_maintenance.py +++ b/tests/test_managed_atomic_maintenance.py @@ -76,7 +76,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b assert inspected.exit_code == 0, inspected.output plan = json.loads(inspected.output) assert plan["source_revision"] == "s1300" - assert plan["target_revision"] == "v1_5_0_004" + assert plan["target_revision"] == "v1_5_2_001" assert plan["readiness_scope"] == "server" assert historical.read_bytes() == original @@ -103,7 +103,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b with closing(sqlite3.connect(result["backup_ref"])) as connection: assert tuple(connection.iterdump()) == original_dump with closing(sqlite3.connect(historical)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_0_004",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_2_001",)] assert connection.execute("SELECT content FROM pc_artifacts").fetchall() == [(b'{"history":"unchanged"}',)] verified = CliRunner().invoke(cli, [*arguments, "--action", "verify"]) assert verified.exit_code == 0, verified.output diff --git a/tests/test_managed_processing_maintenance.py b/tests/test_managed_processing_maintenance.py index 989ca7e786..79411106da 100644 --- a/tests/test_managed_processing_maintenance.py +++ b/tests/test_managed_processing_maintenance.py @@ -75,7 +75,7 @@ def test_registered_mode_switch_backs_up_preserves_revision_and_fences_old_worke assert result.backup_state == "completed" assert result.backup_ref and Path(result.backup_ref).is_file() with closing(sqlite3.connect(path)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_0_004",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_2_001",)] assert ( json.loads(connection.execute("SELECT config_manifest FROM pc_artifact_processing_schema").fetchone()[0])[ "mode" diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 68d3850c19..0a51640f1f 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -47,7 +47,8 @@ async def inspect() -> tuple[str, list[Any]]: assert guidance names = {tool.name for tool in tools} referenced_names = set(re.findall(r"\b[a-z]+(?:_[a-z]+)+\b", guidance)) - assert referenced_names - {"state_version", "merged_into_id", "expected_revision", "status_code"} <= names + fields = {"state_version", "merged_into_id", "expected_revision", "status_code", "idempotency_key"} + assert referenced_names - fields - {"idempotency_conflict"} <= names if directory := os.environ.get("POWERCONTEXT_GUIDANCE_EXPORT"): root = Path(__file__).parents[1] for host in ("codex", "claude-code", "workbuddy", "agent-plugin", "minimax"): diff --git a/tests/test_migration_revision_names.py b/tests/test_migration_revision_names.py index 3de63bddb7..987a40c1ff 100644 --- a/tests/test_migration_revision_names.py +++ b/tests/test_migration_revision_names.py @@ -65,9 +65,10 @@ def invoke(action, *options): "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", + "v1_5_2_001", ] assert [item["revision"] for item in plan["pending_migrations"]] == list(reviewed.revisions) - target = {"revision": "v1_5_0_004", "name": "v1_5_0_004", "software_version": "1.5.0", "sequence": 4} + target = {"revision": "v1_5_2_001", "name": "v1_5_2_001", "software_version": "1.5.2", "sequence": 1} assert plan["target_migration"] == target applied = invoke( @@ -82,7 +83,7 @@ def invoke(action, *options): ) assert applied["migration"] == target and applied["server_ready"] with closing(sqlite3.connect(runner.database)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_0_004",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_5_2_001",)] evidence = runner.evidence_path.read_bytes() recorded = json.loads(evidence) assert recorded["source_revision"] == expected_source["revision"] @@ -98,6 +99,7 @@ def invoke(action, *options): "v1_5_0_002", "v1_5_0_003", "v1_5_0_004", + "v1_5_2_001", } assert runner.verify().state == "ready" assert invoke("verify")["migration"] == target diff --git a/tests/test_registered_source_maintenance_cli.py b/tests/test_registered_source_maintenance_cli.py index 1a1e73264c..9af05bc91d 100644 --- a/tests/test_registered_source_maintenance_cli.py +++ b/tests/test_registered_source_maintenance_cli.py @@ -66,7 +66,7 @@ def test_release140_compatibility_commands_preserve_source_and_share_full_upgrad planned = CliRunner().invoke(cli, [*arguments, "plan", "--backup", "skip"]) assert planned.exit_code == 0, planned.output plan = json.loads(planned.output) - assert plan["source_revision"] == "r1400" and plan["target_revision"] == "v1_5_0_004" + assert plan["source_revision"] == "r1400" and plan["target_revision"] == "v1_5_2_001" assert plan["readiness_scope"] == "server" assert plan["compatibility_steps"] == [] full = CliRunner().invoke(cli, ["server", "db-migrate", "plan", "--backup", "skip"]) From df79da6b74cd146980154732272da44bf028469f Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 11 Nov 2026 01:54:35 +0800 Subject: [PATCH 02/27] test(skills): pin the evaluated Skill to the idempotency guidance --- evaluation/skills/skill-up/skill-lock.json | 6 +++--- .../powercontext-project-context/references/scope-memory.md | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/evaluation/skills/skill-up/skill-lock.json b/evaluation/skills/skill-up/skill-lock.json index 36b3790195..be5a8d9b37 100644 --- a/evaluation/skills/skill-up/skill-lock.json +++ b/evaluation/skills/skill-up/skill-lock.json @@ -1,7 +1,7 @@ { "schema_version": 1, "source_path": "integrations/agent-plugin/powercontext/skills/powercontext-project-context", - "source_commit": "b0fa97214790b18c358e62044ac520c9154c5778", + "source_commit": "99988da5c448500b565fb2d399be1620a418d0cb", "files": { "SKILL.md": "f2667491e0107eca6a3ef308e423b62781adf29697349610eadbef88da724198", "agents/openai.yaml": "2500c7e1d329158214626d203c70e7e9975f6ce7273be7fd4e758cbe4320bdbb", @@ -11,8 +11,8 @@ "references/host.md": "f16d33081061ebe49416afe986fee249b68f3cf9cce419e3fd370d8363f24561", "references/http-boundaries.md": "c012a88b6fb96f5a2e9cfbb6d39a8c9ce897451c4ff3d10f38c7471340ace7e7", "references/review-publication.md": "8f97c758e0877e38a542afaeb2c6ec33ae7a17fce86210efb6cd0e0e14148393", - "references/scope-memory.md": "0cd17b1b3f174bb05ac177a4bf5c8bbfd5200f72f1c1eb913d656a40432d89e1", + "references/scope-memory.md": "da4eb36cdffe8492e1aee54d5e8d779e4231cff97fca1c1674ef033734985736", "references/work-handoff.md": "d258bca1efc9330f1137690f75fb1e34f2a260e0bd277d41580077ce1886e595" }, - "content_sha256": "9103438af6242271735cb1abe2b72d6408a496dc8188592636598bba85353efb" + "content_sha256": "870b7076c60b3933ff41800537d3f24c8a7593573f3bf51bcf7d2a0c7103fbda" } diff --git a/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md b/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md +++ b/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. From 908671caf5530dfb9bb64b64b81dfc4a08946ff4 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 11 Nov 2026 03:05:43 +0800 Subject: [PATCH 03/27] test(desktop): qualify the idempotent remember_memory contract Bind the bundled Desktop contract to Server source df79da6b and its built wheel after the native probe passed all four connection modes. --- desktop/VALIDATION.md | 43 +++++++++++++++++++ .../src/connections/compatibility.json | 22 ++++++++++ 2 files changed, 65 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index be3c3f019a..a3854a5719 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -2676,3 +2676,46 @@ installed-platform acceptance remain separate requirements. 连接模式均通过。原生协议模块和业务断言保持不变;本机验收将 Server 启动就绪等待设为 60 秒, 不代表默认启动预算通过,也不构成启动性能承诺。该记录不替代安装后 GUI、原生凭据持久化、 Windows/macOS、数据库升级、签名或正式发行验收。 + +## Server df79da6b memory idempotency protocol qualification + +`sqlite-memory-idempotency-df79da6b-v1` qualifies all thirteen bundled Desktop protocol operations +against Server source `df79da6b74cd146980154732272da44bf028469f`, whose contract adds the optional +`idempotency_key` to `remember_memory`. The 63 earlier qualification records retain their original +identities and evidence. + +- Normalized OpenAPI SHA-256: `e0e147b69008320adfe9d8d46183fa73b3f3ede6f815205fdf51b920438e14d7`. +- Wheel: `powercontext-1.5.2.dev10+gdf79da6b7-py3-none-any.whl`. +- Wheel SHA-256: `58ab4068f0267a876d00a7513869f959546eb749fe8a534d554da6c1f9a5b49b`. +- Native debug probe SHA-256: `508fdd4ba4470f9913937afc627dad9574f6d76129cf20c48e2afa80e8c88b3c`. + +The wheel was built from a clean checkout of that commit. All 751 packaged runtime files match +the exact Git source archive after CRLF normalization, with no missing or extra runtime files. +The wheel uses the actual VCS development version; it is not a tagged stable artifact. The +qualification follow-up changes only this record and its catalog entry. + +On 2026-11-11, Linux x86_64 (kernel 6.5.0, glibc 2.36, Debian 12 container), Python 3.11.2 and +Rust 1.95.0 passed anonymous loopback, static Bearer, HTTPS with an explicit CA/base path, and +enforced authentication Provider modes against independent real HTTP/SQLite Servers. +`python desktop/tests/real_server.py --product-qualification sqlite-memory-idempotency-df79da6b-v1` +reported `bundled product records` with the matching wheel and contract digests. The unchanged +`server_probe` example was built from the product crate with `cargo build --locked` and the +repository harness ran with its default startup budget. Every mode kept the Server alive after +the client exited and reported a committed write with a lost response as unknown without replay. +The Provider mode also covered Principal changes, revocation, scoped authorization without Server +observation permission, and same-title Scope pagination. `cargo test --locked --test session` +passed 9 tests, including bundled product coverage of every Desktop operation. + +Python dependencies were installed from the versions and hashes in `uv.lock` through a package +mirror, and the wheel was built with `python -m build`; the run did not use `uv sync` or `uv build`. +The probe does not send `idempotency_key`; keyed replay and conflict behavior is covered by +`tests/e2e/test_remember_memory_idempotency.py`. + +This record does not qualify the installed WebView, credential persistence, Windows/macOS, +native database upgrades, signing, or stable release publication. The full Tauri build and +installed-platform acceptance remain separate requirements. + +本记录绑定上述精确源码、契约和 wheel,751 个运行时文件与源码归档一致,四种真实 HTTP/SQLite +连接模式均以测试工具的默认启动预算通过,原生协议模块和业务断言保持不变。探针不发送 +`idempotency_key`,带键重放与冲突行为由 `tests/e2e/test_remember_memory_idempotency.py` 覆盖。 +该记录不替代安装后 GUI、原生凭据持久化、Windows/macOS、数据库升级、签名或正式发行验收。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index c0b77a7664..6f6741e726 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1268,5 +1268,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-bcc0d93a-v151-protocol-qualification" + }, + { + "id": "sqlite-memory-idempotency-df79da6b-v1", + "serverCommit": "df79da6b74cd146980154732272da44bf028469f", + "contractSha256": "e0e147b69008320adfe9d8d46183fa73b3f3ede6f815205fdf51b920438e14d7", + "artifactSha256": "58ab4068f0267a876d00a7513869f959546eb749fe8a534d554da6c1f9a5b49b", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-df79da6b-memory-idempotency-protocol-qualification" } ] From d7003162a1264f28f304c15b5f5e7a0dc0d4284b Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 11 Nov 2026 12:52:14 +0800 Subject: [PATCH 04/27] test(server): accept idempotency_key in the stubbed memory create --- tests/e2e/test_runtime_server.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/e2e/test_runtime_server.py b/tests/e2e/test_runtime_server.py index 124889956c..73932c749f 100644 --- a/tests/e2e/test_runtime_server.py +++ b/tests/e2e/test_runtime_server.py @@ -1284,7 +1284,9 @@ def test_runtime_server_keeps_unstructured_memory_errors_private( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: - async def invalid_create(_self: ScopedAtomicMemoryApplication, _contents: object, /, *, context=None) -> None: + async def invalid_create( + _self: ScopedAtomicMemoryApplication, _contents: object, /, *, context=None, idempotency_key=None + ) -> None: raise InvalidMemoryCandidateError("canonical", "private implementation detail") monkeypatch.setattr(ScopedAtomicMemoryApplication, "create", invalid_create) From 7aa1ebb288b79e0f5eb3f3b1ba6acb64173cd5b2 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 11 Nov 2026 17:15:45 +0800 Subject: [PATCH 05/27] test(skills): refresh the ZCode Skill pin and tool argument reference --- .../evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md | 2 +- evaluation/zcode_guidance/skill-lock.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md b/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md index d07555502e..1094c6b4f6 100644 --- a/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md +++ b/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md @@ -273,7 +273,7 @@ not replace those schemas or enforce their constraints. It contains no scenario ## mcp__powercontext__remember_memory - Required: `kind: string`, `scope_id: string`, `text: string`. -- Optional: `description: string | null`, `expected_revision: integer | null`, `reason: string | null`. +- Optional: `description: string | null`, `expected_revision: integer | null`, `idempotency_key: string | null`, `reason: string | null`. ## mcp__powercontext__replace_artifact diff --git a/evaluation/zcode_guidance/skill-lock.json b/evaluation/zcode_guidance/skill-lock.json index 9f1a5d78d8..9e78deda3f 100644 --- a/evaluation/zcode_guidance/skill-lock.json +++ b/evaluation/zcode_guidance/skill-lock.json @@ -1,7 +1,7 @@ { "schema_version": 1, "source_path": "integrations/agent-plugin/powercontext/skills/powercontext-project-context", - "source_commit": "b0fa97214790b18c358e62044ac520c9154c5778", + "source_commit": "99988da5c448500b565fb2d399be1620a418d0cb", "files": { "SKILL.md": "f2667491e0107eca6a3ef308e423b62781adf29697349610eadbef88da724198", "agents/openai.yaml": "2500c7e1d329158214626d203c70e7e9975f6ce7273be7fd4e758cbe4320bdbb", @@ -11,7 +11,7 @@ "references/host.md": "f16d33081061ebe49416afe986fee249b68f3cf9cce419e3fd370d8363f24561", "references/http-boundaries.md": "c012a88b6fb96f5a2e9cfbb6d39a8c9ce897451c4ff3d10f38c7471340ace7e7", "references/review-publication.md": "8f97c758e0877e38a542afaeb2c6ec33ae7a17fce86210efb6cd0e0e14148393", - "references/scope-memory.md": "0cd17b1b3f174bb05ac177a4bf5c8bbfd5200f72f1c1eb913d656a40432d89e1", + "references/scope-memory.md": "da4eb36cdffe8492e1aee54d5e8d779e4231cff97fca1c1674ef033734985736", "references/work-handoff.md": "d258bca1efc9330f1137690f75fb1e34f2a260e0bd277d41580077ce1886e595" } } From 5325db8c3daa2afcd8b5ef6fe250a723e7552405 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Thu, 12 Nov 2026 01:07:21 +0800 Subject: [PATCH 06/27] fix(memory): authorize scope contribution before a keyed replay An in-process keyed create returned a replay or a conflict before the caller's creation authority was checked. Require it before the receipt lookup so a revoked contributor learns nothing from an old key. --- .../artifacts/atomic_memory/service.py | 7 ++ .../builtin/persistence/family_management.py | 12 ++++ .../builtin/persistence/records.py | 7 +- tests/e2e/test_remember_memory_idempotency.py | 65 +++++++++++++++++++ 4 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/powercontext/builtin/artifacts/atomic_memory/service.py b/src/powercontext/builtin/artifacts/atomic_memory/service.py index f5c158d6e9..454f0cc612 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/service.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/service.py @@ -507,6 +507,13 @@ async def inspect_change( ) ) + async def authorize_creates( + self, connection: AsyncConnection, scope_id: str, artifact_ids: Sequence[str], context: Any + ) -> None: + """Require the caller's current creation authority without inspecting any content.""" + refs = tuple(ArtifactRef(family="atomic-memory", artifact_id=value, revision=1) for value in artifact_ids) + await self.shared.security.authorize_creates(connection, scope_id, context, refs) + async def inspect_creates( self, connection: AsyncConnection, diff --git a/src/powercontext/builtin/persistence/family_management.py b/src/powercontext/builtin/persistence/family_management.py index 86c2665842..c6b9e551f1 100644 --- a/src/powercontext/builtin/persistence/family_management.py +++ b/src/powercontext/builtin/persistence/family_management.py @@ -547,6 +547,18 @@ async def prepare_creates( scope_id, tuple((artifact_id, content, None) for artifact_id, content in items), execution_context ) + async def authorize_creates(self, scope_id: str, artifact_ids: Sequence[str], *, execution_context=None) -> None: + """Check creation authority alone, for callers that may answer without preparing a write.""" + from powercontext.builtin.runtime.atomic_memory import deferred_decision_audit + + if execution_context is None or execution_context.access is None: + return + async with ( + deferred_decision_audit(execution_context), + self.application.database.transaction() as connection, + ): + await self.application.service.authorize_creates(connection, scope_id, artifact_ids, execution_context) + async def _prepare_commands(self, scope_id, items, context) -> tuple[AtomicMemoryManagementPrepared, ...]: """Inspect one write window, then prepare its projections outside the transaction.""" from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent diff --git a/src/powercontext/builtin/persistence/records.py b/src/powercontext/builtin/persistence/records.py index 3724e18392..1b883af222 100644 --- a/src/powercontext/builtin/persistence/records.py +++ b/src/powercontext/builtin/persistence/records.py @@ -457,17 +457,20 @@ async def create_keyed_atomic_memory( ) -> MemoryIdempotencyReceipt: """Create one memory bound to a retry key, or return the creation the key already names. - Validation and the request digest finish before the key lookup. Only a miss prepares + Validation and the request digest finish before the key lookup. The caller's current + creation authority is required before the lookup, so a replay or a conflict is never + reported to a caller who may no longer create in the Scope. Only a miss prepares projections; the key record commits in the same transaction as the creation. """ writer = self._atomic_creation_writer() command = cast(AtomicMemoryContent, writer.validate_create(content)) key = MemoryIdempotencyKey(namespace_digest(scope_id, principal, idempotency_key), command) request_digest(command) + artifact_id = self._id_factory("atomic-memory") + await writer.authorize_creates(scope_id, (artifact_id,), execution_context=execution_context) stored = await find_receipt(self._database, key) if stored is not None and stored.live: return _replay_receipt(stored, key, scope_id) - artifact_id = self._id_factory("atomic-memory") prepared = await self._prepare_atomic_creations(writer, scope_id, ((artifact_id, command),), execution_context) receipt = MemoryIdempotencyReceipt(artifact_id=artifact_id, revision=1, state_version=0) try: diff --git a/tests/e2e/test_remember_memory_idempotency.py b/tests/e2e/test_remember_memory_idempotency.py index f46f920260..0bde686843 100644 --- a/tests/e2e/test_remember_memory_idempotency.py +++ b/tests/e2e/test_remember_memory_idempotency.py @@ -470,3 +470,68 @@ async def scenario() -> None: ) asyncio.run(scenario()) + + +def test_in_process_keyed_create_requires_current_scope_contribution(tmp_path: Path) -> None: + """A revoked contributor learns neither a replay nor a conflict from an old key.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.server.authz import AccessAuditContext, AccessDeniedError + + database = tmp_path / "in-process-access.db" + + async def scenario() -> None: + server_settings = _settings( + database, + runtime=RuntimeConfig(artifact_processing_families=()), + access=AccessControlConfig(mode="enforced", deployment_id="idempotency"), + ) + await asyncio.to_thread(prepare_server_database, server_settings) + async with open_builtin_access_control( + server_settings.database, bootstrap_administrators=(ADMIN,), deployment_id="idempotency" + ) as access: + app = create_server_app( + settings=server_settings, + authentication_provider=_Authentication(), + access_control=access, + scheduler_path=tmp_path / "scheduler.db", + ) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + created = await client.post( + "/v1/scopes", json={"title": "Keys", "summary": "Idempotent writes", "idempotency_key": "keys"} + ) + assert created.status_code == 201, created.text + scope_id = created.json()["scope_id"] + grant = await _grant(client, scope_id, "alice") + memory = app.state.application.atomic_memory.for_scope(scope_id) + context = ArtifactSearchExecutionContext( + principal=PrincipalRef(type="user", id="alice"), + access=access, + audit=AccessAuditContext(transport="http", operation="test"), + ) + content = AtomicMemoryContent(kind="note", text="Private plan") + + first = await memory.create((content,), idempotency_key="in-process", context=context) + replayed = await memory.create((content,), idempotency_key="in-process", context=context) + assert replayed.records[0].artifact == first.records[0].artifact + assert _memories(database) == 1 + + revoked = await client.post( + "/v1/access/bindings/revoke", + json={ + "binding_id": grant["binding_id"], + "expected_version": grant["version"], + "idempotency_key": "revoke-alice", + }, + ) + assert revoked.status_code == 200, revoked.text + other = AtomicMemoryContent(kind="note", text="Different plan") + for value, key in ((content, "in-process"), (other, "in-process"), (content, "unused")): + with pytest.raises(AccessDeniedError): + await memory.create((value,), idempotency_key=key, context=context) + assert _memories(database) == 1 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 1 + + asyncio.run(scenario()) From 540f9b4d855a7f17eb9fecb0b991af4373ef6bed Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Thu, 12 Nov 2026 13:34:07 +0800 Subject: [PATCH 07/27] fix(memory): share the SDK key namespace when access control is off A context that named a principal without an access service put that principal into the key namespace, so the same key and content created a second memory. Use the empty principal unless access is enforced. --- .../builtin/runtime/application.py | 4 +++- tests/e2e/test_remember_memory_idempotency.py | 24 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index 5bda6643d1..10648f8e83 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -3866,7 +3866,9 @@ async def _create_keyed(self, values, idempotency_key: str, context) -> AtomicMe raise InvalidBaseAccessRequestError( "idempotency_key", "must be 1 to 256 printable ASCII characters, no spaces" ) - principal = None if context is None or context.principal is None else context.principal + # Without an access service every caller shares the Scope's one key namespace, + # whatever principal the context happens to name. + principal = None if context is None or context.access is None else context.principal receipt = await self._runtime._records().create_keyed_atomic_memory( self.scope_id, values[0], diff --git a/tests/e2e/test_remember_memory_idempotency.py b/tests/e2e/test_remember_memory_idempotency.py index 0bde686843..1b2e294b0a 100644 --- a/tests/e2e/test_remember_memory_idempotency.py +++ b/tests/e2e/test_remember_memory_idempotency.py @@ -30,7 +30,7 @@ from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent from powercontext.builtin.persistence.family_management import AtomicMemoryManagementWriter from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.records import InvalidBaseAccessRequestError +from powercontext.builtin.records import BaseValueConflictError, InvalidBaseAccessRequestError from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_runtime from powercontext.builtin.scope import ScopeDraft from powercontext.client import PowerContextClient @@ -231,6 +231,28 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_in_process_keys_share_one_namespace_without_access_control() -> None: + """A context that names a principal but carries no access service does not split the namespace.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + named = ArtifactSearchExecutionContext(principal=PrincipalRef(type="user", id="alice"), trusted_local=True) + + first = await memory.create(content, idempotency_key="shared") + assert await memory.create(content, idempotency_key="shared", context=named) == first + assert len((await memory.list()).items) == 1 + with pytest.raises(BaseValueConflictError): + other = (AtomicMemoryContent(kind="preference", text="Use npm"),) + await memory.create(other, idempotency_key="shared", context=named) + + asyncio.run(scenario()) + + def test_keyed_request_keeps_expected_revision_rejection(tmp_path: Path) -> None: database = tmp_path / "expected.db" From 2f41a83a55bd7812f8ac9a9886658b89b0ed91eb Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Fri, 13 Nov 2026 16:51:19 +0800 Subject: [PATCH 08/27] fix(memory): deny untrusted contexts before a keyed receipt lookup The creation preflight skipped authorization whenever a context had no access service, so an explicit untrusted context could tell an occupied key from a free one through the conflict error. Only an absent context now skips the check; the domain policy decides the rest. --- release/upgrade-support.json | 2 +- .../builtin/persistence/family_management.py | 8 +++++-- tests/e2e/test_remember_memory_idempotency.py | 23 +++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/release/upgrade-support.json b/release/upgrade-support.json index f39bfdada2..ae76967664 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,7 +3,7 @@ "target_version": "1.5.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "8beea298e7a40ed77107e372b9c03bf18b399aef2a8eae7632f286730800ea96", + "persistence_sha256": "e7e5dea1fd9af8337ea36a22c40ed44911c1721270fca288b120e564353c0f1e", "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Revision v1_5_2_001 adds pc_atomic_memory_idempotency after v1_5_0_004 on both registered source releases and all vector/Code profiles. Explicit maintenance creates the empty table and its expiry index; fresh databases receive it through the registered bootstrap. A row holds only SHA-256 namespace and request digests, the bound Artifact identity, revision and creation state version, and database-clock creation and expiry times; raw keys, principal IDs and memory bodies are not stored. A keyed remember_memory creation commits its receipt in the same transaction as the Memory, and expired receipts are removed in bounded batches after commit. Requests without a key, Artifact history, earlier revision resources, fingerprints, checksums and existing row encodings are unchanged. Local SQLite migration, retry and concurrency tests do not constitute native seekDB/OceanBase or installed-release acceptance; the upgrade-required policy, required automatic matrix and publication restrictions remain unchanged." }, "cases": [], diff --git a/src/powercontext/builtin/persistence/family_management.py b/src/powercontext/builtin/persistence/family_management.py index c6b9e551f1..a5fc786c1a 100644 --- a/src/powercontext/builtin/persistence/family_management.py +++ b/src/powercontext/builtin/persistence/family_management.py @@ -548,10 +548,14 @@ async def prepare_creates( ) async def authorize_creates(self, scope_id: str, artifact_ids: Sequence[str], *, execution_context=None) -> None: - """Check creation authority alone, for callers that may answer without preparing a write.""" + """Check creation authority alone, for callers that may answer without preparing a write. + + Only an absent context skips the check; the domain policy decides trusted local and + untrusted contexts exactly as it does for an ordinary creation. + """ from powercontext.builtin.runtime.atomic_memory import deferred_decision_audit - if execution_context is None or execution_context.access is None: + if execution_context is None: return async with ( deferred_decision_audit(execution_context), diff --git a/tests/e2e/test_remember_memory_idempotency.py b/tests/e2e/test_remember_memory_idempotency.py index 1b2e294b0a..162937f242 100644 --- a/tests/e2e/test_remember_memory_idempotency.py +++ b/tests/e2e/test_remember_memory_idempotency.py @@ -557,3 +557,26 @@ async def scenario() -> None: assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 1 asyncio.run(scenario()) + + +def test_untrusted_in_process_context_cannot_probe_an_occupied_key() -> None: + """An explicit context that is neither access-controlled nor trusted local is denied before any lookup.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.server.authz import AccessDeniedError + + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + other = (AtomicMemoryContent(kind="preference", text="Use npm"),) + await memory.create(content, idempotency_key="known") + + untrusted = ArtifactSearchExecutionContext() + for value, key in ((content, None), (content, "unused"), (content, "known"), (other, "known")): + with pytest.raises(AccessDeniedError): + await memory.create(value, idempotency_key=key, context=untrusted) + assert len((await memory.list()).items) == 1 + + asyncio.run(scenario()) From 3ea53dc684ce242839e956d3f44e279ef2630270 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Fri, 13 Nov 2026 16:51:26 +0800 Subject: [PATCH 09/27] test(desktop): qualify the merged memory idempotency contract Bind the bundled Desktop contract to Server source bc11d08e and its built wheel after the native probe passed all four connection modes. --- desktop/VALIDATION.md | 43 +++++++++++++++++++ .../src/connections/compatibility.json | 22 ++++++++++ 2 files changed, 65 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 8031ad0ae9..2b169d0593 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -2888,3 +2888,46 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml \ --test session bundled_product_qualification_covers_every_desktop_operation make contract-test ``` + +## Server bc11d08e memory idempotency protocol qualification + +`sqlite-memory-idempotency-bc11d08e-v1` qualifies all thirteen bundled Desktop protocol operations +against Server source `bc11d08ee694a5c05131b90b0a46d032ee5cbb66`, whose contract combines the optional +`idempotency_key` on `remember_memory` with the optional Task Outcome stop reason. The 66 earlier +qualification records retain their original identities and evidence. + +- Normalized OpenAPI SHA-256: `36eb4ebc989a34be1872cd220c5289df81d690ea57d9e5565d50d06046ac9a81`. +- Wheel: `powercontext-1.5.2.dev56+gbc11d08ee-py3-none-any.whl`. +- Wheel SHA-256: `4bb3bb9c97efe9bb2b0ebec4d6a299c2861bd572ebf0fd6dc148d1e360e34bc9`. +- Native debug probe SHA-256: `931e0cc0dba27c8e889c612ae5009a7889ab8bd22ca9bee37f80b078418d7b8a`. + +The wheel was built from a clean checkout of that commit. All 752 packaged runtime files match +the exact Git source archive after CRLF normalization, with no missing or extra runtime files. +The wheel uses the actual VCS development version; it is not a tagged stable artifact. + +On 2026-11-12, Linux x86_64 (kernel 6.5.0, glibc 2.36, Debian 12 container), Python 3.11.2 and +Rust 1.95.0 passed anonymous loopback, static Bearer, HTTPS with an explicit CA/base path, and +enforced authentication Provider modes against independent real HTTP/SQLite Servers. +`python desktop/tests/real_server.py --product-qualification sqlite-memory-idempotency-bc11d08e-v1` +reported `bundled product records` with matching client and Server contract digests. The unchanged +`server_probe` example was built from the product crate with `cargo build --locked`, and the +repository harness ran with its default startup budget. Every mode kept the Server alive after the +client exited and reported a committed write with a lost response as unknown without replay. The +Provider mode also covered Principal changes, revocation, scoped authorization without Server +observation permission, and same-title Scope pagination. `cargo test --locked --test session` +passed 9 tests, including bundled product coverage of every Desktop operation. + +Python dependencies were installed from the versions and hashes in `uv.lock` through a package +mirror, and the wheel was built with `python -m build`. The probe sends neither `idempotency_key` +nor a stop reason; keyed replay and conflict behavior is covered by +`tests/e2e/test_remember_memory_idempotency.py`, and stop reasons by the Work and HTTP SQLite tests. +A later commit on the same branch changes in-process authorization before keyed receipt lookup; +it does not change the HTTP contract or the Desktop protocol path. + +This record does not qualify the installed WebView, credential persistence, Windows/macOS, +native database upgrades, signing, or stable release publication. + +本记录绑定上述精确源码、契约和 wheel,752 个运行时文件与源码归档一致,四种真实 HTTP/SQLite +连接模式均以测试工具的默认启动预算通过,原生协议模块和业务断言保持不变。探针不发送 +`idempotency_key` 或停止原因,相关行为由各自的 SQLite 测试覆盖。该记录不替代安装后 GUI、 +原生凭据持久化、Windows/macOS、数据库升级、签名或正式发行验收。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 73e888b648..2907971007 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1333,5 +1333,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#task-stop-reason-merged-contract-protocol-qualification" + }, + { + "id": "sqlite-memory-idempotency-bc11d08e-v1", + "serverCommit": "bc11d08ee694a5c05131b90b0a46d032ee5cbb66", + "contractSha256": "36eb4ebc989a34be1872cd220c5289df81d690ea57d9e5565d50d06046ac9a81", + "artifactSha256": "4bb3bb9c97efe9bb2b0ebec4d6a299c2861bd572ebf0fd6dc148d1e360e34bc9", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-bc11d08e-memory-idempotency-protocol-qualification" } ] From cc8581e49036eb09f72b6520ba4b37bc6ad5e01c Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sat, 14 Nov 2026 05:55:10 +0000 Subject: [PATCH 10/27] fix(desktop): qualify the merged idempotency contract --- desktop/VALIDATION.md | 66 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++ 2 files changed, 88 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 5cfb5ec9ff..ddd418439e 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3300,3 +3300,69 @@ cargo +1.95.0 build --locked --manifest-path desktop/src-tauri/Cargo.toml --exam ``` The exact wheel is retained under `.git/pr2557-wheel3/`; the measured report is under ignored `desktop/.artifacts/real-server.json`. These are local protocol results against an isolated built-wheel Server. They do not establish installed UI, native credential persistence, Windows or Intel macOS execution, OceanBase behavior, external production acceptance or release readiness. + +## Server 6506e18f memory idempotency protocol qualification + +`sqlite-memory-idempotency-6506e18f-v1` qualifies all thirteen bundled Desktop protocol +operations against Server source `6506e18f4cf6a1bf4e575df61bf3abe849d95054`. The bundled +contract includes the optional `idempotency_key` on `remember_memory`, Core target +resolution and Task Outcome stop reasons. + +- Normalized OpenAPI SHA-256: `71296c61a668467c03235d1dd2395ef69ac7f60476c8de0987eec455f1c72e75`. +- Wheel: `powercontext-1.5.2.dev121+g6506e18f4-py3-none-any.whl`. +- Wheel SHA-256: `b092c3bd646bce9c445e67ee57087c6fb53551efb5b7e9a8069f1a2a21fec374`. +- Native debug probe SHA-256: `cad39a7dc4a1aad294042169e129b14ee1e40b7be41a8b875e702209ee952bc3`. + +All 797 packaged Server and service-bootstrap runtime files match the exact Git source +archive after CRLF normalization, with no missing, extra or changed runtime files. +The wheel was built from the clean recorded commit with its actual VCS development +version. The product probe was built with Rust 1.95.0 and `cargo build --locked`, without +`ci-fixtures`. Its working tree contained the added qualification record; the recorded +Server wheel remains bound to the clean source commit. + +On 2026-11-14, a dedicated remote Linux x86_64 server ran the unchanged +`desktop/tests/real_server.py` in an Ubuntu 24.04 container, kernel 6.5.0, glibc 2.39 and +Python 3.12.3. Anonymous loopback, static Bearer, HTTPS with an explicit CA/base path, +and enforced Provider modes all passed through the ordinary product ConnectionManager. +Every mode reported `bundled product records` and the exact qualification above, with +matching client and Server contract digests. Checks include connection identity, exact +Scope selection, Memory save/search/exact revision reads, statistics, committed writes +with lost responses without replay, and Server survival after the client exits. Provider +mode also checks Principal changes, same-identity revocation, scoped authorization +without Server observation permission, and 51 same-title Scopes. Statistics usage is +controlled fixture input rather than an external model-provider execution claim. + +The contract gate passes 68 tests and the idempotency end-to-end suite passes 18 tests, +including revoked-contributor retries, untrusted-context key probing and the shared +anonymous namespace when access control is disabled. All nine native session tests pass, +including bundled coverage of every Desktop operation. The original missing-profile +contract assertion was reproduced before adding this record. Skill pin and tool-contract +fixture checks also pass. Python dependencies were installed from an export of `uv.lock` +with the pinned versions and hashes verified through a package mirror; the repository +lock files retain their original registry identities. + +The exact wheel, source comparison, native probe identity and four-mode report are +retained on the remote server under ignored `desktop/.artifacts/pr2583/`. This evidence +qualifies the observed HTTP/SQLite protocol behavior. Installed WebView, credential +persistence, other operating systems, external databases, database upgrade acceptance +and release publication require their own evidence. The Desktop probe does not send +`idempotency_key`; keyed replay, conflict and authorization behavior use the separate +idempotency suite above. + +Reproduce using the recorded wheel and a client containing this bundled profile: + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-idempotency-6506e18f-v1 \ + --wheel desktop/.artifacts/pr2583/server-wheel/powercontext-1.5.2.dev121+g6506e18f4-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +make contract-test +uv run --no-sync python -m pytest tests/e2e/test_remember_memory_idempotency.py -q +``` + +本记录绑定上述精确源码、契约和 wheel,797 个运行时文件与 Git 源码归档一致。独立远端容器中的 +四种真实 HTTP/SQLite 连接模式全部通过,产品连接管理器选中同一内置资格记录。合同测试 68 项、 +幂等端到端测试 18 项和原生 session 测试 9 项通过,包含评论涉及的权限与命名空间回归。 +依赖按锁文件中的版本和哈希经镜像安装,未修改仓库锁文件。本记录不替代安装版界面、凭据持久化、 +其他平台、外部数据库、升级或发布验收;幂等 key 的行为由独立端到端测试覆盖。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 330cbe1496..25c7b16a5e 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1636,5 +1636,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#stable-note-counts-source-snapshot-protocol-qualification" + }, + { + "id": "sqlite-memory-idempotency-6506e18f-v1", + "serverCommit": "6506e18f4cf6a1bf4e575df61bf3abe849d95054", + "contractSha256": "71296c61a668467c03235d1dd2395ef69ac7f60476c8de0987eec455f1c72e75", + "artifactSha256": "b092c3bd646bce9c445e67ee57087c6fb53551efb5b7e9a8069f1a2a21fec374", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-6506e18f-memory-idempotency-protocol-qualification" } ] From f6d7d52127a4edcbdfb2bb0051d7077b62c0f0d0 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sun, 15 Nov 2026 05:09:25 +0000 Subject: [PATCH 11/27] fix(desktop): qualify the merged gateway memory contract --- desktop/VALIDATION.md | 59 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++ 2 files changed, 81 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 0e7d60ed73..1060aec022 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3584,3 +3584,62 @@ profiles retain their original source, contract, artifact and evidence identitie This is local SQLite protocol qualification, not an installed WebView or credential-persistence test, other-platform qualification, external database deployment, gateway transport acceptance, or release approval. + +## Server dc99352f memory gateway protocol qualification + +`sqlite-memory-gateway-dc99352f-v1` qualifies all thirteen bundled Desktop protocol +operations against Server source `dc99352fa53f9db07398000e904cb006c7b17a01`. The combined +OpenAPI includes keyed Memory creation and Gateway lifecycle metadata. + +- Normalized OpenAPI SHA-256: `4ebf65e50668d64b7856c7f72667f7758840a49e443d1bb618318ac5d4615c00`. +- Wheel: `powercontext-1.5.2.dev164+gdc99352fa-py3-none-any.whl`. +- Wheel SHA-256: `ee4f6c22345711c1a52e043bca950c7655a2323ef1aacf6c5428329dcb757ad5`. +- Native debug probe SHA-256: `ff98d330b4fb9f2ff958b2badd2ab3234f097ced473d3997b72e4e904e5ca6ae`. + +All 799 packaged runtime files match the exact Git source archive after CRLF +normalization, with no missing, extra or changed files. The wheel was built from the +clean recorded commit with its actual VCS development version. Rust 1.95.0 built the +ordinary product probe with `cargo build --locked`, without `ci-fixtures`; the client +working tree contained the added qualification record. + +On 2026-11-15, a dedicated remote Linux x86_64 server ran the unchanged real-Server +harness in an Ubuntu 24.04 container, kernel 6.5.0, glibc 2.39 and Python 3.12.3. +Anonymous loopback, static Bearer, HTTPS with an explicit CA/base path, and enforced +Provider modes all passed. Every mode reported `bundled product records`, the exact +qualification above and matching client/Server contract digests. Checks cover identity, +Scope selection, Memory save/search/exact reads, statistics, committed writes with lost +responses without replay, and Server survival after client exit. Provider mode also +checks Principal changes, revocation, scoped authorization without Server observation +permission, and 51 same-title Scopes. Statistics usage is controlled fixture input. + +The generated Python and Desktop contracts are current. The Desktop generator and its +check mode pass with Node 24.14.1, OpenAPI Generator 7.26.0 and Rustfmt 1.95.0; +TypeScript checking also passes. The contract suite passes 69 tests, the idempotency +end-to-end suite passes 18 tests, and all nine native session tests pass. `make check` +passes, including type checks and 61 integration-manifest tests. Skill pin and +tool-contract fixture checks pass. The missing-profile assertion was reproduced before +adding this record. + +The wheel, source comparison, probe checksum and four-mode report are retained on the +remote server under ignored `desktop/.artifacts/pr2583-nov15/`. Historical qualification +records and authenticated-client mappings retain their evidence identities. These results +qualify the Desktop HTTP/SQLite protocol, not the Rust Gateway lifecycle routes, +installed WebView, credential persistence, other platforms, external databases, database +upgrades or release publication. The probe does not send `idempotency_key`; the separate +idempotency suite covers keyed writes, replay, conflict and authorization. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-gateway-dc99352f-v1 \ + --wheel desktop/.artifacts/pr2583-nov15/server-wheel/powercontext-1.5.2.dev164+gdc99352fa-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +make contract-test +uv run --no-sync python -m pytest tests/e2e/test_remember_memory_idempotency.py -q +``` + +本记录绑定上述精确源码、组合契约和 wheel,799 个运行时文件与源码归档一致。远端容器中的匿名、 +Bearer、HTTPS 和 Provider 四种真实 HTTP/SQLite 模式全部通过,产品连接管理器选中同一内置记录。 +合同测试 69 项、幂等端到端测试 18 项、原生 session 测试 9 项及完整代码质量检查通过。 +历史资格与已认证客户端映射保留各自证据。本记录验证 Desktop 协议,不代替 Rust Gateway 生命周期、 +安装版界面、凭据持久化、其他平台、外部数据库、升级或发布验收;幂等 key 由独立端到端测试覆盖。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 913841f3b0..149a4e700e 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1750,5 +1750,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-a211ba84-merged-gateway-contract-protocol-qualification" + }, + { + "id": "sqlite-memory-gateway-dc99352f-v1", + "serverCommit": "dc99352fa53f9db07398000e904cb006c7b17a01", + "contractSha256": "4ebf65e50668d64b7856c7f72667f7758840a49e443d1bb618318ac5d4615c00", + "artifactSha256": "ee4f6c22345711c1a52e043bca950c7655a2323ef1aacf6c5428329dcb757ad5", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-dc99352f-memory-gateway-protocol-qualification" } ] From 3e8a2ae20680e639677b5f01a88cc5828282772b Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sun, 15 Nov 2026 05:41:23 +0000 Subject: [PATCH 12/27] fix(desktop): qualify the combined plugin memory contract --- desktop/VALIDATION.md | 63 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++ 2 files changed, 85 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 7b7ad405d5..2418e3075b 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3672,3 +3672,66 @@ Bearer、HTTPS 和 Provider 四种真实 HTTP/SQLite 模式全部通过,产 --product-qualification sqlite-plugin-interfaces-3427cee7-v1 \ --wheel desktop/.artifacts/plugin-interfaces/powercontext-1.5.2.dev163+g3427cee71-py3-none-any.whl ``` + +## Server b496cc22 memory plugins protocol qualification + +`sqlite-memory-plugins-b496cc22-v1` qualifies all thirteen bundled Desktop protocol +operations against Server source `b496cc22ccf73a9c9e86dd5e7f942aa750186d1c`. Its OpenAPI +combines keyed Memory creation, Gateway lifecycle metadata and the plugin interfaces. + +- Normalized OpenAPI SHA-256: `d988b0dacfa08880a2f21d562f8c014f5c8175d139ecac0de24612d6c503861a`. +- Wheel: `powercontext-1.5.2.dev195+gb496cc22c-py3-none-any.whl`. +- Wheel SHA-256: `e93a6080ad051bd0cb8d2ee7e4ee55852bc48a447e465c305cf31d157baa5da7`. +- Native debug probe SHA-256: `ba2e76b6700bff1a38c05e279f6f7ebb82a6a2b7a8c9c21c43123dcceb28f2c5`. + +All 807 packaged runtime files match the exact Git source archive after CRLF +normalization, with no missing, extra or changed files. The wheel was built from the +clean recorded commit with its actual VCS development version. Rust 1.95.0 built the +ordinary product probe with `cargo build --locked`, without `ci-fixtures`; the client +working tree contained the added qualification record. + +On 2026-11-15, the unchanged real-Server harness passed anonymous loopback, static +Bearer, HTTPS with explicit CA/base path and enforced Provider modes on a dedicated +remote Linux x86_64 server in an Ubuntu 24.04 container, kernel 6.5.0, glibc 2.39 and +Python 3.12.3. Every mode reported `bundled product records`, the exact qualification +above and matching client/Server contract digests. Checks cover identity, Scope +selection, Memory save/search/exact reads, statistics, committed writes with lost +responses without replay, and Server survival after client exit. Provider mode also +checks Principal changes, revocation, scoped authorization without Server observation +permission, and 51 same-title Scopes. Statistics usage is controlled fixture input. + +The API/Desktop contract suite passes 69 tests, the idempotency suite passes 18 tests, +and all nine native session tests pass. `make check` passes, including type checks and +61 integration-manifest tests. Desktop generation/check mode, TypeScript checking and +native IPC generation checking pass. Skill pins and the tool-contract fixture pass. +Separate SQLite migration and maintenance coverage passes 85 tests. The plugin storage +regression preserves refusal while retired plugin data exists, then checks that cleanup +and receipt-table creation complete through `v1_5_0_005` followed by `v1_5_2_001`. +The receipt revision inherits plugin-aware readiness and records the reviewed final +schema fingerprint on both registered source chains. + +The exact wheel, source comparison, probe checksum and four-mode report are retained +on the remote server under ignored `desktop/.artifacts/pr2583-interfaces/`. Historical +profiles and authenticated-client mappings retain their evidence identities. These +results qualify the Desktop HTTP/SQLite protocol, not arbitrary plugin execution, +Rust Gateway lifecycle routes, installed WebView, credential persistence, other platforms, +external databases, installed-release upgrades or release publication. The probe does +not send `idempotency_key`; the separate idempotency suite covers keyed creation, +replay, conflict and authorization. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-plugins-b496cc22-v1 \ + --wheel desktop/.artifacts/pr2583-interfaces/server-wheel/powercontext-1.5.2.dev195+gb496cc22c-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +make contract-test +uv run --no-sync python -m pytest tests/e2e/test_remember_memory_idempotency.py -q +``` + +本记录绑定上述精确源码、组合契约和 wheel,807 个运行时文件与源码归档一致。远端容器中的四种 +真实 HTTP/SQLite 连接模式全部通过,产品连接管理器选中同一内置记录。合同测试 69 项、幂等测试 +18 项、原生 session 测试 9 项、SQLite 迁移与维护测试 85 项及代码质量检查通过。升级链先执行 +`v1_5_0_005`,再执行 `v1_5_2_001`,保留插件数据拒绝规则、插件就绪校验和幂等收据表。 +本记录不代替任意插件执行、Rust Gateway 生命周期、安装版、凭据持久化、其他平台、外部数据库、 +已安装发行版升级或发布验收;幂等 key 的行为由独立端到端测试覆盖。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index eddaafe4e8..e8c62b5bdd 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1794,5 +1794,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-3427cee7-plugin-interfaces-protocol-qualification" + }, + { + "id": "sqlite-memory-plugins-b496cc22-v1", + "serverCommit": "b496cc22ccf73a9c9e86dd5e7f942aa750186d1c", + "contractSha256": "d988b0dacfa08880a2f21d562f8c014f5c8175d139ecac0de24612d6c503861a", + "artifactSha256": "e93a6080ad051bd0cb8d2ee7e4ee55852bc48a447e465c305cf31d157baa5da7", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-b496cc22-memory-plugins-protocol-qualification" } ] From 61a98346540e2aa2b4caea1fe688177a149277a8 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sun, 15 Nov 2026 09:39:36 +0000 Subject: [PATCH 13/27] test(evaluation): refresh assembly input fingerprints Assembly sections now serialize hits and search_failed defaults. Preserve complete-input hashing and refresh the pinned reports and run provenance; allocation metrics and the decision are unchanged. --- .../reports/budget-v1/report.json | 10 +++++----- .../reports/budget-v1/report.md | 10 +++++----- .../reports/budget-v1/run-manifest.json | 16 ++++++++-------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json index 2b493e60a2..fd53b0351a 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json @@ -1889,7 +1889,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 3000, - "input_sha256": "bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b03933", + "input_sha256": "74132e65051a1c2c34aedde5f414789d373136598206ce4234d31aabd88b0e17", "baseline_content_bytes": 2952, "candidate_content_bytes": 3000, "baseline_coverage": 0.5857421563596759, @@ -2047,7 +2047,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 1400, - "input_sha256": "391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd1", + "input_sha256": "8d00f828905ab0d2e5a2a6a12bc521b8a88e425b3270d759dac83ff52d293038", "baseline_content_bytes": 1399, "candidate_content_bytes": 1400, "baseline_coverage": 0.4944314063466925, @@ -2159,7 +2159,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 640, - "input_sha256": "7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76d", + "input_sha256": "3c2cf212de65546866d245aad3703f51771a391a84b0de78ee30e69fa01f4d28", "baseline_content_bytes": 640, "candidate_content_bytes": 640, "baseline_coverage": 0.051853254067369715, @@ -2330,7 +2330,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 2400, - "input_sha256": "e996105f32ead0a09138d8182dde67e23252c8dca26a009fc37fb038f953a345", + "input_sha256": "93a5308fa74066923ec1fa76c687ea3e5b9b4b7792131cc4e79a8b9f724f683f", "baseline_content_bytes": 2234, "candidate_content_bytes": 2400, "baseline_coverage": 0.4690000933206748, @@ -2703,7 +2703,7 @@ "sensitivity_of": "assembly-large-early-then-small", "path": "assembly", "max_bytes": 3000, - "input_sha256": "bfb0fc5f1aad7c0558a227dd8cee2319fef9a9100de3c9a5ae95f3108d7a8e3d", + "input_sha256": "119ec1d83cfd36e1c008dd0205d193d0a20beec1c52452ea2fbe68544c58e92a", "baseline_content_bytes": 3000, "candidate_content_bytes": 3000, "baseline_coverage": 0.8389852114932723, diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md index 6404479238..2c34e54acc 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md @@ -217,7 +217,7 @@ Inputs SHA-256: `7898b82f155accc150e507ba8eab48a1a1aa34681521dd71e201af5fa0f6bc6 ### `assembly-large-early-then-small` -Inputs SHA-256: `bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b03933` +Inputs SHA-256: `74132e65051a1c2c34aedde5f414789d373136598206ce4234d31aabd88b0e17` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -231,7 +231,7 @@ Inputs SHA-256: `bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b0393 ### `assembly-controls-and-line-endings` -Inputs SHA-256: `391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd1` +Inputs SHA-256: `8d00f828905ab0d2e5a2a6a12bc521b8a88e425b3270d759dac83ff52d293038` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -242,7 +242,7 @@ Inputs SHA-256: `391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd ### `assembly-infeasible-640` -Inputs SHA-256: `7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76d` +Inputs SHA-256: `3c2cf212de65546866d245aad3703f51771a391a84b0de78ee30e69fa01f4d28` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -257,7 +257,7 @@ Inputs SHA-256: `7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76 ### `assembly-four-sections` -Inputs SHA-256: `e996105f32ead0a09138d8182dde67e23252c8dca26a009fc37fb038f953a345` +Inputs SHA-256: `93a5308fa74066923ec1fa76c687ea3e5b9b4b7792131cc4e79a8b9f724f683f` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -289,7 +289,7 @@ Inputs SHA-256: `c07ebcd45331d109c14dea3742a00af25cbcd18da56dc80847ad5fa589ac76c ### `sensitivity-assembly-large-last` -Inputs SHA-256: `bfb0fc5f1aad7c0558a227dd8cee2319fef9a9100de3c9a5ae95f3108d7a8e3d` +Inputs SHA-256: `119ec1d83cfd36e1c008dd0205d193d0a20beec1c52452ea2fbe68544c58e92a` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json b/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json index 6d10818c89..3c00db1862 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json @@ -1,6 +1,6 @@ { "schema_version": "powercontext.prepared-context-budget-report.v1", - "generated_at": "2026-11-12T16:23:47+00:00", + "generated_at": "2026-11-15T09:38:24+00:00", "command": [ "run.py", "--manifest", @@ -12,17 +12,17 @@ "manifest_sha256": "f66d20fde6356dee53d63790dbb4f5936f8979e51f1f01ee10452cde80068078", "definitions_path": "evaluation/memory/prepared_context_budget/fixtures/budget-v1-definitions.md", "definitions_sha256": "1892d202e9d5d9bda732912991609ecf68224ee096b48bd7269fa746bd3aa5ec", - "git_head": "9c2bfdc3d147c4f62b677a2301ff7e0ac07d43bd", - "git_worktree_dirty": false, + "git_head": "3e8a2ae20680e639677b5f01a88cc5828282772b", + "git_worktree_dirty": true, "source_sha256": { - "src/powercontext/builtin/runtime/prepared_context.py": "e3d77ee5a841f57d9af78ee1df7ef7b33ea492d88c46d4b81666ed47355ca53b", - "src/powercontext/builtin/runtime/prepared_text.py": "00d4bd578ec06db729be77965a044a69a799786b7ab6ec3bd8e16e1653788ef7", - "evaluation/memory/prepared_context_budget/arms.py": "d0e3fd2bf17cc3385f026064f0eddd25c192fc6165809b6567f0488a215e720f", + "src/powercontext/builtin/runtime/prepared_context.py": "a9168fbf8dbf0951d3688aaffb0c2a68a93b5fde8067a7166654b7d0ee24fe67", + "src/powercontext/builtin/runtime/prepared_text.py": "b9247f2b8376c7176050a02b7c594375e976a36e01487489f01640d2a294de13", + "evaluation/memory/prepared_context_budget/arms.py": "c4f6f6745c29fade0f664c97789c8f4937f63157b6fe30c6cfb93d682cec917a", "evaluation/memory/prepared_context_budget/experiment.py": "edd5949143c7b44533750d74a15acd295ca79deec4a5a2006e10eb58a06e28c5", "evaluation/memory/prepared_context_budget/manifest.py": "5d8d51f350ba8dd06a9a253c92cca0d45c5e42e08d5c9279b9af61a2a7268812", "evaluation/memory/prepared_context_budget/report.py": "252697fbb23fc16372340e18d0fde6252168c4f2e45d1908ecac9b612f314a0d", "evaluation/memory/prepared_context_budget/run.py": "9253c5fdfcf0e522f16a0dd036517f89aeb44e06a53296cb35b98292b5d93f0b" }, - "python": "3.13.13", - "platform": "macOS-27.2-arm64-arm-64bit-Mach-O" + "python": "3.12.3", + "platform": "Linux-6.5.0-26-generic-x86_64-with-glibc2.39" } From 6dce47015479c17910cab9cf5109040983253e9a Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Mon, 16 Nov 2026 14:35:21 +0000 Subject: [PATCH 14/27] test(desktop): qualify merged 1.5.2 idempotency contract --- desktop/VALIDATION.md | 48 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++ 2 files changed, 70 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index c30491923c..59f3874d22 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3801,3 +3801,51 @@ record was not yet committed. Historical profiles retain their original evidence These results qualify the observed local SQLite protocol, not installed WebView behavior, native credential persistence, other platforms, external providers, native database upgrades or the formal release acceptance matrix. + +## Server efd4be07 memory release protocol qualification + +`sqlite-memory-release-efd4be07-v1` qualifies all thirteen bundled Desktop protocol operations against +Server source `efd4be0731bc4683be4e2a66fc045cd808d00eb8`, combining API version `1.5.2` and keyed Memory creation. + +- Normalized OpenAPI SHA-256: `f41106d8716b5acc5212afcf515b45d58f963d6b10c0c158b85afe54a7acd731`. +- Wheel: `powercontext-1.5.2.dev216+gefd4be073-py3-none-any.whl`. +- Wheel SHA-256: `c9d384e215bd1d5e433e2b948654c9d1586bf5bfda6da719df3086b53ef48ff7`. +- Native debug probe SHA-256: `6dc5179afaa963f74e2c9ed3f41c15a90fe61725ad6e05d4900def354d0693db`. + +All 808 packaged runtime files match the exact Git source archive after CRLF +normalization. The wheel was built from the clean recorded commit with its actual VCS +version. Rust 1.95.0 built the ordinary product probe with `cargo build --locked`, without +`ci-fixtures`; the client working tree contained the added qualification record. + +On 2026-11-16, the unchanged real-Server harness passed anonymous loopback, static Bearer, +HTTPS with explicit CA/base path and enforced Provider modes on a dedicated remote Linux +x86_64 server in an Ubuntu 24.04 container, kernel 6.5.0, glibc 2.39 and Python 3.12.3. +All four modes selected this bundled product record with matching client and Server +contract digests. Checks cover identity, Scope selection, Memory save/search/exact reads, +statistics, committed writes with lost responses without replay, and Server survival +after client exit. Provider mode additionally checks Principal changes, revocation, +51 same-title Scopes, and scoped authorization without Server observation permission. +Statistics usage is controlled fixture input. + +The exact wheel, source comparison, probe checksum and four-mode report are retained +on the validation server under ignored `desktop/.artifacts/pr2583-release/`. +Historical profiles and authenticated-client mappings retain their original identities. +This record qualifies the Desktop HTTP/SQLite protocol; it does not establish installed +WebView behavior, credential persistence, arbitrary plugin execution, Gateway lifecycle +routes, other platforms, external databases, installed-release upgrades or publication. +The probe does not send `idempotency_key`; separate end-to-end tests cover keyed writes. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-release-efd4be07-v1 \ + --wheel desktop/.artifacts/pr2583-release/server-wheel/powercontext-1.5.2.dev216+gefd4be073-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +make contract-test +uv run --no-sync pytest tests/e2e/test_remember_memory_idempotency.py -q +``` + +本记录绑定上述精确源码、API 1.5.2 与幂等写入组合契约及 wheel;808 个运行时文件与源码归档一致。 +远端容器中的匿名、Bearer、HTTPS 和 Provider 四种真实 HTTP/SQLite 连接模式全部通过, +产品连接管理器选中对应内置记录。历史记录保持不变。本记录不代替安装版界面、凭据持久化、 +任意插件执行、Gateway 生命周期、其他平台、外部数据库、已安装发行版升级或发布验收。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 631a1c4acb..3d2db045a6 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1838,5 +1838,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-be5f0f76-v152-release-protocol-qualification" + }, + { + "id": "sqlite-memory-release-efd4be07-v1", + "serverCommit": "efd4be0731bc4683be4e2a66fc045cd808d00eb8", + "contractSha256": "f41106d8716b5acc5212afcf515b45d58f963d6b10c0c158b85afe54a7acd731", + "artifactSha256": "c9d384e215bd1d5e433e2b948654c9d1586bf5bfda6da719df3086b53ef48ff7", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-efd4be07-memory-release-protocol-qualification" } ] From fa594a31f5b7dab178eb1f4476cd533454eb405e Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 18 Nov 2026 20:51:36 +0800 Subject: [PATCH 15/27] test(desktop): qualify reconciled memory and Source contract --- desktop/VALIDATION.md | 50 +++++++++++++++++++ .../src/connections/compatibility.json | 22 ++++++++ 2 files changed, 72 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 35d3874b90..bcfae9e9f6 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3939,3 +3939,53 @@ uv run --no-sync python desktop/tests/real_server.py \ --product-qualification sqlite-plugin-scope-listing-bc22089e-v1 \ --wheel desktop/.artifacts/plugin-scope-listing/powercontext-1.5.2.dev238+gbc22089e9-py3-none-any.whl ``` + +## Server f63022b3 memory and Source protocol qualification + +`sqlite-memory-source-f63022b3-v1` qualifies all thirteen bundled Desktop protocol operations against +Server source `f63022b3f80358872170e995a5c55bf5c4dd5ef4`. Its contract combines keyed Memory creation, +Source collection runners, plugin reload, and the exclusion of plugin-created Scopes from Scope listings. +The registered migration chain reaches `v1_5_2_001` through `v1_5_2_pr2639`. + +- Normalized OpenAPI SHA-256: `a4143b643a80cbc98c04b75053799e64d12e3b03c9819416920c24ee8a730b32`. +- Wheel: `powercontext-1.5.2.dev273+gf63022b3f-py3-none-any.whl`. +- Wheel SHA-256: `7577343e5af3bac316b99225eebf6bb18c8097e93082a830cd458e74e7b0371c`. +- Native debug probe SHA-256: `de9360f4d40a6bfeafe07bb54a05d25627c731955650826ac1a5a52261baca8d`. + +All 810 packaged runtime files from `powercontext`, `powercontext_service_bootstrap`, and +`powercontext_integration_lifecycle` match the recorded Git source archive after CRLF normalization. +The wheel was built from that clean commit with its actual VCS version. Rust 1.95.0 built the ordinary +product probe with `cargo build --locked`, without `ci-fixtures`. The client working tree contained +the added qualification record; historical profiles and authenticated-client mappings retain their identities. + +On 2026-11-18, the unchanged `desktop/tests/real_server.py` passed anonymous loopback, static Bearer, +HTTPS with an explicit CA/base path, and enforced Provider fixture modes in an Ubuntu 24.04 container +on Linux 6.5.0-26 x86_64, with glibc 2.39, Python 3.12.3, and SQLite 3.45.1. All four modes selected +this bundled product record with identical Server and client contract digests. Checks cover identity, +Scope selection, Memory save/search/exact revision reads, statistics, committed writes with lost responses +without replay, and Server survival after client exit. Provider mode also verifies Principal changes, +same-identity revocation, 51 same-title Scopes, and scoped authorization without Server observation permission. +The native session suite passed all nine tests, including bundled coverage of every Desktop operation. +Statistics usage is controlled fixture input. + +The exact wheel, source comparison, probe checksum, and four-mode report are retained on the validation +host under ignored `desktop/.artifacts/reconcile-2639/`. This qualifies the observed HTTP/SQLite protocol; +it does not establish installed WebView behavior, credential persistence, arbitrary plugin execution, +Gateway lifecycle, other operating systems, external providers or databases, installed-release upgrades, +or publication acceptance. The probe does not send `idempotency_key`; separate end-to-end tests cover +keyed writes, including upgrades from the Source collection checkpoint through both registered source histories. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-source-f63022b3-v1 \ + --wheel desktop/.artifacts/reconcile-2639/server-wheel/powercontext-1.5.2.dev273+gf63022b3f-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +make contract-test +uv run --no-sync pytest tests/e2e/test_remember_memory_idempotency.py -q +``` + +本记录绑定上述精确源码、组合契约与 wheel;810 个运行时文件与源码归档一致,四种真实 HTTP/SQLite +连接模式全部选中该内置资格记录。原生 session 的九项测试通过。带键写入及两条来源路径从 Source 采集 +检查点升级后的幂等重放,由独立端到端测试覆盖。本记录不替代安装版界面、凭据持久化、任意插件执行、 +Gateway 生命周期、其他平台、外部 Provider 或数据库、已安装发行版升级及正式发布验收。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 3cee438e4b..be4dd2b774 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1926,5 +1926,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-bc22089e-plugin-scope-listing-protocol-qualification" + }, + { + "id": "sqlite-memory-source-f63022b3-v1", + "serverCommit": "f63022b3f80358872170e995a5c55bf5c4dd5ef4", + "contractSha256": "a4143b643a80cbc98c04b75053799e64d12e3b03c9819416920c24ee8a730b32", + "artifactSha256": "7577343e5af3bac316b99225eebf6bb18c8097e93082a830cd458e74e7b0371c", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-f63022b3-memory-and-source-protocol-qualification" } ] From 977071cb81e1531d4c31cd3f92c210ddb98c8275 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Fri, 20 Nov 2026 02:08:21 +0800 Subject: [PATCH 16/27] test(desktop): qualify memory and batch capture contract --- desktop/VALIDATION.md | 38 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++++ 2 files changed, 60 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index b28b215067..d867483c87 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4211,3 +4211,41 @@ uv run --no-sync python desktop/tests/real_server.py \ --product-qualification sqlite-gateway-batch-capture-477a6c8b-v1 \ --wheel desktop/.artifacts/gateway-batch-capture/powercontext-1.5.3.dev90+g477a6c8ba-py3-none-any.whl ``` + +## Server ff058b03 memory and batch capture protocol qualification + +`sqlite-memory-batch-ff058b03-v1` qualifies all thirteen bundled Desktop operations against +Server source `ff058b0399d81614c02bc5d927e107d177b7827d`, whose contract includes keyed Memory creation +and batch ContentSource capture. + +- Normalized OpenAPI SHA-256: `faf79a7df51ecb088c26691c04f8d6d10ca5d968891078dedc55aeb3aff90e92`. +- Wheel: `powercontext-1.5.2.dev306+gff058b039-py3-none-any.whl`. +- Wheel SHA-256: `456545493b0f93361c31dc46e8a1d8ed82e1247884063fa78e329f4ad5228a52`. +- Native debug probe SHA-256: `12f3af459c4eb21774b700fd97247ba885485779da3c1d07035e3b3823af113b`. + +The wheel was built from the recorded Git commit. All 811 packaged runtime files match that +commit's source archive after CRLF normalization. Rust 1.95.0 built the native probe with the +product Cargo lock and without `ci-fixtures`. + +On 2026-11-20, the real-Server harness selected the bundled product record in all four modes: +anonymous loopback, static Bearer, HTTPS with explicit CA and a base path, and enforced Provider. +The run used Linux 6.5.0-26 x86_64 with glibc 2.39 and Python 3.12.3 in an Ubuntu 24.04 container. +The client and Server contract digests matched. Memory saves, searches, exact revision reads and +the other bundled operations passed, including lost-response handling and Provider revocation. +The native session suite passed all nine cases. The Desktop probe exercises HTTP/SQLite and the +native protocol. Separate Server tests exercise keyed Memory replay and batch capture. + +The wheel, source comparison, probe checksum, and four-mode report are retained under ignored +`desktop/.artifacts/pr2583-batch-capture/` on the validation host. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-batch-ff058b03-v1 \ + --wheel desktop/.artifacts/pr2583-batch-capture/server-wheel/powercontext-1.5.2.dev306+gff058b039-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +本记录绑定精确源码、组合契约与 wheel。811 个运行时文件与源码归档一致,匿名、Bearer、HTTPS +和 Provider 四种真实 HTTP/SQLite 连接均选中该内置资格记录,原生 session 九项测试通过。 +带键 Memory 重放和批量 ContentSource 采集由独立的 Server 测试覆盖。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 183f7bef5a..29e45ab04f 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2102,5 +2102,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-477a6c8b-gateway-batch-capture-metadata-wording-protocol-qualification" + }, + { + "id": "sqlite-memory-batch-ff058b03-v1", + "serverCommit": "ff058b0399d81614c02bc5d927e107d177b7827d", + "contractSha256": "faf79a7df51ecb088c26691c04f8d6d10ca5d968891078dedc55aeb3aff90e92", + "artifactSha256": "456545493b0f93361c31dc46e8a1d8ed82e1247884063fa78e329f4ad5228a52", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-ff058b03-memory-and-batch-capture-protocol-qualification" } ] From a8afcd9ac6723fb477f501d47e808ba518063452 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sat, 21 Nov 2026 01:52:58 +0800 Subject: [PATCH 17/27] test: prune migration scripts using the Alembic revision chain Historical upgrade fixtures missed the cumulative draft 000.py when pruning later revisions by filename. Resolve each script from the registered chain so historical bundles keep their intended head. --- .../builtin/persistence/test_portable_storage_migration.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/builtin/persistence/test_portable_storage_migration.py b/tests/builtin/persistence/test_portable_storage_migration.py index 4fcf41102a..33623bff15 100644 --- a/tests/builtin/persistence/test_portable_storage_migration.py +++ b/tests/builtin/persistence/test_portable_storage_migration.py @@ -19,6 +19,7 @@ import shutil import sqlite3 from contextlib import closing +from pathlib import Path import pytest @@ -54,7 +55,7 @@ def previous_bundle(directory, embedding, *, through="s1401"): shutil.copytree(current.directory, directory, ignore=shutil.ignore_patterns("__pycache__")) manifest_path = directory / "manifest.json" manifest = json.loads(manifest_path.read_text()) - revisions = list(manifest["revision_resources"]) + revisions = current.revisions # Prune every revision after the requested previous head so the fixture # keeps describing the same earlier registration as later revisions are appended. created = set() @@ -68,8 +69,8 @@ def previous_bundle(directory, embedding, *, through="s1401"): path.unlink(missing_ok=True) if resource in manifest["mysql_state_layouts"]: manifest["mysql_state_layouts"].remove(resource) - for version in (directory / "versions").glob(f"{revision}_*.py"): - version.unlink() + script = current.script.get_revision(revision) + (directory / Path(script.path).relative_to(current.snapshot_directory)).unlink() (directory / "mysql" / "versions" / f"{revision}.py").unlink(missing_ok=True) del manifest["sqlite_fingerprints"][revision] del manifest["domain_readiness"][revision] From c4450578a77c72d13ba9f7ef134d0f143b205d46 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sat, 21 Nov 2026 02:19:03 +0800 Subject: [PATCH 18/27] ci: retry timed-out unit jobs From 277bc2362f0e53ab0d964af64171ac4ddbfee99d Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sat, 21 Nov 2026 02:46:40 +0800 Subject: [PATCH 19/27] ci: bound unit test worker concurrency The standard runner auto-selected 32 pytest workers, and consecutive runs failed in different deadline-sensitive tests. Limit unit jobs to eight workers so subprocesses can keep their existing deadlines. --- .github/workflows/master.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 4d3c2308de..2858f55637 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -300,6 +300,8 @@ jobs: if: matrix.suite == 'unit' env: PYTEST_ADDOPTS: --require-dsh-config-runtime --require-claude-code-python-floor + # Limit contention for tests that spawn subprocesses with fixed deadlines. + PYTEST_WORKERS: "8" run: make unit-test - name: Check Source serialization with minimum Pydantic From cc2373dfb2db47ab28a81dc7b3a2f5cf9106a4da Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Mon, 23 Nov 2026 00:01:20 +0800 Subject: [PATCH 20/27] test(desktop): qualify merged Memory and OAuth contract --- desktop/VALIDATION.md | 35 +++++++++++++++++++ .../src/connections/compatibility.json | 22 ++++++++++++ 2 files changed, 57 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 726e4731fa..04c0a86889 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4302,3 +4302,38 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session On 2026-11-19, `desktop/tests/real_server.py` passed anonymous loopback, static Bearer, HTTPS with an explicit CA and base path, and injected-provider authentication with enforced access. The product ConnectionManager selected the bundled qualification and reported matching client and Server contract digests. The checks used SQLite on Linux 5.10 x86_64, glibc 2.32 and Python 3.14.6. The native probe used Rust 1.97.1 and the product adapter modules in an isolated Cargo crate, with registry dependency pins matching the product Cargo lock. This qualification covers the local SQLite protocol. Installed WebView and platform keyring behavior require separate checks. + +## Server 5b75d4e6 memory and OAuth protocol qualification + +`sqlite-memory-oauth-5b75d4e6-v1` qualifies all thirteen bundled Desktop operations against +Server source `5b75d4e6468ba0eaf8a8f92388dce18cf48d7abc` for the combined keyed Memory and OAuth OpenAPI contract. + +- Normalized OpenAPI SHA-256: `b24d0adc353792ed18a64e60f6597bd50b7efbd3297407ae9962374db51a0de8`. +- Wheel: `powercontext-1.5.3.dev355+g5b75d4e64-py3-none-any.whl`. +- Wheel SHA-256: `60404af75c291e4e40b906d93a8d9d359fe54b1a2e7a5111f59e8d45ecd88e5c`. +- Native debug probe SHA-256: `8baf742e55adac367538d33f336f79080e6470204bb5f646261cc43a5835634f`. + +All 834 packaged runtime files match the exact Git source archive. +Rust 1.95.0 built the ordinary product probe with `cargo build --locked`. The +client included the new bundled record during validation. + +The real-Server harness passed anonymous loopback, static Bearer, HTTPS with an +explicit CA and base path, and injected-Provider enforced access in Ubuntu 24.04 +on a Linux x86_64 validation server (kernel 6.5.0, glibc 2.39, Python 3.12.3 and +SQLite 3.45.1). The product ConnectionManager selected this bundled record. +Checks exercised Memory saves, search and exact revision reads, Scope +pagination, lost write responses without replay, Server liveness after client +exit, and authorization changes in Provider mode. All nine native session tests +passed. The qualification covers Desktop HTTP/TLS with fixture authentication +and SQLite. Keyed-write retries use separate Server end-to-end tests. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-oauth-5b75d4e6-v1 \ + --wheel desktop/.artifacts/server-wheel/powercontext-1.5.3.dev355+g5b75d4e64-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +真实 Server 的匿名、Bearer、HTTPS 和注入式 Provider 四种模式均通过。 +本次验证覆盖组合契约下的 Desktop HTTP/TLS 与 SQLite 行为,服务端幂等重试由独立端到端用例验证。 diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 9c0f30bf66..b3cd333b77 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2212,5 +2212,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-ff058b03-memory-and-batch-capture-protocol-qualification" + }, + { + "id": "sqlite-memory-oauth-5b75d4e6-v1", + "serverCommit": "5b75d4e6468ba0eaf8a8f92388dce18cf48d7abc", + "contractSha256": "b24d0adc353792ed18a64e60f6597bd50b7efbd3297407ae9962374db51a0de8", + "artifactSha256": "60404af75c291e4e40b906d93a8d9d359fe54b1a2e7a5111f59e8d45ecd88e5c", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-5b75d4e6-memory-and-oauth-protocol-qualification" } ] From 8ed387bb9856c1af9d52a04f6a4e43b4794f2d9c Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Tue, 24 Nov 2026 00:30:12 +0800 Subject: [PATCH 21/27] test(desktop): qualify the 1.6 keyed Memory contract --- desktop/VALIDATION.md | 27 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++++++++ docs/en/docs/operate/database-migrations.md | 10 ++++--- docs/zh/docs/operate/database-migrations.md | 10 ++++--- 4 files changed, 61 insertions(+), 8 deletions(-) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 09f18dc947..49059f073a 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4374,3 +4374,30 @@ Reproduce with the recorded artifact (allow sufficient local startup time): --product-qualification sqlite-release-1-6-0-98a9b1f7-v1 \ --wheel /data/codex-tmp/release-1.6.0/wheel/powercontext-1.5.3.dev327+g98a9b1f7f-py3-none-any.whl ``` + +## Server 4ad765be 1.6 and keyed Memory protocol qualification + +`sqlite-memory-1-6-4ad765be-v1` qualifies all thirteen bundled Desktop operations against Server source +`4ad765beaa4bb89f4131ade392f97834dcb7fc82` with OpenAPI version `1.6.0` and keyed `remember_memory` creation. + +- OpenAPI SHA-256: `4178ded59dc9b7333f3b99c0da3275498a3de030bc515a528f6a6565695dd123`. +- Server wheel: `powercontext-1.5.3.dev386+g4ad765bea-py3-none-any.whl`. +- Server wheel SHA-256: `81dc8f38252c676fed5dfc1f7e67afb47f4b4bd3feec526e9a3f1a459ad2198c`. +- Native debug probe SHA-256: `f2dfe8de0e98f1d87539a8eaf052fdc481e40bcdc71dbc98f81535707cd4a1a9`. +- All 838 packaged runtime files match the Git source byte for byte. + +On 2026-11-24, the Linux x86_64 run used Python 3.12.3, SQLite 3.45.1 and Rust 1.95.0. The native +probe selected the bundled product record and matched the Server contract digest in all four real Server +modes: anonymous loopback, static Bearer, HTTPS with a custom CA and base path, and enforced fixture +Provider authentication. The native session suite passed all nine tests. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-1-6-4ad765be-v1 \ + --wheel /path/to/powercontext-1.5.3.dev386+g4ad765bea-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform +keyring and native database upgrades require separate validation. diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 14b7a58a56..9e16ca0f66 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2256,5 +2256,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-5b75d4e6-memory-and-oauth-protocol-qualification" + }, + { + "id": "sqlite-memory-1-6-4ad765be-v1", + "serverCommit": "4ad765beaa4bb89f4131ade392f97834dcb7fc82", + "contractSha256": "4178ded59dc9b7333f3b99c0da3275498a3de030bc515a528f6a6565695dd123", + "artifactSha256": "81dc8f38252c676fed5dfc1f7e67afb47f4b4bd3feec526e9a3f1a459ad2198c", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-4ad765be-16-and-keyed-memory-protocol-qualification" } ] diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index 001e476646..d338d13e5e 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -97,6 +97,12 @@ Revision `v1_5_0_005` removes the previous Artifact plugin-framework storage and Revision `v1_5_0_006` adds `pc_source_runners` and `pc_source_collect_targets` for Source collection and drops the empty `pc_source_write_plugins`; it rewrites no records. While `pc_source_write_plugins` still holds records (after `source load --kind write`), the upgrade is refused with `unsupported_plugin_data` and the database stays unchanged. The previous version has no operation that removes these registrations, so such a database currently has no supported in-place upgrade path: keep using the previous version or move to a new database, and do not delete the records by hand to bypass the check. The previous Source management service's own SQLite is not migrated. See [Source plugins](../workflows/source-plugins.md). +On development builds with keyed Memory creation, both paths continue from `v1_6_0` to draft `000`. + +The cumulative draft `000` registers `pc_atomic_memory_idempotency`, the retry receipts for keyed `remember_memory` creations, with an index on their expiry time. Existing managed databases require explicit migration before Server startup; the migration creates an empty table and rewrites no existing data. A receipt stores SHA-256 digests of the key namespace and the created content, the bound Artifact revision and the creation state version; it stores neither the raw key, the principal ID nor the memory body. Receipts expire 24 hours after creation and are removed in bounded batches. See [Atomic Memory](../workflows/atomic-memory.md) for retry behavior. + +Rebuild development databases and migration plans that use an earlier `000` draft or the unpublished `v1_5_2_001` revision. + Revision `v1_4_1_006` registers `pc_source_write_plugins` for persisted Source write plugin declarations. Revision `v1_5_0_001` adds Artifact plugin registration fields, family schemas, search state and projections, index coverage and change tracking, and vector-space/index registrations. SQLite also registers portable vector @@ -904,10 +910,6 @@ registered migration chain and read-only startup admission; its startup never in ### Prepare diagnostic storage -On development builds with keyed Memory creation, both paths continue from `v1_6_0` to draft `000`. - -The cumulative draft `000` registers `pc_atomic_memory_idempotency`, the retry receipts for keyed `remember_memory` creations, with an index on their expiry time. Existing managed databases require explicit migration before Server startup; the migration creates an empty table and rewrites no existing data. A receipt stores SHA-256 digests of the key namespace and the created content, the bound Artifact revision and the creation state version; it stores neither the raw key, the principal ID nor the memory body. Receipts expire 24 hours after creation and are removed in bounded batches. See [Atomic Memory](../workflows/atomic-memory.md) for retry behavior. - Revision `v1_6_0` adds only `pc_context_prepare_diagnostics` and its Scope/time/status indexes. It does not change existing records or backfill past prepare calls. The table has no Scope deletion foreign key or cascade. Existing managed installations must migrate before startup. Capture is always on for the Server; recovery uses the existing diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 96d1cf7d83..3a4daa2cf3 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -80,6 +80,12 @@ payload 身份及待处理 intent。兼容的当前任务原样保留,不套 修订 `v1_5_0_006` 新增 Source 采集用的 `pc_source_runners` 和 `pc_source_collect_targets`,并删除空的 `pc_source_write_plugins`,不改写任何记录。`pc_source_write_plugins` 中仍有记录时(执行过 `source load --kind write`),升级以 `unsupported_plugin_data` 拒绝,数据库保持不变;旧版本没有删除这些登记的操作,所以这样的数据库目前没有受支持的原地升级路径,请继续使用旧版本或改用新的数据库,不要手工删除记录来绕过检查。旧 Source 管理服务自己的 SQLite 不迁移。详见 [Source 插件](../workflows/source-plugins.md)。 +支持带键 Memory 创建的开发版本中,两条路径均从 `v1_6_0` 继续迁移到草稿 `000`。 + +累计迁移草稿 `000` 登记 `pc_atomic_memory_idempotency`,即带键 `remember_memory` 创建的重试回执,并为过期时间建立索引。已有受管数据库必须在 Server 启动前显式迁移;迁移只创建空表,不重写任何既有数据。回执保存键命名空间与所创建内容的 SHA-256 摘要、所绑定的 Artifact revision 及创建时的 state version,不保存原始键、principal ID 或记忆正文。回执在创建 24 小时后过期,并按有界批次清理。重试行为参见 [Atomic Memory](../workflows/atomic-memory.md)。 + +使用早期草稿 `000` 或未发布修订 `v1_5_2_001` 的开发数据库和迁移计划需要重建。 + `v1_5_0_001` 增加 Artifact 插件注册字段、family schema、检索状态和投影、索引覆盖与变更跟踪,以及向量空间和索引登记。 SQLite 还登记可移植向量和 FTS 辅助结构。两条来源链均通过显式维护加入这些增量变更;历史修订资源与校验和保持不变。 根据已登记空间创建的原生向量表,必须通过精确布局检查才能纳入后续维护。上述登记不扩展受支持的来源版本, @@ -667,10 +673,6 @@ Scope 的原始标题、摘要、外部引用和 binding 标识保持不变。 ### 上下文准备诊断存储 -支持带键 Memory 创建的开发版本中,两条路径均从 `v1_6_0` 继续迁移到草稿 `000`。 - -累计迁移草稿 `000` 登记 `pc_atomic_memory_idempotency`,即带键 `remember_memory` 创建的重试回执,并为过期时间建立索引。已有受管数据库必须在 Server 启动前显式迁移;迁移只创建空表,不重写任何既有数据。回执保存键命名空间与所创建内容的 SHA-256 摘要、所绑定的 Artifact revision 及创建时的 state version,不保存原始键、principal ID 或记忆正文。回执在创建 24 小时后过期,并按有界批次清理。重试行为参见 [Atomic Memory](../workflows/atomic-memory.md)。 - 迁移 `v1_6_0` 只新增 `pc_context_prepare_diagnostics` 及其 Scope/时间/状态索引,不修改既有记录,也不为历史准备调用回填。 该表没有 Scope 删除外键或级联。既有受管安装必须在启动前完成迁移。Server 的捕获始终开启;恢复沿用既有已验证备份工作流, 从不自动删除诊断记录。 From b89e2d813848d7944e6c1fedec97d85a23e58c87 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Fri, 27 Nov 2026 00:56:37 +0800 Subject: [PATCH 22/27] test: qualify the combined Desktop and Memory migration contract --- desktop/VALIDATION.md | 28 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++++++++ docs/en/docs/operate/database-migrations.md | 2 +- docs/zh/docs/operate/database-migrations.md | 2 +- tests/test_atomic_memory_alias_upgrade.py | 6 +++- 5 files changed, 57 insertions(+), 3 deletions(-) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 6ab18694c5..41a8570fad 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4431,3 +4431,31 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform keyring and native database upgrades require separate validation. + +## Server 3db8c17d 1.6 and keyed Memory protocol qualification + +`sqlite-memory-1-6-3db8c17d-v1` covers all thirteen bundled Desktop operations against Server source +`3db8c17d45a73dd07df989c00c2101f18b6a1c77`. The OpenAPI 1.6.0 contract includes Source response metadata and keyed +`remember_memory` creation. + +- Normalized OpenAPI SHA-256: `afa4523d92f32dc64a39e5b455214c1cf93172f9a696301331407dcf94bb8f19`. +- Server wheel: `powercontext-1.5.3.dev485+g3db8c17d4-py3-none-any.whl`. +- Server wheel SHA-256: `fbd66f53e645ecfaee171e6e3498f20a5078a44183c4329b81f607ae69d9a8f4`. +- Native debug probe SHA-256: `762fffdd687796fbbec9524535271396990823f3078b8943432c4b52b927fe74`. +- All 842 packaged runtime files match the Git source byte for byte. + +On 2026-11-27, a Linux x86_64 container with Python 3.12.3, SQLite 3.45.1 and Rust 1.95.0 ran the native probe +against the packaged Server. The probe selected the bundled product record and matched the contract digest +in all four modes: anonymous loopback, static Bearer, HTTPS with a custom CA and base path, and enforced +fixture Provider authentication. All nine native session tests passed. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-1-6-3db8c17d-v1 \ + --wheel /path/to/powercontext-1.5.3.dev485+g3db8c17d4-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform +keyring and native database upgrades require separate validation. diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 5911b05bd3..1aaf3ccbc1 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2300,5 +2300,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-4ad765be-16-and-keyed-memory-protocol-qualification" + }, + { + "id": "sqlite-memory-1-6-3db8c17d-v1", + "serverCommit": "3db8c17d45a73dd07df989c00c2101f18b6a1c77", + "contractSha256": "afa4523d92f32dc64a39e5b455214c1cf93172f9a696301331407dcf94bb8f19", + "artifactSha256": "fbd66f53e645ecfaee171e6e3498f20a5078a44183c4329b81f607ae69d9a8f4", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-3db8c17d-16-and-keyed-memory-protocol-qualification" } ] diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index 0ea1a13dd7..113532b453 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -181,7 +181,7 @@ literal mutable draft ID `000`. The registered revisions are: | `v1_5_0_005` | 1.5.0 | 5 | `v1_5_0_005` | Remove previous plugin-framework storage and add nullable Artifact metadata | | `v1_5_0_006` | 1.5.0 | 6 | `v1_5_0_006` | Source collection runner and target tables; remove the write plugin registry | | `v1_6_0` | 1.6.0 | — | `v1_6_0` | Independent prepare diagnostics | -| `000` | — | — | `000` | Disposable historical Atomic Memory alias projection | +| `000` | — | — | `000` | Disposable historical Atomic Memory alias projection and keyed Memory creation receipts | Both registered source paths reach `000` after `v1_6_0`; only 1.3.0 is selected for CI upgrade acceptance: diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 3f68be3a0a..d23057529d 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -151,7 +151,7 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 | `v1_5_0_005` | 1.5.0 | 第五步 | `v1_5_0_005` | 移除旧插件框架存储并新增可空的 Artifact 元数据 | | `v1_5_0_006` | 1.5.0 | 第六步 | `v1_5_0_006` | Source 采集的 runner 与目标表,移除 write 插件登记表 | | `v1_6_0` | 1.6.0 | — | `v1_6_0` | 独立上下文准备诊断 | -| `000` | — | — | `000` | 可重建的 Atomic Memory 历史别名投影 | +| `000` | — | — | `000` | 可重建的 Atomic Memory 历史别名投影及带键写入回执 | 两条已登记来源路径都在 `v1_6_0` 之后到达 `000`;CI 升级验收只选择 1.3.0: diff --git a/tests/test_atomic_memory_alias_upgrade.py b/tests/test_atomic_memory_alias_upgrade.py index 2b4ea07b3b..853bdad13c 100644 --- a/tests/test_atomic_memory_alias_upgrade.py +++ b/tests/test_atomic_memory_alias_upgrade.py @@ -52,7 +52,11 @@ def test_registered_mysql_alias_layout_uses_configured_vector_type(dimension): ) bundle = server_bundle(embedding_profile=profile) schema = MySQLSchema(bundle) - (statement,) = schema.statements("000") + (statement,) = ( + statement + for statement in schema.statements("000") + if statement.startswith("CREATE TABLE pc_atomic_memory_alias (") + ) name, table = _parse_table(statement) assert name == "pc_atomic_memory_alias" assert table == schema.required(bundle.head)["tables"][name] From d47074dd550f2875634d17ba7ee157b52281df39 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Sat, 28 Nov 2026 17:05:46 +0800 Subject: [PATCH 23/27] test(desktop): qualify the combined Source limits and keyed Memory contract --- desktop/VALIDATION.md | 28 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index ed55281483..520bf00497 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4492,3 +4492,31 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform keyring and native database upgrades require separate validation. + +## Server 84e35eb7 1.6 and keyed Memory protocol qualification + +`sqlite-memory-1-6-84e35eb7-v1` covers all thirteen bundled Desktop operations against Server source +`84e35eb73ca77564d1b03abf63c824a9986919b3`. The OpenAPI 1.6.0 contract includes Content Source limit discovery and keyed +`remember_memory` creation. + +- Normalized OpenAPI SHA-256: `676885fe400bc546197bee980223891bd639dba5485374c742b381148ada8dfa`. +- Server wheel: `powercontext-1.5.3.dev532+g84e35eb73-py3-none-any.whl`. +- Server wheel SHA-256: `f613e9c0a1bfee68c70ed06ffa17686291d83ee6069d238002bf83c47e3c6135`. +- Native debug probe SHA-256: `3b65bb5a5ba37a8e211d65266a9d858c81b936c8eafd25f02dbe22dd0cd9eee5`. +- All 842 packaged runtime files match the Git source byte for byte. + +On 2026-11-28, a Linux x86_64 container with Python 3.12.3, SQLite 3.45.1 and Rust 1.95.0 ran the native probe +against the packaged Server. The probe selected the bundled product record and matched the contract digest +in all four modes: anonymous loopback, static Bearer, HTTPS with a custom CA and base path, and enforced +fixture Provider authentication. All nine native session tests passed. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-1-6-84e35eb7-v1 \ + --wheel /path/to/powercontext-1.5.3.dev532+g84e35eb73-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform +keyring and native database upgrades require separate validation. diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 8efa2adc61..5fe492ac72 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2344,5 +2344,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-3db8c17d-16-and-keyed-memory-protocol-qualification" + }, + { + "id": "sqlite-memory-1-6-84e35eb7-v1", + "serverCommit": "84e35eb73ca77564d1b03abf63c824a9986919b3", + "contractSha256": "676885fe400bc546197bee980223891bd639dba5485374c742b381148ada8dfa", + "artifactSha256": "f613e9c0a1bfee68c70ed06ffa17686291d83ee6069d238002bf83c47e3c6135", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-84e35eb7-16-and-keyed-memory-protocol-qualification" } ] From 97f81fb45cdbfe82e778b635f005be5d133547a8 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Mon, 30 Nov 2026 21:23:33 +0800 Subject: [PATCH 24/27] test(desktop): qualify combined tag limits and keyed Memory contract --- desktop/VALIDATION.md | 28 +++++++++++++++++++ .../src/connections/compatibility.json | 22 +++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 992ed032cd..1ef3fc8334 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -4554,3 +4554,31 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform keyring and native database upgrades require separate validation. + +## Server b62f10eb 1.6 and keyed Memory protocol qualification + +`sqlite-memory-1-6-b62f10eb-v1` covers all thirteen bundled Desktop operations against Server source +`b62f10eb69f1504c746c2d1922bbe792dbd66add`. The OpenAPI 1.6.0 contract includes configurable tag limits and keyed +`remember_memory` creation. + +- Normalized OpenAPI SHA-256: `1b46ad9b1d1657652db32ad174b2207ba1c41e755fd1ef52a2d69e6c0f905f1d`. +- Server wheel: `powercontext-1.5.3.dev564+gb62f10eb6-py3-none-any.whl`. +- Server wheel SHA-256: `bd53af87fdcc8266d50e25fd4d487825dc48703f4b5d6174c36d5c8252d9f640`. +- Native debug probe SHA-256: `d59134755d53b9ef06685a7cfd55572c9a94f7080fc16201816ea3941764ca53`. +- All 844 packaged runtime files match the Git source byte for byte. + +On 2026-11-30, a Linux x86_64 container with Python 3.12.3, SQLite 3.45.1 and Rust 1.95.0 ran the native probe +against the packaged Server. The probe selected the bundled product record and matched the contract digest +in all four modes: anonymous loopback, static Bearer, HTTPS with a custom CA and base path, and enforced +fixture Provider authentication. All nine native session tests passed. + +```sh +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +python desktop/tests/real_server.py \ + --product-qualification sqlite-memory-1-6-b62f10eb-v1 \ + --wheel /path/to/powercontext-1.5.3.dev564+gb62f10eb6-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml --test session +``` + +The qualification covers the Desktop protocol with a packaged SQLite Server. Installed WebView, platform +keyring and native database upgrades require separate validation. diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 7ed91d0929..20ef130720 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2388,5 +2388,27 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-84e35eb7-16-and-keyed-memory-protocol-qualification" + }, + { + "id": "sqlite-memory-1-6-b62f10eb-v1", + "serverCommit": "b62f10eb69f1504c746c2d1922bbe792dbd66add", + "contractSha256": "1b46ad9b1d1657652db32ad174b2207ba1c41e755fd1ef52a2d69e6c0f905f1d", + "artifactSha256": "bd53af87fdcc8266d50e25fd4d487825dc48703f4b5d6174c36d5c8252d9f640", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-b62f10eb-16-and-keyed-memory-protocol-qualification" } ] From 55f9740126851f39bc35aa07338364b45f008edd Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Tue, 1 Dec 2026 00:36:50 +0800 Subject: [PATCH 25/27] fix(ci): bound E2E workers for deadline-sensitive tests The failing Python 3.11 shard starts 32 xdist workers. In a four-CPU container, repeated write-contention cases fail 10/30 at 32 workers and 2/30 at 16 workers, while 8 workers pass 30/30 and the focused suite passes 287 tests. Bound E2E workers to 8, matching the unit job, to reduce scheduling contention while retaining the existing write-time assertions. The exact original 1.069-second failure remains unproven locally. --- .github/workflows/master.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index d8d8e237c5..6fe8f472de 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -367,6 +367,8 @@ jobs: if: matrix.suite == 'e2e' env: PYTEST_ADDOPTS: --ci-shard-index=${{ matrix.shard-index }} --ci-shard-count=${{ matrix.shard-count }} + # Keep deadline-sensitive SQLite and subprocess tests within the runner budget. + PYTEST_WORKERS: "8" run: | PYTHONPATH="$PWD/.github/scripts${PYTHONPATH:+:$PYTHONPATH}" \ make e2e-test-parallel PYTEST_ARGS="-p pytest_ci_diagnostics -o faulthandler_timeout=600 --junitxml=$RUNNER_TEMP/pytest-diagnostics/e2e.xml" From 9747f0867f14dbb5fe990dbed3f6abe09fe82d38 Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Tue, 1 Dec 2026 23:11:28 +0800 Subject: [PATCH 26/27] test(desktop): qualify the 1.6.1 keyed Memory contract Qualify Server deedec9bc against all thirteen Desktop operations in anonymous loopback, static Bearer, HTTPS with CA/base path, and Provider modes. All 842 packaged runtime files match the source. Native sessions pass 9 tests, IPC generation matches, and the replacement UI passes 86 tests. Record exact contract and wheel digests in the product catalog. --- .../src/connections/compatibility.json | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index cf9ef18219..5d5339afc0 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1959,5 +1959,26 @@ "remember_memory", "search_memory" ] + }, + { + "id": "sqlite-memory-1-6-deedec9b-v1", + "serverCommit": "deedec9bcdf1272a4a6d2e0fea5db0b71b57d4ec", + "contractSha256": "419278292c9065144d081c7cb369b8ff2fcd4161c8c56052a97b5dcfa6b89d52", + "artifactSha256": "4aea81977845c40bd670a3a1207d0374ef151857d4592772369cf0fe603161bf", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ] } ] From 79daca289252372d73420a1ce6fa816c9db0f98d Mon Sep 17 00:00:00 2001 From: Doar <2508356590@qq.com> Date: Wed, 2 Dec 2026 13:19:36 +0800 Subject: [PATCH 27/27] test(desktop): qualify the merged keyed Memory contract --- .../src/connections/compatibility.json | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 1c7c2445a0..63e5f65d9e 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2022,5 +2022,26 @@ "remember_memory", "search_memory" ] + }, + { + "id": "sqlite-memory-1-6-0d1bfe33-v1", + "serverCommit": "0d1bfe33a3b894086b9c6e5c324b70f85df7cb73", + "contractSha256": "727649c606e096a92d88e56959e24e751df9398fd90175464b59f44b98cd40b6", + "artifactSha256": "0480c6c1cb945cc6908bca03b4c11b99903438da19f19f4f58bc53401b19af1d", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ] } ]