diff --git a/.env.example b/.env.example index f357e758a3..b5e2b659d1 100644 --- a/.env.example +++ b/.env.example @@ -85,6 +85,10 @@ POWERCONTEXT_SERVER_DATABASE_KIND=sqlite POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT=100 # Maximum sum of explicit assembly section limits; per-family limits still apply. POWERCONTEXT_SERVER_RUNTIME_CONTEXT_ASSEMBLY_MAX_ENTRIES=8 +# Maximum labels on one Artifact tag set, 1..256; applies to writes, Dream approval and merge selection. +POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT=32 +# Maximum labels in one tag query or filter, 1..64. +POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS=16 POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE=coding POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS=60 POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS=60 diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index ce349dec4c..b4c7031e14 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -3991,3 +3991,37 @@ POWERCONTEXT_SERVER_ACCESS_MODE=enforced POWERCONTEXT_SERVER_AUTH_TOKEN=qualific POWERCONTEXT_SERVER_SOURCE_CONTENT_MAX_CHARS=64 \ /tmp/pc-venv-limit7/bin/powercontext server run --host 127.0.0.1 --port 8246 --no-env-file ``` + +## Server b7399de tag limits protocol qualification + +`sqlite-tag-limits-b7399de-v1` covers all thirteen Desktop protocol operations against Server source +`b7399deae0965226d4aa4bb4ebcb10adee5d2bbc`. The contract makes the per-Artifact and per-query tag limits deployment +settings, widens the candidate response contract to the same ceiling, rejects over-limit proposals and revisions before +they are stored, and applies the query limit to plugin listings without changing page sizes; the Desktop operations and +their request or response shapes are unchanged. + +- Normalized OpenAPI SHA-256: `4a632917abc6a54f117d2c7dd299b105534a5cbe576f653750cf130ada1e69d5`. +- Wheel: `powercontext-0.1.dev2+gb7399deae-py3-none-any.whl`. +- Wheel SHA-256: `7e2d4630af1688bcfd9fa9e273b65575a6a76079198d34365e084916d72fc7ed`. + +On 2026-11-29, Linux x86_64 (WSL2) with Python 3.14 and that wheel passed static Bearer mode with an enforced token: +unauthenticated requests returned 401, and the bundled Python client exercised all thirteen operations. The Server ran +with `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT=64` and `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS=20`: +64 Artifact labels were accepted and 65 rejected with a `422` naming the limit; a 20-label tag query succeeded and a +21-label query was rejected with a `400` naming the limit; a 21-label Atomic Memory list filter was rejected with the +same `422` query-limit error. + +The native `server_probe` was not rebuilt for this record because the validation environment has no Rust toolchain. This +record therefore establishes HTTP protocol compatibility between the new client contract and the exact wheel; it does not +establish native-probe, installed-WebView, Windows/macOS or release acceptance. + +Reproduce against the recorded artifact: + +```sh +uv build --wheel --out-dir /tmp/pc-wheel-tags7 +uv pip install --python ~/pc-venv-tags/bin/python \ + "/tmp/pc-wheel-tags7/powercontext-0.1.dev2+gb7399deae-py3-none-any.whl[server,cli]" +POWERCONTEXT_SERVER_ACCESS_MODE=enforced POWERCONTEXT_SERVER_AUTH_TOKEN=qualification-token \ + POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT=64 POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS=20 \ + ~/pc-venv-tags/bin/powercontext server run --host 127.0.0.1 --port 8250 --no-env-file +``` diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 43dd11f4e2..d1701c3e00 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-7b58ce2-source-content-limit-protocol-qualification" + }, + { + "id": "sqlite-tag-limits-b7399de-v1", + "serverCommit": "b7399deae0965226d4aa4bb4ebcb10adee5d2bbc", + "contractSha256": "4a632917abc6a54f117d2c7dd299b105534a5cbe576f653750cf130ada1e69d5", + "artifactSha256": "7e2d4630af1688bcfd9fa9e273b65575a6a76079198d34365e084916d72fc7ed", + "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-b7399de-tag-limits-protocol-qualification" } ] diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index 0497c81684..78c639983d 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "29f33308b74ff51bdd3d9825f85d7dd5a2308c80a476c6b1badf32a850e662f5", + "contractSha256": "4a632917abc6a54f117d2c7dd299b105534a5cbe576f653750cf130ada1e69d5", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/src-tauri/src/transport/wire.rs b/desktop/src-tauri/src/transport/wire.rs index 157203c497..5e4be72c05 100644 --- a/desktop/src-tauri/src/transport/wire.rs +++ b/desktop/src-tauri/src/transport/wire.rs @@ -2880,6 +2880,7 @@ pub enum SubtreeScopeSelectionMode { Subtree, } +/// TagFilter : Exact label filter. The deployment's configured query-label limit, 16 by default, applies. #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] #[serde(deny_unknown_fields)] pub struct TagFilter { @@ -2891,6 +2892,7 @@ pub struct TagFilter { } impl TagFilter { + /// Exact label filter. The deployment's configured query-label limit, 16 by default, applies. #[allow(clippy::too_many_arguments)] pub fn new(tags: Vec) -> TagFilter { TagFilter { diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index 57ea3f6d15..0cde8d077f 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -5853,12 +5853,13 @@ export interface components { entry_id: string; }; TagTarget: components["schemas"]["ArtifactTagTarget"] | components["schemas"]["MemoryEntryTagTarget"]; + /** @description Exact label filter. The deployment's configured query-label limit, 16 by default, applies. */ TagFilter: { tags: string[]; /** @default all */ match: components["schemas"]["TagMatch"]; }; - /** @description Replace all labels atomically. Empty clears the set. Labels preserve display text, use NFC then casefold for exact matching, and reject normalized duplicates, outer whitespace, and Unicode control, surrogate or unassigned characters. */ + /** @description Replace all labels atomically. Empty clears the set. The deployment's configured Artifact tag limit, 32 by default, applies. Labels preserve display text, use NFC then casefold for exact matching, and reject normalized duplicates, outer whitespace, and Unicode control, surrogate or unassigned characters. */ ReplaceArtifactTagsRequest: { tags: string[]; }; diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index e091107944..9da92681d1 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 = "29f33308b74ff51bdd3d9825f85d7dd5a2308c80a476c6b1badf32a850e662f5"; +export const contractSha256 = "4a632917abc6a54f117d2c7dd299b105534a5cbe576f653750cf130ada1e69d5"; export const operations = { "get_liveness": { "method": "GET", diff --git a/docs/en/docs/operate/configuration.md b/docs/en/docs/operate/configuration.md index f37667683c..10ee5bca4d 100644 --- a/docs/en/docs/operate/configuration.md +++ b/docs/en/docs/operate/configuration.md @@ -64,9 +64,11 @@ changes authoritative history. For a hosted decision backend, set `MEMORY_WRITE_ and explicitly select `MEMORY_WRITE_GATE_SANITIZER=known_secrets`. The sanitizer covers known sensitive environment/Codex values and a bounded set of provider-key prefixes; it is not a general PII or password detector. The sanitizer selection defaults to `none`, and hosted-redacted composition fails with a named configuration error until one is selected. -The existing limit of 32 tags per Artifact still applies to a merge result. When its inputs carry more than 32 distinct -normalized labels, the result keeps a deterministic selection of 32, and the merge and its Source window commit -normally. See [Organize with tags](../workflows/manage-artifact-tags.md#label-rules-and-storage) for the selection order. +The deployment's Artifact tag limit applies to a merge result. It is 32 tags by default and can be raised to 256 with +`POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT`; the query-label limit is 16 by default and can be raised to 64 with +`POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS`. Both settings take effect on restart. Clients built from this contract +are required to read or write more than 32 labels; a client built from an earlier contract rejects them. When a merge's inputs carry more normalized labels than the effective +limit, the result keeps a deterministic selection of that size, and the merge and its Source window commit normally. See [Organize with tags](../workflows/manage-artifact-tags.md#label-rules-and-storage) for the selection order. ## User data @@ -172,6 +174,8 @@ still occupies an HTTP slot until it finishes; reserve other slots for concurren | `POWERCONTEXT_SERVER_DATABASE_BUSY_TIMEOUT_MS` | `5000` | Milliseconds a business connection waits for SQLite's single write lock before raising; it does not govern usage accounting, which has its own bounded budget | | `POWERCONTEXT_SERVER_RUNTIME_SCOPE_CACHE_SIZE` | `128` | Inactive scope compositions retained by the Runtime; in-flight scopes are never evicted | | `POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT` | `100` | Maximum Source journal positions per activation; Memory reduces its window after generation timeouts | +| `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT` | `32` | Effective maximum labels on one Artifact tag set; `1` to `256`. Applies to tag replacement, Dream/catalog approval and merge selection | +| `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS` | `16` | Effective maximum labels in one tag query or filter; `1` to `64`. Applies to tag queries and Artifact or Memory tag filters | | `POWERCONTEXT_SERVER_RUNTIME_CONTEXT_ASSEMBLY_MAX_ENTRIES` | `8` | Maximum sum of explicit `assembly.sections[].limit`; positive integer. Per-family limits still apply. | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE` | `coding` | Memory selection policy: `coding` or `conversation` | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_ENABLED` | `false` | Apply listwise reranking after coarse Memory retrieval | diff --git a/docs/en/docs/workflows/manage-artifact-tags.md b/docs/en/docs/workflows/manage-artifact-tags.md index 81d122a4f4..85feb47375 100644 --- a/docs/en/docs/workflows/manage-artifact-tags.md +++ b/docs/en/docs/workflows/manage-artifact-tags.md @@ -113,7 +113,9 @@ does not freeze a snapshot across requests. ## Label rules and storage -- A target holds at most 32 labels; a filter accepts 1–16 labels. +- A target holds at most the deployment's Artifact tag limit: 32 labels by default, configured with + `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT` (1–256). A filter accepts 1 label up to the deployment's + query-label limit: 16 by default, configured with `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS` (1–64). - Each label has 1–64 Unicode code points, no outer whitespace, and no control, surrogate, or unassigned characters. - Matching uses NFC normalization followed by Unicode case folding. The submitted display spelling is retained. Normalized duplicates such as `Straße` and `STRASSE` are rejected atomically. A normalized key may not exceed 128 @@ -121,8 +123,9 @@ does not freeze a snapshot across requests. - Tags are Scope-local discovery metadata, not permissions or trusted instructions. They are not added to model prompts, Skill package frontmatter, or publication/import payloads. Published copies start without the source target's tags. - Inactive memories retain their authoritative tags. Rebuilding active search projections does not delete them. -- A merge result starts with tags drawn from its inputs. When the inputs carry more than 32 distinct normalized labels, - the result keeps 32: labels carried by more inputs first, then code point order of the normalized key. The selection +- A merge result starts with tags drawn from its inputs. When the inputs carry more normalized labels than the effective + Artifact limit, the result keeps that many: labels carried by more inputs first, then code point order of the normalized + key. The selection does not depend on input order, so repeating the same merge assigns the same tags. The merged inputs keep their complete tag sets, and restoration makes them active with those tags. diff --git a/docs/en/docs/workflows/review-dream-revisions.md b/docs/en/docs/workflows/review-dream-revisions.md index 4d4b2d1ecf..88d403f27d 100644 --- a/docs/en/docs/workflows/review-dream-revisions.md +++ b/docs/en/docs/workflows/review-dream-revisions.md @@ -87,6 +87,8 @@ async def propose_tags(client, scope_id, current, tags_etag, evidence_source_id) Atomic Memory uses `ArtifactTagTarget(family="atomic-memory", ...)` and the exact `basis_ref`, just like other Artifacts. Its target is comparison context and cannot support its own Tag change; supply independent evidence. The resulting run has `candidate.kind="tag"`. Inspect it using `get_candidate(GetCandidateRequest(...))`; approval uses `approve_candidate(ApproveCandidateRequest(...))`. The unified `/v1/candidates/list|get|history|revise|approve|reject` interfaces preserve Tag's distinct lifecycle. Approval checks both the Tag ETag and content baseline atomically. The result contains the complete tags and new ETag, with no Artifact revision. +An over-limit Dream Tag proposal fails its run with `invalid_generation_output` and creates no candidate. A revise, or an approval of a candidate created before the limit was lowered, whose `after_tags` exceeds the deployment's effective Artifact tag limit returns `422 invalid_request` with `details.field="after_tags"`, `details.reason="tag_limit_exceeded"` and the effective `details.limit`; an embedded `catalog_changes.propose` caller gets `InvalidCandidateError`. Approval leaves the target unchanged. + ```sh powercontext candidate list --candidate-kind tag --scope-id "$SCOPE_ID" powercontext candidate show --scope-id "$SCOPE_ID" "$CANDIDATE_ID" diff --git a/docs/en/rfcs/1467_artifact_tags.md b/docs/en/rfcs/1467_artifact_tags.md index 9faa28e454..e77abc60f4 100644 --- a/docs/en/rfcs/1467_artifact_tags.md +++ b/docs/en/rfcs/1467_artifact_tags.md @@ -239,7 +239,7 @@ A submitted tag must satisfy all of the following: - it has no leading or trailing whitespace; - it contains no Unicode control, surrogate, or unassigned code point; - its normalized key is at most 128 Unicode code points; and -- the complete submitted set contains at most 32 tags. +- the complete submitted set contains at most the deployment's effective Artifact tag limit (32 by default, ceiling 256). PowerContext preserves the submitted value as `tag` for display. It computes `tag_key` by applying Unicode NFC and then Unicode default case folding. It does not collapse internal whitespace, split punctuation, parse `/`, translate, diff --git a/docs/en/rfcs/1715_multi_artifact_dreaming.md b/docs/en/rfcs/1715_multi_artifact_dreaming.md index 6f299df477..ccb54f88df 100644 --- a/docs/en/rfcs/1715_multi_artifact_dreaming.md +++ b/docs/en/rfcs/1715_multi_artifact_dreaming.md @@ -124,7 +124,7 @@ For a Memory entry, use a target with type=memory_entry, family=memory, artifact | `/v1/candidates/approve` | scope_id, candidate_id, expected_version | Conditional Tag replacement and stored result | | `/v1/candidates/reject` | scope_id, candidate_id, expected_version, reason | Terminal rejection without changing tags | -Reads require scope.read; review mutations require scope.review and applicable target permissions. The complete proposal retains the original target, expected_etag, basis, and before_tags. Revision must not change those fields to bypass a conflict. after_tags contains the entire replacement set: 0–32 labels, each 1–64 characters. An empty set clears the tags. Apply NFC/casefold normalization and reject duplicates after normalization. +Reads require scope.read; review mutations require scope.review and applicable target permissions. The complete proposal retains the original target, expected_etag, basis, and before_tags. Revision must not change those fields to bypass a conflict. after_tags contains the entire replacement set: 0 to the deployment's effective Artifact tag limit (32 by default, ceiling 256) labels, each 1–64 characters. An empty set clears the tags. Apply NFC/casefold normalization and reject duplicates after normalization. Example request to `/v1/candidates/revise`: diff --git a/docs/zh/docs/operate/configuration.md b/docs/zh/docs/operate/configuration.md index a01348fdaf..59a7d2afff 100644 --- a/docs/zh/docs/operate/configuration.md +++ b/docs/zh/docs/operate/configuration.md @@ -54,8 +54,12 @@ MemoryWriteGate 采用 fail-open 策略,只裁决写入,不修改权威历 `MEMORY_WRITE_GATE_PRIVACY_BOUNDARY=hosted_redacted` 和显式的 `MEMORY_WRITE_GATE_SANITIZER=known_secrets`。 内置 sanitizer 覆盖已知的敏感环境变量/Codex 值及有限的 provider 前缀,不是通用的 PII 或口令检测器。sanitizer 默认是 `none`;hosted-redacted 组合在未选择 sanitizer 时会以命名配置错误失败。 -合并结果仍遵守每个 Artifact 最多 32 个标签的限制。输入标签按规范化键去重后超过 32 个时,结果保留确定性选出的 32 个, -合并及其 Source 窗口照常提交。选择顺序见[使用标签整理内容](../workflows/manage-artifact-tags.md#标签规则与存储)。 +合并结果遵守部署的 Artifact 标签上限:默认 32 个,可通过 +`POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT` 提高到 256;查询标签上限默认 16,可通过 +`POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS` 提高到 64。两个设置都在重启后生效。 +要读写超过 32 个标签,客户端必须使用当前契约构建;旧契约构建的客户端会拒绝这些数据。 +输入标签按规范化键去重后超过生效上限时,结果保留确定性选出的该上限数量,合并及其 Source 窗口照常提交。 +选择顺序见[使用标签整理内容](../workflows/manage-artifact-tags.md#标签规则与存储)。 ## 用户数据 @@ -156,6 +160,8 @@ MCP 使用 stateless Streamable HTTP,每次工具执行都采用当前请求 | `POWERCONTEXT_SERVER_DATABASE_BUSY_TIMEOUT_MS` | `5000` | 业务连接等待 SQLite 单一写锁的毫秒数;它不约束用量记账,后者有自己的有界预算 | | `POWERCONTEXT_SERVER_RUNTIME_SCOPE_CACHE_SIZE` | `128` | Runtime 保留的非活动 scope composition 数量;进行中的 scope 不会被驱逐 | | `POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT` | `100` | 每次处理的 Source 日志位置上限;Memory 在生成超时后会缩小窗口 | +| `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT` | `32` | 单个 Artifact 标签集的生效上限,取值 `1` 到 `256`;适用于标签替换、Dream/Catalog 审批和合并选标签 | +| `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS` | `16` | 单次标签查询或过滤的生效上限,取值 `1` 到 `64`;适用于标签查询以及 Artifact、Memory 标签过滤 | | `POWERCONTEXT_SERVER_RUNTIME_CONTEXT_ASSEMBLY_MAX_ENTRIES` | `8` | 显式 `assembly.sections[].limit` 之和的上限;正整数,各类别单独上限仍适用 | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_EXTRACTION_PROFILE` | `coding` | Memory 选择策略:`coding` 或 `conversation` | | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_ENABLED` | `false` | 在 Memory 粗召回后应用 listwise rerank | diff --git a/docs/zh/docs/workflows/manage-artifact-tags.md b/docs/zh/docs/workflows/manage-artifact-tags.md index bf7cbc048e..995e762f2e 100644 --- a/docs/zh/docs/workflows/manage-artifact-tags.md +++ b/docs/zh/docs/workflows/manage-artifact-tags.md @@ -108,14 +108,16 @@ Atomic Memory 的 list/search 接口使用如下标签字段: ## 标签规则与存储 -- 每个对象最多 32 个标签;一次过滤接受 1–16 个标签。 +- 每个对象最多容纳部署的 Artifact 标签上限:默认 32 个,可通过 + `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT`(1–256)配置。一次过滤接受 1 个到部署的查询标签上限: + 默认 16 个,可通过 `POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_QUERY_LABELS`(1–64)配置。 - 每个标签包含 1–64 个 Unicode 码点,首尾不能有空白,不能包含控制字符、代理字符或未分配字符。 - 匹配键由 NFC 规范化后再执行 Unicode case folding 得到,显示文字保留原始写法。 `Straße` 和 `STRASSE` 等规范化后重复的标签会让整次请求失败;规范化键不能超过 128 个码点。 - 标签是 Scope 内的检索元数据,不是权限或可信指令,不会进入模型提示词、Skill 包 frontmatter 或发布/导入内容。 发布后的副本不会继承源对象的标签。 - 非在役记忆的标签仍保留在权威标签表中;重建搜索投影不会删除这些标签。 -- 合并结果的初始标签取自各输入。输入标签按规范化键去重后超过 32 个时,结果只保留 32 个:先选被更多输入共同携带的标签, +- 合并结果的初始标签取自各输入。输入标签按规范化键去重后超过生效上限时,结果只保留该上限数量的标签:先选被更多输入共同携带的标签, 再按规范化键的 Unicode 码点顺序补足。选择结果与输入顺序无关,重复同一合并会得到相同标签。被合并的输入保留完整标签, 恢复后带着这些标签重新进入在役状态。 diff --git a/docs/zh/docs/workflows/review-dream-revisions.md b/docs/zh/docs/workflows/review-dream-revisions.md index 92c45ef667..038997d035 100644 --- a/docs/zh/docs/workflows/review-dream-revisions.md +++ b/docs/zh/docs/workflows/review-dream-revisions.md @@ -9,6 +9,7 @@ description: 使用 Dream 契约 2 提议并审核 Prompt、标签和 Atomic Mem Dream 使用精确目标与证据生成待审 Candidate。生成不会批准、安装、执行或发布内容;已有自动生成流程保持原有策略。审批须由用户明确决定,并携带实际检查过的候选版本。 + ## Profile 与 Handoff 生效边界 Profile Dream 在接收请求时冻结影响生成的策略配置。普通 Source 处理、待审候选指针变化和仅控制 Source 的激活配置不会使提案失效。生成配置改变需要重新发起 Dream;Profile head 改变则独立触发目标冲突。批准不消费 Source 游标,也不清除普通待审候选。 @@ -86,6 +87,8 @@ async def propose_tags(client, scope_id, current, tags_etag, evidence_source_id) Atomic Memory 与其他制品统一使用 `ArtifactTagTarget(family="atomic-memory", ...)` 和精确的 `basis_ref`。目标只作为比较上下文,不能作为自身 Tag 改动的依据;必须提供独立证据。成功生成后 `candidate.kind="tag"`,通过 `get_candidate(GetCandidateRequest(...))` 检查,通过 `approve_candidate(ApproveCandidateRequest(...))` 决定。统一的 `/v1/candidates/list|get|history|revise|approve|reject` 接口保留标签生命周期,批准时同时校验 ETag 和正文版本,原子替换标签并记录决定,不创建 Artifact Revision。 +超过上限的 Dream Tag 提案会让本次运行以 `invalid_generation_output` 失败,并且不创建候选。修订,或批准一个在上限调低前创建、且 `after_tags` 超过部署生效 Artifact 标签上限的候选,会返回 `422 invalid_request`,其中 `details.field="after_tags"`、`details.reason="tag_limit_exceeded"`,并带有生效的 `details.limit`;嵌入式 `catalog_changes.propose` 调用方会收到 `InvalidCandidateError`。批准被拒绝时目标保持不变。 + ```sh powercontext candidate list --candidate-kind tag --scope-id "$SCOPE_ID" powercontext candidate show --scope-id "$SCOPE_ID" "$CANDIDATE_ID" diff --git a/docs/zh/rfcs/1467_artifact_tags.md b/docs/zh/rfcs/1467_artifact_tags.md index 65905d4c20..54b3785d20 100644 --- a/docs/zh/rfcs/1467_artifact_tags.md +++ b/docs/zh/rfcs/1467_artifact_tags.md @@ -229,7 +229,7 @@ canonical persistence form 使用 `target_id`: - 没有前导或尾随空白; - 不包含 Unicode control、surrogate 或 unassigned code point; - normalized key 不超过 128 个 Unicode code point; -- 完整提交集合最多包含 32 个标签。 +- 完整提交集合最多包含部署生效的 Artifact 标签上限(默认 32,上限 256)。 PowerContext 将提交值保留为用于展示的 `tag`,先应用 Unicode NFC,再应用 Unicode default case folding,生成 `tag_key`。它不会折叠内部空白、拆分标点、解析 `/`、翻译、词干化或推断层级。`tag` 与 `tag_key` 都在规范化后校验。 diff --git a/docs/zh/rfcs/1715_multi_artifact_dreaming.md b/docs/zh/rfcs/1715_multi_artifact_dreaming.md index f3ca630b29..4d0a86f9dd 100644 --- a/docs/zh/rfcs/1715_multi_artifact_dreaming.md +++ b/docs/zh/rfcs/1715_multi_artifact_dreaming.md @@ -298,7 +298,7 @@ Memory 条目目标将 `target` 替换为 `{"type":"memory_entry","family":"memo | `POST /v1/candidates/approve` | `scope_id`、`candidate_id`、`expected_version` | 通过候选版本、标签 ETag 和正文基准校验后替换标签集 | | `POST /v1/candidates/reject` | `scope_id`、`candidate_id`、`expected_version`、`reason` | 拒绝当前版本,不更改正式标签 | -修订提交完整的类型化 proposal;服务端验证 target、expected_etag、basis 和 before_tags 与候选原始基准一致,不允许借修订绕过冲突。`after_tags` 是完整的目标标签集合(0–32 个标签,每个 1–64 个字符);空数组表示清空标签。标签按 NFC 与 casefold 规则规范化,规范化后重复的标签会被拒绝。`expected_version` 是候选版本的并发保护值,旧版本不能被修订、批准或拒绝。 +修订提交完整的类型化 proposal;服务端验证 target、expected_etag、basis 和 before_tags 与候选原始基准一致,不允许借修订绕过冲突。`after_tags` 是完整的目标标签集合(0 到部署生效的 Artifact 标签上限,默认 32、上限 256,每个标签 1–64 个字符);空数组表示清空标签。标签按 NFC 与 casefold 规则规范化,规范化后重复的标签会被拒绝。`expected_version` 是候选版本的并发保护值,旧版本不能被修订、批准或拒绝。 修订候选的请求示例: diff --git a/integrations/dify/plugin/powercontext_dify/contract.json b/integrations/dify/plugin/powercontext_dify/contract.json index 554a48d9d4..440bdd9867 100644 --- a/integrations/dify/plugin/powercontext_dify/contract.json +++ b/integrations/dify/plugin/powercontext_dify/contract.json @@ -1773,7 +1773,7 @@ "minLength": 1, "maxLength": 64 }, - "maxItems": 32 + "maxItems": 256 }, "after_tags": { "type": "array", @@ -1782,7 +1782,7 @@ "minLength": 1, "maxLength": 64 }, - "maxItems": 32 + "maxItems": 256 } } }, @@ -1811,7 +1811,7 @@ "minLength": 1, "maxLength": 64 }, - "maxItems": 32 + "maxItems": 256 }, "tag_digest": { "type": "string", @@ -3005,7 +3005,7 @@ "type": "string", "minLength": 1 }, - "maxItems": 16 + "maxItems": 64 }, "tag_match": { "$ref": "#/components/schemas/TagMatch" @@ -5179,11 +5179,12 @@ "required": [ "tags" ], + "description": "Exact label filter. The deployment's configured query-label limit, 16 by default, applies.", "properties": { "tags": { "type": "array", "minItems": 1, - "maxItems": 16, + "maxItems": 64, "items": { "type": "string", "minLength": 1, diff --git a/integrations/dify/plugin/tools/pc_experience_generate.yaml b/integrations/dify/plugin/tools/pc_experience_generate.yaml index 47f4fb2100..1d77b74c8f 100644 --- a/integrations/dify/plugin/tools/pc_experience_generate.yaml +++ b/integrations/dify/plugin/tools/pc_experience_generate.yaml @@ -1335,14 +1335,14 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 after_tags: type: array items: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 source_refs: type: array maxItems: 32 @@ -1574,7 +1574,7 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 tag_digest: type: string minLength: 1 diff --git a/integrations/dify/plugin/tools/pc_review_get.yaml b/integrations/dify/plugin/tools/pc_review_get.yaml index 849f1453e3..44ef55c2e2 100644 --- a/integrations/dify/plugin/tools/pc_review_get.yaml +++ b/integrations/dify/plugin/tools/pc_review_get.yaml @@ -1232,14 +1232,14 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 after_tags: type: array items: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 source_refs: type: array maxItems: 32 @@ -1469,7 +1469,7 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 tag_digest: type: string minLength: 1 diff --git a/integrations/dify/plugin/tools/pc_review_list.yaml b/integrations/dify/plugin/tools/pc_review_list.yaml index a5c44130ad..f79b02537c 100644 --- a/integrations/dify/plugin/tools/pc_review_list.yaml +++ b/integrations/dify/plugin/tools/pc_review_list.yaml @@ -1345,14 +1345,14 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 after_tags: type: array items: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 source_refs: type: array maxItems: 32 @@ -1584,7 +1584,7 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 tag_digest: type: string minLength: 1 diff --git a/integrations/dify/plugin/tools/pc_skill_generate.yaml b/integrations/dify/plugin/tools/pc_skill_generate.yaml index d7ac5eb64f..4aa0c933fd 100644 --- a/integrations/dify/plugin/tools/pc_skill_generate.yaml +++ b/integrations/dify/plugin/tools/pc_skill_generate.yaml @@ -1360,14 +1360,14 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 after_tags: type: array items: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 source_refs: type: array maxItems: 32 @@ -1599,7 +1599,7 @@ output_schema: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 tag_digest: type: string minLength: 1 diff --git a/openapi/powercontext.yaml b/openapi/powercontext.yaml index 2610c10f48..f900452f78 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -4728,7 +4728,7 @@ paths: schema: type: array minItems: 1 - maxItems: 16 + maxItems: 64 items: {type: string, minLength: 1, maxLength: 64} - name: tag_match in: query @@ -6137,7 +6137,7 @@ components: items: type: string minLength: 1 - maxItems: 16 + maxItems: 64 tag_match: $ref: '#/components/schemas/TagMatch' limit: @@ -6373,7 +6373,7 @@ components: items: type: string minLength: 1 - maxItems: 16 + maxItems: 64 tag_match: $ref: '#/components/schemas/TagMatch' limit: @@ -6427,7 +6427,7 @@ components: items: type: string minLength: 1 - maxItems: 16 + maxItems: 64 tag_match: $ref: '#/components/schemas/TagMatch' limit: @@ -13476,11 +13476,12 @@ components: type: object additionalProperties: false required: [tags] + description: Exact label filter. The deployment's configured query-label limit, 16 by default, applies. properties: tags: type: array minItems: 1 - maxItems: 16 + maxItems: 64 items: {type: string, minLength: 1, maxLength: 64} match: $ref: '#/components/schemas/TagMatch' @@ -13489,12 +13490,12 @@ components: type: object additionalProperties: false required: [tags] - description: Replace all labels atomically. Empty clears the set. Labels preserve display text, use NFC then casefold for exact matching, and reject normalized duplicates, outer whitespace, and Unicode control, surrogate or unassigned characters. + description: Replace all labels atomically. Empty clears the set. The deployment's configured Artifact tag limit, 32 by default, applies. Labels preserve display text, use NFC then casefold for exact matching, and reject normalized duplicates, outer whitespace, and Unicode control, surrogate or unassigned characters. properties: tags: type: array minItems: 0 - maxItems: 32 + maxItems: 256 items: {type: string, minLength: 1, maxLength: 64} QueryArtifactTagsRequest: type: object @@ -13504,7 +13505,7 @@ components: tags: type: array minItems: 1 - maxItems: 16 + maxItems: 64 items: {type: string, minLength: 1, maxLength: 64} match: $ref: '#/components/schemas/TagMatch' @@ -13535,7 +13536,7 @@ components: tags: type: array minItems: 0 - maxItems: 32 + maxItems: 256 items: {type: string, minLength: 1, maxLength: 64} tag_digest: type: string @@ -13551,7 +13552,7 @@ components: tags: type: array minItems: 0 - maxItems: 32 + maxItems: 256 items: {type: string, minLength: 1, maxLength: 64} tag_digest: type: string @@ -13575,7 +13576,7 @@ components: tag: type: array minItems: 1 - maxItems: 16 + maxItems: 64 items: {type: string, minLength: 1, maxLength: 64} tag_match: $ref: '#/components/schemas/TagMatch' @@ -14781,7 +14782,7 @@ components: type: string minLength: 1 maxLength: 64 - maxItems: 32 + maxItems: 256 after_tags: *id005 CatalogTagResult: type: object diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 0fef647271..c344f19a91 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.6.0", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "b6709b95d7a00c9d147d958316f7ec6c4a8815d6bc6c950a19211ae015c863b7", - "rationale": "Revision v1_5_0_006 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. 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. Unpublished Server schema changes accumulate in a shared 000 revision and its registered resources. Release preparation freezes this draft as v__ after declaring the target version. Development databases are disposable; only supported released-version upgrades are promised. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for frozen release names and 000; the draft has no software_version. Historical sequence and PR-based names remain readable. Dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. 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. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. 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. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes. The 000 draft creates the private prepare diagnostic store with nullable Unicode query text included in the initial table definition. Earlier published resources and existing domain data remain unchanged. The public prepare response, public body-free Receipts, reuse and operational telemetry remain unchanged; diagnostics retain same-execution query and candidate/final text outside Source and Bootstrap storage, and capture adds no expiry or cleanup action. Schema transitions are additive and do not establish native installed-release acceptance. SQLite model-usage accounting classifies expiry during native-connection setup as an unapplied attempt, allowing the recorder to retry within its existing total write budget. No usage statement has executed at that boundary; indeterminate-commit handling and production deadlines remain unchanged. This changes no registered schema, migration resource, revision checksum, persisted row encoding, journal format, or declared upgrade support. Atomic Memory legacy recovery reads express lexical and semantic channel predicates in separate EXISTS query blocks within one scalar SQL statement. Scope and metadata eligibility, per-channel admission thresholds, invalid-vector precedence, bound-vector types and the consistent statement boundary are preserved. This changes read-query planning only: registered table layouts, projection formats, stored row encodings, migration resources, revision checksums and journal formats are unchanged. No migration or projection rebuild is required. The upgrade-required policy, registered source versions and full installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. OceanBase Experience, Atomic Memory and Topic Memory FULLTEXT initialization share the existing Topic Memory policy for transient native error 1205 during index creation. Each recovery attempt rechecks index existence before repeating only the derived-index DDL; subsequent projection refresh and capability validation still execute. Persistent conflicts and other errors remain failures, cancellation propagates, and the helper does not explicitly commit or roll back the caller or replay business writes. Native DDL transaction semantics are unchanged. Index definitions, registered table layouts, projection versions, stored row encodings, frozen migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. Vector index initialization, the upgrade-required policy, registered source versions and all installed-release acceptance profiles are unchanged; this compatibility review does not certify installed-release upgrades. SQLite profile-owned cursors close a failed native statement on the existing database worker before propagating the original SQL error. This prevents cyclic exception collection from blocking the event loop while the same connection's worker waits for another writer. Cancellation retains the existing interrupt and transaction-cleanup path; this change adds no statement replay, retry, commit, rollback or lock-wait extension. Registered table layouts, stored row encodings, projection formats, migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. The upgrade-required policy, source registrations and full installed-release acceptance matrix remain unchanged; this compatibility review does not certify installed-release upgrades. Release 1.6.0 freezes the cumulative 000 prepare-diagnostics migration as v1_6_0 after v1_5_0_006. Owned resource names, registrations and the persistence digest are synchronized; published revision identities and checksums remain unchanged. No historical query text is backfilled. This freeze preserves the upgrade-required policy and all twelve selected installed-release acceptance profiles; it does not itself certify upgrades. The Source collection revision introduced by PR #2639 after the 1.5.2 release is named v1_5_0_006 before publication. All 47 migration scripts and schema resources shipped in 1.5.2 remain byte-identical. The baseline validator is unchanged and rejects this rename against a base containing the former identity; this known CI failure is retained. Development databases and recovery plans using the former identity must be rebuilt; no runtime alias or installed-release upgrade certification is introduced. The Dashboard Topic Memory processing-status projection reads existing Scope-bound Source cursors, journal heads, targets, work budgets and retained block diagnostics without writing or repairing records or starting processing. It changes no table layout, persisted encoding, migration resource, frozen revision checksum or historical record. The upgrade-required policy and installed-release acceptance matrix remain unchanged; this review does not establish installed-release upgrade acceptance. Revision 000 adds the disposable pc_atomic_memory_alias projection on both registered source chains and backend profiles. The relation binds each merged identity to its exact selected historical revision, immediate merge target and state version, with historical text and profile-bound vector metadata. Managed databases require explicit schema maintenance; ordinary startup remains read-only, and the schema revision creates an empty alias table without backfilling existing merges. Explicit projection repair reconstructs active rows and merged aliases from authority, retains compatible stored historical vectors, prepares missing or incompatible vectors outside write transactions and rechecks authority and embedding configuration before publication. Empty projections and profile changes may regenerate vectors; nondeterministic embeddings cannot reproduce deleted original vector bytes from authority alone. Historical conversion publishes only the tables registered at its checkpoint, so aliases are not accessed before their revision. Frozen historical revision resources, required table sets and checksums remain unchanged. The current projection remains active-only; authoritative Artifact content, lifecycle encodings, identities, evidence and processing progress retain their existing semantics. Alias recall is reconciliation-only and uses the existing Scope, endpoint filtering, authorization, snapshot and version checks. Local SQLite and generated native SQL tests do not establish real seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic acceptance matrix and publication restrictions remain unchanged. Pristine unmanaged SQLite Atomic maintenance output that includes the alias projection is registered as a separate exact continuation layout. Initialization requires the complete registered schema, including the alias table definition and empty alias rows, before creating Topic recovery objects. Unknown partial layouts, modified alias objects and persisted alias evidence remain rejected before writes. The previously frozen Topic recovery resource and historical migration resources are unchanged, as are authoritative records, task DDL and installed-release acceptance requirements. Topic recovery maintenance checksums bind the relative paths and exact contents of schema.json and atomic_maintenance_sqlite_v2.json, excluding README.md. Reviewed plans detect changes to these resources. Journals using the released schema-only checksum remain resumable only with the exact frozen schema. Recovery preserves original journal and backup checksum identities and continues to validate configuration and backups. Changed frozen schemas and incompatible journals remain rejected before writes. Local SQLite recovery tests do not establish installed-release or native backend acceptance. Atomic Memory alias recall discovers successor identities and versions before loading and authorizing bodies in pages. This changes read scheduling without changing stored layouts, persisted encodings or registered migration resources. Alias lexical recall applies the same per-memory coverage threshold as direct recall to the indexed historical text. No stored layout or migration changes. PR #2728 adds a read-only `metadata` response projection to Content Sources; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. A manual Topic Memory replace links only the previous exact revision in Artifact lineage instead of copying the current revision's inherited references; existing lineage rows are left as stored, and no table, migration resource, stored encoding or upgrade support claim changes. Built-in Experience FTS search now passes its projection-level lexical admission decision to the decoder after verifying SQLite FTS-to-head projection equality and exact single-term coverage on OceanBase, and RecurrenceRepository adds the read-only verdicts_for_target query over existing pc_recurrence_observation rows using the existing revision index, signature hash and plaintext filters plus event != 'selected'; these read-only query changes alter no table layout, column, index, migration resource, frozen checksum, stored encoding or upgrade support declaration. PR #2745 adds deployment limit constants to `powercontext.limits` and a read-only discovery endpoint; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. Server startup adds best-effort, read-only guidance for widening an existing SQLite Processing capability declaration without changing its mode or bindings; incompatible configurations remain refused until the explicit offline Processing switch completes. Content Source writes enforce the configured character limit, with a 200,000-character default and a 1,000,000-character setting ceiling within the existing payload storage capacity. Neither change alters table layouts, migration resources, frozen checksums, stored encodings or the installed-release acceptance requirements." + "persistence_sha256": "aa1745b981e97d3c5117a51aeaab694cc8ae145b0e269ab0dfa4941b3610550e", + "rationale": "Revision v1_5_0_006 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. 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. Unpublished Server schema changes accumulate in a shared 000 revision and its registered resources. Release preparation freezes this draft as v__ after declaring the target version. Development databases are disposable; only supported released-version upgrades are promised. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for frozen release names and 000; the draft has no software_version. Historical sequence and PR-based names remain readable. Dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. 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. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. 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. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes. The 000 draft creates the private prepare diagnostic store with nullable Unicode query text included in the initial table definition. Earlier published resources and existing domain data remain unchanged. The public prepare response, public body-free Receipts, reuse and operational telemetry remain unchanged; diagnostics retain same-execution query and candidate/final text outside Source and Bootstrap storage, and capture adds no expiry or cleanup action. Schema transitions are additive and do not establish native installed-release acceptance. SQLite model-usage accounting classifies expiry during native-connection setup as an unapplied attempt, allowing the recorder to retry within its existing total write budget. No usage statement has executed at that boundary; indeterminate-commit handling and production deadlines remain unchanged. This changes no registered schema, migration resource, revision checksum, persisted row encoding, journal format, or declared upgrade support. Atomic Memory legacy recovery reads express lexical and semantic channel predicates in separate EXISTS query blocks within one scalar SQL statement. Scope and metadata eligibility, per-channel admission thresholds, invalid-vector precedence, bound-vector types and the consistent statement boundary are preserved. This changes read-query planning only: registered table layouts, projection formats, stored row encodings, migration resources, revision checksums and journal formats are unchanged. No migration or projection rebuild is required. The upgrade-required policy, registered source versions and full installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. OceanBase Experience, Atomic Memory and Topic Memory FULLTEXT initialization share the existing Topic Memory policy for transient native error 1205 during index creation. Each recovery attempt rechecks index existence before repeating only the derived-index DDL; subsequent projection refresh and capability validation still execute. Persistent conflicts and other errors remain failures, cancellation propagates, and the helper does not explicitly commit or roll back the caller or replay business writes. Native DDL transaction semantics are unchanged. Index definitions, registered table layouts, projection versions, stored row encodings, frozen migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. Vector index initialization, the upgrade-required policy, registered source versions and all installed-release acceptance profiles are unchanged; this compatibility review does not certify installed-release upgrades. SQLite profile-owned cursors close a failed native statement on the existing database worker before propagating the original SQL error. This prevents cyclic exception collection from blocking the event loop while the same connection's worker waits for another writer. Cancellation retains the existing interrupt and transaction-cleanup path; this change adds no statement replay, retry, commit, rollback or lock-wait extension. Registered table layouts, stored row encodings, projection formats, migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. The upgrade-required policy, source registrations and full installed-release acceptance matrix remain unchanged; this compatibility review does not certify installed-release upgrades. Release 1.6.0 freezes the cumulative 000 prepare-diagnostics migration as v1_6_0 after v1_5_0_006. Owned resource names, registrations and the persistence digest are synchronized; published revision identities and checksums remain unchanged. No historical query text is backfilled. This freeze preserves the upgrade-required policy and all twelve selected installed-release acceptance profiles; it does not itself certify upgrades. The Source collection revision introduced by PR #2639 after the 1.5.2 release is named v1_5_0_006 before publication. All 47 migration scripts and schema resources shipped in 1.5.2 remain byte-identical. The baseline validator is unchanged and rejects this rename against a base containing the former identity; this known CI failure is retained. Development databases and recovery plans using the former identity must be rebuilt; no runtime alias or installed-release upgrade certification is introduced. The Dashboard Topic Memory processing-status projection reads existing Scope-bound Source cursors, journal heads, targets, work budgets and retained block diagnostics without writing or repairing records or starting processing. It changes no table layout, persisted encoding, migration resource, frozen revision checksum or historical record. The upgrade-required policy and installed-release acceptance matrix remain unchanged; this review does not establish installed-release upgrade acceptance. Revision 000 adds the disposable pc_atomic_memory_alias projection on both registered source chains and backend profiles. The relation binds each merged identity to its exact selected historical revision, immediate merge target and state version, with historical text and profile-bound vector metadata. Managed databases require explicit schema maintenance; ordinary startup remains read-only, and the schema revision creates an empty alias table without backfilling existing merges. Explicit projection repair reconstructs active rows and merged aliases from authority, retains compatible stored historical vectors, prepares missing or incompatible vectors outside write transactions and rechecks authority and embedding configuration before publication. Empty projections and profile changes may regenerate vectors; nondeterministic embeddings cannot reproduce deleted original vector bytes from authority alone. Historical conversion publishes only the tables registered at its checkpoint, so aliases are not accessed before their revision. Frozen historical revision resources, required table sets and checksums remain unchanged. The current projection remains active-only; authoritative Artifact content, lifecycle encodings, identities, evidence and processing progress retain their existing semantics. Alias recall is reconciliation-only and uses the existing Scope, endpoint filtering, authorization, snapshot and version checks. Local SQLite and generated native SQL tests do not establish real seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic acceptance matrix and publication restrictions remain unchanged. Pristine unmanaged SQLite Atomic maintenance output that includes the alias projection is registered as a separate exact continuation layout. Initialization requires the complete registered schema, including the alias table definition and empty alias rows, before creating Topic recovery objects. Unknown partial layouts, modified alias objects and persisted alias evidence remain rejected before writes. The previously frozen Topic recovery resource and historical migration resources are unchanged, as are authoritative records, task DDL and installed-release acceptance requirements. Topic recovery maintenance checksums bind the relative paths and exact contents of schema.json and atomic_maintenance_sqlite_v2.json, excluding README.md. Reviewed plans detect changes to these resources. Journals using the released schema-only checksum remain resumable only with the exact frozen schema. Recovery preserves original journal and backup checksum identities and continues to validate configuration and backups. Changed frozen schemas and incompatible journals remain rejected before writes. Local SQLite recovery tests do not establish installed-release or native backend acceptance. Atomic Memory alias recall discovers successor identities and versions before loading and authorizing bodies in pages. This changes read scheduling without changing stored layouts, persisted encodings or registered migration resources. Alias lexical recall applies the same per-memory coverage threshold as direct recall to the indexed historical text. No stored layout or migration changes. PR #2728 adds a read-only `metadata` response projection to Content Sources; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. A manual Topic Memory replace links only the previous exact revision in Artifact lineage instead of copying the current revision's inherited references; existing lineage rows are left as stored, and no table, migration resource, stored encoding or upgrade support claim changes. Built-in Experience FTS search now passes its projection-level lexical admission decision to the decoder after verifying SQLite FTS-to-head projection equality and exact single-term coverage on OceanBase, and RecurrenceRepository adds the read-only verdicts_for_target query over existing pc_recurrence_observation rows using the existing revision index, signature hash and plaintext filters plus event != 'selected'; these read-only query changes alter no table layout, column, index, migration resource, frozen checksum, stored encoding or upgrade support declaration. PR #2745 adds deployment limit constants to `powercontext.limits` and a read-only discovery endpoint; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. Server startup adds best-effort, read-only guidance for widening an existing SQLite Processing capability declaration without changing its mode or bindings; incompatible configurations remain refused until the explicit offline Processing switch completes. Content Source writes enforce the configured character limit, with a 200,000-character default and a 1,000,000-character setting ceiling within the existing payload storage capacity. Neither change alters table layouts, migration resources, frozen checksums, stored encodings or the installed-release acceptance requirements. PR #2816 makes the per-Artifact and per-query tag limits configurable; it adds admission policy fields to the built-in runtime, widens the candidate response contract to the same ceiling, rejects over-limit proposals and revisions before they are stored, applies the query limit to embedded and plugin listings while preserving page sizes, and validates at the HTTP, plugin, Dream approval, merge and embedded-query boundaries without changing any table, payload encoding, migration or stored format." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/artifacts/atomic_memory/search.py b/src/powercontext/builtin/artifacts/atomic_memory/search.py index f9175df78a..cdb9670c43 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/search.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/search.py @@ -33,6 +33,7 @@ ) from powercontext.builtin.records import InvalidBaseAccessRequestError from powercontext.builtin.tags import TagFilter, normalize_tags +from powercontext.limits import MAX_QUERY_TAG_LABELS_CEILING if TYPE_CHECKING: from powercontext.builtin.artifacts.memory import EmbeddingProfile @@ -71,7 +72,7 @@ def validate_kind(cls, value: str) -> str: @classmethod def validate_tags(cls, value: tuple[str, ...]) -> tuple[str, ...]: try: - normalize_tags(value, maximum=16, allow_empty=False) + normalize_tags(value, maximum=MAX_QUERY_TAG_LABELS_CEILING, allow_empty=False) except InvalidBaseAccessRequestError: raise ValueError("tags must contain distinct valid labels") from None # noqa: TRY003 return value diff --git a/src/powercontext/builtin/catalog_changes/models.py b/src/powercontext/builtin/catalog_changes/models.py index 575a6b4587..4d35f8cc87 100644 --- a/src/powercontext/builtin/catalog_changes/models.py +++ b/src/powercontext/builtin/catalog_changes/models.py @@ -24,6 +24,7 @@ from powercontext.builtin.evidence.models import ResolvedEvidence from powercontext.builtin.review.models import CandidateAudit, CandidateStatus from powercontext.builtin.tags import ArtifactTagSet, TagTarget, normalize_tags +from powercontext.limits import MAX_TARGET_TAGS_CEILING from powercontext.sources import SourceRef @@ -45,21 +46,21 @@ def validate_basis(self): class TagChangeProposal(CatalogValue): - after_tags: tuple[str, ...] = Field(max_length=32) + after_tags: tuple[str, ...] = Field(max_length=MAX_TARGET_TAGS_CEILING) @field_validator("after_tags") @classmethod def valid_tags(cls, value: tuple[str, ...]) -> tuple[str, ...]: - return tuple(normalize_tags(value).values()) + return tuple(normalize_tags(value, maximum=MAX_TARGET_TAGS_CEILING).values()) class CatalogChangeProposal(TagDreamTarget, TagChangeProposal): - before_tags: tuple[str, ...] = Field(max_length=32) + before_tags: tuple[str, ...] = Field(max_length=MAX_TARGET_TAGS_CEILING) @field_validator("before_tags") @classmethod def valid_before_tags(cls, value: tuple[str, ...]) -> tuple[str, ...]: - return tuple(normalize_tags(value).values()) + return tuple(normalize_tags(value, maximum=MAX_TARGET_TAGS_CEILING).values()) class CatalogChangeCandidate(CatalogValue): diff --git a/src/powercontext/builtin/catalog_changes/service.py b/src/powercontext/builtin/catalog_changes/service.py index a463535a4a..d9eee7eb40 100644 --- a/src/powercontext/builtin/catalog_changes/service.py +++ b/src/powercontext/builtin/catalog_changes/service.py @@ -48,6 +48,7 @@ ) from powercontext.builtin.review.models import CandidateAudit from powercontext.builtin.tags import ArtifactTagSet, TagPreconditionError +from powercontext.limits import MAX_TARGET_TAGS from powercontext.sources import SourceRef @@ -63,6 +64,7 @@ def __init__( tags: RelationalTagService | None = None, connection: AsyncConnection | None = None, authorization_context: Callable[[], AbstractAsyncContextManager[None]] = nullcontext, + tag_limit: int = MAX_TARGET_TAGS, ) -> None: self._database = database self._scope_id = scope_id @@ -73,6 +75,7 @@ def __init__( self._repository = CatalogCandidateRepository() self._bound_connection = connection self._authorization_context = authorization_context + self._tag_limit = tag_limit self._authorize_many = None self.authorize_action: Callable[[str, str, TagDreamTarget], Awaitable[None]] | None = None @@ -156,6 +159,13 @@ async def inspect_target(self, target: TagDreamTarget) -> ArtifactTagSet: raise TagPreconditionError return current + def _require_after_tag_limit(self, proposal: CatalogChangeProposal) -> None: + if len(proposal.after_tags) > self._tag_limit: + raise InvalidCandidateError( + "after_tags", + f"the candidate exceeds the deployment's {self._tag_limit}-tag Artifact limit", + ) + async def propose( self, proposal: CatalogChangeProposal, @@ -167,6 +177,7 @@ async def propose( candidate_id: str | None = None, audit: CandidateAudit | None = None, ) -> CatalogChangeCandidate: + self._require_after_tag_limit(proposal) candidate = CatalogChangeCandidate( candidate_id=candidate_id or self._id_factory("candidate"), version=1, @@ -244,6 +255,7 @@ async def revise( if self.authorize_action is not None: await self.authorize_action(self._scope_id, "revise", preview.proposal) expected = CatalogChangeProposal.model_validate({**preview.proposal.model_dump(), "after_tags": after_tags}) + self._require_after_tag_limit(expected) if proposal is not None and proposal != expected: raise InvalidCandidateError("proposal", "Tag revision cannot change its original target or baseline") proposal = expected @@ -299,6 +311,7 @@ async def _approve_once(self, candidate_id: str, expected_version: int) -> Catal if current != preview: raise CandidateConflictError(candidate_id, expected_version, current.version) await self._validate_audit(connection, current) + self._require_after_tag_limit(current.proposal) result = await self._tags.replace_in_transaction( connection, self._scope_id, diff --git a/src/powercontext/builtin/persistence/records.py b/src/powercontext/builtin/persistence/records.py index 091aa21272..f2c2a82043 100644 --- a/src/powercontext/builtin/persistence/records.py +++ b/src/powercontext/builtin/persistence/records.py @@ -97,8 +97,16 @@ ContentSourceInternal, ContentSourceTarget, ) -from powercontext.builtin.tags import ArtifactTagSet, TagFilter, TagQuery, TagQueryPage, TagTarget +from powercontext.builtin.tags import ( + ArtifactTagSet, + TagFilter, + TagQuery, + TagQueryPage, + TagTarget, + require_tag_query_limit, +) from powercontext.errors import RevisionConflictError +from powercontext.limits import MAX_QUERY_TAG_LABELS from powercontext.sources import SourceMaterialization, SourceObservation, SourceRef Clock = Callable[[], datetime] @@ -137,6 +145,7 @@ def __init__( processing_pending: ArtifactProcessingPendingRepository | None = None, source_processing_bindings: tuple[str, ...] = (), tags: RelationalTagService | None = None, + tag_query_limit: int = MAX_QUERY_TAG_LABELS, atomic_memory_tag_hook=None, atomic_memory_tag_authorizer=None, topic_memory_list_reader: ArtifactListReader | None = None, @@ -156,6 +165,7 @@ def __init__( self._processing_pending = processing_pending self._source_processing_bindings = source_processing_bindings self._topic_memory_list_reader = topic_memory_list_reader + self._tag_query_limit = tag_query_limit self._artifact_handles = ArtifactHandleRepository(database) self._tags = tags or RelationalTagService( database, @@ -636,6 +646,8 @@ async def query_artifacts( ) -> ArtifactRecordPage: repository = self._read_repository(family) _require_limit(limit) + if tag_filter is not None: + require_tag_query_limit(tag_filter.tags, self._tag_query_limit) reader = self._topic_memory_list_reader if reader is not None and family == reader.family: return await reader.query( diff --git a/src/powercontext/builtin/persistence/tags.py b/src/powercontext/builtin/persistence/tags.py index e0a6eebf41..4e96da8e9e 100644 --- a/src/powercontext/builtin/persistence/tags.py +++ b/src/powercontext/builtin/persistence/tags.py @@ -38,6 +38,7 @@ from powercontext.builtin.records import ( BaseValueNotFoundError, CursorExpiredError, + InvalidBaseAccessRequestError, InvalidCursorError, ) from powercontext.builtin.tags import ( @@ -50,8 +51,10 @@ TagQueryPage, TagTarget, normalize_tags, + require_tag_query_limit, tag_set, ) +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS, MAX_TARGET_TAGS_CEILING def tag_predicate( @@ -120,6 +123,8 @@ def __init__( cursor_ttl_seconds: int = 3600, projection_hook=None, atomic_write_authorizer=None, + tag_limit: int = MAX_TARGET_TAGS, + tag_query_limit: int = MAX_QUERY_TAG_LABELS, ) -> None: self._database = database self._artifacts = artifacts @@ -128,6 +133,8 @@ def __init__( self._cursor_ttl = cursor_ttl_seconds self._projection_hook = projection_hook self._atomic_write_authorizer = atomic_write_authorizer + self._tag_limit = tag_limit + self._tag_query_limit = tag_query_limit async def get(self, scope_id: str, target: TagTarget) -> ArtifactTagSet: async with self._database.transaction() as connection: @@ -172,7 +179,11 @@ async def replace_in_transaction( expected_etag: str, execution_context=None, ) -> ArtifactTagSet: - desired = normalize_tags(tags) + desired = normalize_tags(tags, maximum=MAX_TARGET_TAGS_CEILING) + if len(desired) > self._tag_limit: + raise InvalidBaseAccessRequestError( + "tags", f"must contain at most the deployment's {self._tag_limit}-label Artifact limit" + ) await self.lock_target(connection, scope_id, target) await self._target_reference(connection, scope_id, target) if target.family == "atomic-memory" and self._atomic_write_authorizer is not None: @@ -181,7 +192,7 @@ async def replace_in_transaction( current = tag_set(scope_id, target, latest.tags) if not hmac.compare_digest(expected_etag.encode("utf-8"), current.etag.encode("utf-8")): raise TagPreconditionError - previous = normalize_tags(current.tags) + previous = normalize_tags(current.tags, maximum=MAX_TARGET_TAGS_CEILING) identity = _identity(scope_id, target) removed = previous.keys() - desired.keys() if removed: @@ -211,6 +222,7 @@ async def replace_in_transaction( return tag_set(scope_id, target, tags) async def query(self, scope_id: str, query: TagQuery, *, caller: str = "runtime") -> TagQueryPage: + require_tag_query_limit(query.tags, self._tag_query_limit) binding = sha256( rfc8785.dumps({ "scope_id": scope_id, diff --git a/src/powercontext/builtin/plugins/executor.py b/src/powercontext/builtin/plugins/executor.py index d17472a2ed..78c19a9f5d 100644 --- a/src/powercontext/builtin/plugins/executor.py +++ b/src/powercontext/builtin/plugins/executor.py @@ -42,6 +42,7 @@ ) from powercontext.builtin.runtime.processing_execution import InvocationAlreadyHandled, ScopeInvocation from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY, SourceCursor +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS from powercontext.plugins import ArtifactPlugin, GenerateRequest, GenerationSource, PluginContext logger = logging.getLogger(__name__) @@ -59,6 +60,8 @@ class PluginWorkerSpec: storage_root: str | None = None # The loaded plugins' Source inputs, for Workers that write Sources: (binding, Scopes, Source types). source_bindings: tuple[tuple[str, tuple[str, ...] | None, tuple[str, ...]], ...] = () + tag_max_per_artifact: int = MAX_TARGET_TAGS + tag_max_query_labels: int = MAX_QUERY_TAG_LABELS def run_plugin_worker( @@ -180,6 +183,8 @@ async def complete(connection) -> None: complete=complete, transaction_timeout_seconds=generate.transaction_timeout_seconds, security=security, + tag_limit=spec.tag_max_per_artifact, + tag_query_limit=spec.tag_max_query_labels, ) call = bool(window) or inputs is None if call: diff --git a/src/powercontext/builtin/plugins/host.py b/src/powercontext/builtin/plugins/host.py index 9405837ebd..e2c6efa3af 100644 --- a/src/powercontext/builtin/plugins/host.py +++ b/src/powercontext/builtin/plugins/host.py @@ -312,6 +312,8 @@ async def authorize(connection: Any) -> None: begin=authorize, transaction_timeout_seconds=spec.transaction_timeout_seconds, security=security, + tag_limit=self.spec.tag_max_per_artifact, + tag_query_limit=self.spec.tag_max_query_labels, ) def _no_caller(self) -> None: @@ -461,6 +463,8 @@ def _writer(self, scope_id: str, *, change: UserChange | None = None) -> PluginA context=_CURRENT.get().context, change=change, caller_scoped=True, + tag_limit=self.spec.tag_max_per_artifact, + tag_query_limit=self.spec.tag_max_query_labels, ) async def _authorize(self, scope_id: str, action: str, artifact_id: str | None) -> None: diff --git a/src/powercontext/builtin/plugins/host_protocol.py b/src/powercontext/builtin/plugins/host_protocol.py index 7e1320f880..8af24356a8 100644 --- a/src/powercontext/builtin/plugins/host_protocol.py +++ b/src/powercontext/builtin/plugins/host_protocol.py @@ -23,6 +23,8 @@ from dataclasses import dataclass, field from typing import Any, Literal +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS + HostMethod = Literal[ "create_artifact", "update_artifact", @@ -65,6 +67,8 @@ class PluginHostSpec: storage_root: str | None = None # The background identity upgrade writes act as; None when access is disabled or none is configured. upgrade_security: dict[str, Any] | None = None + tag_max_per_artifact: int = MAX_TARGET_TAGS + tag_max_query_labels: int = MAX_QUERY_TAG_LABELS @dataclass(frozen=True) diff --git a/src/powercontext/builtin/plugins/writer.py b/src/powercontext/builtin/plugins/writer.py index eb933c9f98..279936457a 100644 --- a/src/powercontext/builtin/plugins/writer.py +++ b/src/powercontext/builtin/plugins/writer.py @@ -59,10 +59,11 @@ plugin_artifact_repository, record_revision_metadata, ) -from powercontext.builtin.records import ArtifactRevisionPreconditionError +from powercontext.builtin.records import ArtifactRevisionPreconditionError, InvalidBaseAccessRequestError from powercontext.builtin.runtime.artifact_merge import ArtifactMergeAccess, merge_artifact_tags from powercontext.builtin.sources.content import ContentSource, ContentSourceInternal, ContentSourceTarget from powercontext.builtin.tags import normalize_tags +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS from powercontext.plugins import ArtifactChange, ArtifactPage, ArtifactSnapshot, LifecycleState, UndoMergePreview from powercontext.sources import SourceMaterialization, SourceRef @@ -232,7 +233,12 @@ async def list( if cursor is not None: statement = statement.where(heads.c.artifact_id > cursor) if tags: - keys = tuple(normalize_tags(tuple(tags), allow_empty=False)) + tag_bound = owner.tag_query_limit + if len(tuple(tags)) > tag_bound: + raise InvalidBaseAccessRequestError( + "tags", f"must contain at most the deployment's {tag_bound}-label query limit" + ) + keys = tuple(normalize_tags(tuple(tags), allow_empty=False, maximum=tag_bound)) tagged = ( select(ARTIFACT_TAGS_TABLE.c.artifact_id) .where( @@ -664,7 +670,7 @@ async def set_tags(self, artifact_id: str, tags: Sequence[str], /) -> tuple[str, ref = (await self._require(artifact_id)).artifact.as_ref() await self._authorize_write(ref) await owner.artifacts.lock_heads(self._connection, owner.scope_id, (ref,)) - desired = normalize_tags(tuple(tags)) + desired = normalize_tags(tuple(tags), maximum=owner.tag_limit) await self._connection.execute( delete(ARTIFACT_TAGS_TABLE).where(*_tag_identity(owner.scope_id, owner.family, artifact_id)) ) @@ -712,6 +718,8 @@ def __init__( context: Any = None, change: UserChange | None = None, caller_scoped: bool = False, + tag_limit: int = MAX_TARGET_TAGS, + tag_query_limit: int = MAX_QUERY_TAG_LABELS, ) -> None: """``caller_scoped`` writers act as ``context``'s caller under the shared Artifact access policy.""" @@ -724,11 +732,14 @@ def __init__( self._timeout = transaction_timeout_seconds self.context = context self.change = change + self.tag_limit = tag_limit + self.tag_query_limit = tag_query_limit self.service = plugin_merge_service( family, ArtifactMergeAccess(family) if caller_scoped or change is not None else _Security(family, security), sources, metadata=metadata, + tag_limit=tag_limit, ) self.artifacts = self.service.artifacts self.states = ArtifactGovernanceRepository() @@ -791,7 +802,12 @@ async def transaction(self): def plugin_merge_service( - family: str, security: Any, sources: SourceRepository, *, metadata: bytes | None = None + family: str, + security: Any, + sources: SourceRepository, + *, + metadata: bytes | None = None, + tag_limit: int = MAX_TARGET_TAGS, ) -> ArtifactMergeService: """The shared governance engine for one plugin family; ``security`` decides who may change it. @@ -804,7 +820,7 @@ def plugin_merge_service( artifacts=plugin_artifact_repository(family, sources), adapter=_Adapter(family, metadata), security=security, - merge_tags=partial(merge_artifact_tags, family=family), + merge_tags=partial(merge_artifact_tags, family=family, maximum=tag_limit), sources=sources, ) diff --git a/src/powercontext/builtin/portability/bundle.py b/src/powercontext/builtin/portability/bundle.py index 47d4916e3b..b7c413eb43 100644 --- a/src/powercontext/builtin/portability/bundle.py +++ b/src/powercontext/builtin/portability/bundle.py @@ -125,6 +125,7 @@ ) from powercontext.builtin.tags import normalize_tags from powercontext.errors import SourceError +from powercontext.limits import MAX_TARGET_TAGS, MAX_TARGET_TAGS_CEILING from powercontext.sources import SourceDefinitionManifest, SourceLocator, SourceObservation, SourceRef from powercontext.sources.evidence import MemoryEvidenceDeclaration, SourceEvidence @@ -543,8 +544,10 @@ def __init__( artifact_content_decoder: Callable[[Mapping[str, Any]], object] | None = None, candidate_decoder: Callable[[Mapping[str, Any]], object] | None = None, source_decoder: Callable[[Mapping[str, Any]], object] | None = None, + tag_limit: int = MAX_TARGET_TAGS, ) -> None: self._database = database + self._tag_limit = tag_limit self._projection_rebuilder = projection_rebuilder self._artifact_content_decoder = artifact_content_decoder self._candidate_decoder = candidate_decoder @@ -626,7 +629,9 @@ async def export( # Reject missing dependencies and size-limit breaches # without replacing a previous usable backup at the destination. _parse_bundle(archive_path) - with _validate_dependencies(archive_path, candidate_decoder=self._candidate_decoder): + with _validate_dependencies( + archive_path, candidate_decoder=self._candidate_decoder, maximum=MAX_TARGET_TAGS_CEILING + ): archive_path.replace(output) return BundleReceipt(bundle_id=bundle_id, record_count=count, total_digest=digest) finally: @@ -650,7 +655,7 @@ async def validate( """Verify bundle integrity, dependencies, and optional adapter support.""" inspection = _parse_bundle(source, progress=progress, phase="validate") - with _validate_dependencies(source, candidate_decoder=self._candidate_decoder) as ( + with _validate_dependencies(source, candidate_decoder=self._candidate_decoder, maximum=self._tag_limit) as ( required_sources, required_families, index, @@ -894,7 +899,7 @@ async def flush() -> None: if ( conflicts == 0 and ARTIFACT_TAGS_TABLE.name in existing_tables - and not await _validate_target_tag_sets(connection, dependency_index) + and not await _validate_target_tag_sets(connection, dependency_index, maximum=self._tag_limit) ): conflicts += 1 return already_present, conflicts @@ -1796,7 +1801,7 @@ def bytes_values(*fields: str, nullable: tuple[str, ...] = ()) -> None: if identity["target_type"] == "memory_entry" and identity["family"] != "memory": raise BundleFormatError("artifact tag has invalid target") try: - normalized = normalize_tags((payload["tag"],)) + normalized = normalize_tags((payload["tag"],), maximum=MAX_TARGET_TAGS_CEILING) except InvalidBaseAccessRequestError as error: raise BundleFormatError("artifact tag has invalid label") from error if identity["tag_key"] not in normalized: @@ -1963,7 +1968,11 @@ def _validate_safe_value(value: object, key: str | None = None, *, host_paths: b @contextmanager def _validate_dependencies( - source: Path, /, *, candidate_decoder: Callable[[Mapping[str, Any]], object] | None = None + source: Path, + /, + *, + candidate_decoder: Callable[[Mapping[str, Any]], object] | None = None, + maximum: int = MAX_TARGET_TAGS, ) -> Iterator[tuple[set[str], set[str], sqlite3.Connection]]: """Validate dependencies with disk-backed identities and bounded metadata.""" @@ -1993,7 +2002,7 @@ def contains(record_type: str, identity: Mapping[str, object]) -> bool: required_sources.add(str(record.identity["source_type"])) required_families.update(_required_artifact_families((record,))) _validate_publication_chains(index) - _validate_tag_sets(index) + _validate_tag_sets(index, maximum=maximum) yield required_sources, required_families, index @@ -2075,7 +2084,7 @@ def _index_tag_set(index: sqlite3.Connection, record: _Record, /) -> None: ) -def _validate_tag_sets(index: sqlite3.Connection, /) -> None: +def _validate_tag_sets(index: sqlite3.Connection, /, *, maximum: int = MAX_TARGET_TAGS) -> None: current: str | None = None labels: list[str] = [] for target, label in index.execute("SELECT target, label FROM tag_labels ORDER BY target, tag_key"): @@ -2084,12 +2093,14 @@ def _validate_tag_sets(index: sqlite3.Connection, /) -> None: labels.clear() labels.append(label) try: - normalize_tags(tuple(labels)) + normalize_tags(tuple(labels), maximum=maximum) except InvalidBaseAccessRequestError as error: raise BundleFormatError("artifact tag set has invalid labels") from error -async def _validate_target_tag_sets(connection: AsyncConnection, index: sqlite3.Connection, /) -> bool: +async def _validate_target_tag_sets( + connection: AsyncConnection, index: sqlite3.Connection, /, *, maximum: int = MAX_TARGET_TAGS +) -> bool: table = ARTIFACT_TAGS_TABLE fields = tuple(field for field in _SPECS["artifact_tag"].identity if field != "tag_key") pending = index.execute( @@ -2114,7 +2125,7 @@ async def _validate_target_tag_sets(connection: AsyncConnection, index: sqlite3. return False _index_tag_set(index, record) try: - _validate_tag_sets(index) + _validate_tag_sets(index, maximum=maximum) except BundleFormatError: return False return True diff --git a/src/powercontext/builtin/runtime/artifact_merge.py b/src/powercontext/builtin/runtime/artifact_merge.py index 81d970ccd9..03f9bebd87 100644 --- a/src/powercontext/builtin/runtime/artifact_merge.py +++ b/src/powercontext/builtin/runtime/artifact_merge.py @@ -342,6 +342,7 @@ async def merge_artifact_tags( input_ids: tuple[str, ...], *, family: str, + maximum: int = MAX_TARGET_TAGS, ) -> None: """Assign the result a bounded, deterministic selection from its inputs' tags. @@ -369,8 +370,8 @@ async def merge_artifact_tags( labels.setdefault(key, str(row.tag)) carriers[key] += 1 # Independent of input order, so retries and replays of the same merge assign the same tags. - retained = sorted(labels, key=lambda key: (-carriers[key], key.encode("utf-8")))[:MAX_TARGET_TAGS] - for key, label in normalize_tags(tuple(labels[key] for key in retained)).items(): + retained = sorted(labels, key=lambda key: (-carriers[key], key.encode("utf-8")))[:maximum] + for key, label in normalize_tags(tuple(labels[key] for key in retained), maximum=maximum).items(): await connection.execute( insert(ARTIFACT_TAGS_TABLE).values( scope_id=scope_id, diff --git a/src/powercontext/builtin/runtime/atomic_memory.py b/src/powercontext/builtin/runtime/atomic_memory.py index 4898feca74..c244b04d14 100644 --- a/src/powercontext/builtin/runtime/atomic_memory.py +++ b/src/powercontext/builtin/runtime/atomic_memory.py @@ -115,6 +115,7 @@ require_source_eligible, ) from powercontext.builtin.tags import TagFilter +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS logger = logging.getLogger(__name__) @@ -367,6 +368,8 @@ def __init__( rerank_candidate_limit: int = 30, recall_channel_weights: RecallChannelWeights = DEFAULT_RECALL_CHANNEL_WEIGHTS, prompt_context_factory=None, + tag_limit: int = MAX_TARGET_TAGS, + tag_query_limit: int = MAX_QUERY_TAG_LABELS, ) -> None: if reranker is not None and not getattr(reranker, "supports_atomic_memory", False): raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "Atomic text candidate contract") @@ -374,6 +377,8 @@ def __init__( self.rerank_candidate_limit = rerank_candidate_limit self.recall_channel_weights = recall_channel_weights self.prompt_context_factory = prompt_context_factory + self.tag_limit = tag_limit + self.tag_query_limit = tag_query_limit self.database = database self.artifacts = artifacts self.index = index @@ -400,7 +405,9 @@ def for_scope(self, scope_id: str) -> ScopedAtomicMemory: return ScopedAtomicMemory(self, scope_id) async def merge_tags(self, connection, scope_id: str, result_id: str, input_ids: tuple[str, ...]) -> None: - await merge_artifact_tags(connection, scope_id, result_id, input_ids, family=self.security.family) + await merge_artifact_tags( + connection, scope_id, result_id, input_ids, family=self.security.family, maximum=self.tag_limit + ) class ScopedAtomicMemory: @@ -408,6 +415,15 @@ def __init__(self, application: AtomicMemoryApplication, scope_id: str) -> None: self.application = application self.scope_id = scope_id + def _require_tag_query_limit(self, tag_filter: TagFilter | None) -> None: + if tag_filter is None: + return + limit = self.application.tag_query_limit + if len(tag_filter.tags) > limit: + raise InvalidBaseAccessRequestError( + "tags", f"must contain at most the deployment's {limit}-label query limit" + ) + @asynccontextmanager async def _read(self, context, *, pin: bool = True): # Local policy shares the business snapshot; external providers keep their boundary. @@ -626,6 +642,7 @@ async def manifest( context=None, ) -> RecallManifestPage: """Read only current metadata; never assemble content or infer summaries.""" + self._require_tag_query_limit(tag_filter) _validate_limit(limit) if kind is not None: AtomicMemoryContent(kind=kind, text="validation", description="validation") @@ -727,6 +744,7 @@ def list_query( ): """Build the canonical browse window; the caller owns its read transaction and PEP.""" _validate_limit(limit) + self._require_tag_query_limit(tag_filter) if not states or len(set(states)) != len(states): raise InvalidBaseAccessRequestError("states", "must contain distinct lifecycle values") states = tuple(AtomicMemoryStateValue(state).value for state in states) @@ -836,6 +854,7 @@ async def list( cursor: str | None = None, context=None, ) -> AtomicMemoryPage: + self._require_tag_query_limit(tag_filter) async with self._read(context) as connection: statement, bound, after = self.list_query( connection, @@ -881,6 +900,7 @@ async def search( # noqa: C901 query, mode, limit = artifact_request.query, plan.mode, artifact_request.limit kind, tag_filter = artifact_request.filters.kind, artifact_request.filters.as_tag_filter() admission = artifact_request.admission.as_floor() + self._require_tag_query_limit(tag_filter) _validate_limit(limit) normalize_query(query) if mode not in {"auto", "text", "vector", "hybrid"}: diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index 9e8bc64b2f..1874c56a5b 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -512,7 +512,7 @@ def _artifact_merge_application(contexts: RelationalContexts, config: RuntimeCon artifacts=contexts.repositories.artifacts, adapter=ExperienceMergeAdapter(contexts.experience_index), security=ArtifactMergeAccess("experience"), - merge_tags=partial(merge_artifact_tags, family="experience"), + merge_tags=partial(merge_artifact_tags, family="experience", maximum=config.tag_max_per_artifact), preview_signer=signer, ) return ArtifactMergeApplication( @@ -1335,6 +1335,8 @@ async def open_builtin_contexts( # noqa: C901 -- Backend admission and resource memory_write_gate=memory_write_gate, decision_observation_retention_days=config.runtime.decision_observation_retention_days, memory_rerank_candidate_limit=config.runtime.memory_rerank_candidate_limit, + tag_max_per_artifact=config.runtime.tag_max_per_artifact, + tag_max_query_labels=config.runtime.tag_max_query_labels, recall_channel_weights=config.runtime.recall_channel_weights, prompt_registry=prompt_registry, prompt_demonstrators=prompt_demonstrators, @@ -1419,6 +1421,8 @@ async def open_builtin_contexts( # noqa: C901 -- Backend admission and resource memory_reranker=memory_reranker, decision_model=decision_model, memory_rerank_candidate_limit=config.runtime.memory_rerank_candidate_limit, + tag_max_per_artifact=config.runtime.tag_max_per_artifact, + tag_max_query_labels=config.runtime.tag_max_query_labels, recall_channel_weights=config.runtime.recall_channel_weights, prompt_registry=prompt_registry, prompt_demonstrators=prompt_demonstrators, diff --git a/src/powercontext/builtin/runtime/config.py b/src/powercontext/builtin/runtime/config.py index 2a2f8fd6ca..f6ad731a3b 100644 --- a/src/powercontext/builtin/runtime/config.py +++ b/src/powercontext/builtin/runtime/config.py @@ -52,6 +52,13 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime._scope_cache import DEFAULT_SCOPE_CACHE_SIZE from powercontext.builtin.runtime.decision_policy import DecisionPolicyMode, DecisionPrivacyBoundary +from powercontext.limits import ( + MAX_QUERY_TAG_LABELS, + MAX_QUERY_TAG_LABELS_CEILING, + MAX_TARGET_TAGS, + MAX_TARGET_TAGS_CEILING, + TagLimits, +) _HTTP_FIELD_NAME_PATTERN = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") InputEncodingOperation = Literal[ @@ -168,6 +175,14 @@ def reject_boolean_worker_quota(cls, value: Any) -> Any: memory_compaction_enabled: bool = False memory_compaction_min_tombstone_revisions: int = Field(default=10, ge=0) memory_max_history_revisions: int = Field(default=100, ge=1) + tag_max_per_artifact: int = Field(default=MAX_TARGET_TAGS, ge=1, le=MAX_TARGET_TAGS_CEILING) + tag_max_query_labels: int = Field(default=MAX_QUERY_TAG_LABELS, ge=1, le=MAX_QUERY_TAG_LABELS_CEILING) + + @property + def tag_limits(self) -> TagLimits: + """Return the deployment's effective tag admission policy.""" + + return TagLimits(max_per_artifact=self.tag_max_per_artifact, max_query_labels=self.tag_max_query_labels) @model_validator(mode="after") def validate_memory_capacity_order(self) -> RuntimeConfig: diff --git a/src/powercontext/builtin/runtime/relational.py b/src/powercontext/builtin/runtime/relational.py index 620f27d074..d36b689f1d 100644 --- a/src/powercontext/builtin/runtime/relational.py +++ b/src/powercontext/builtin/runtime/relational.py @@ -254,6 +254,7 @@ SourceDefinitionNotFoundError, SourceNotFoundError, ) +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS from powercontext.sources import ( TEXT_EVIDENCE_PROJECTION_KEY, ConnectorBinding, @@ -517,6 +518,8 @@ def __init__( memory_write_gate: MemoryWriteGate | None = None, decision_observation_retention_days: int | None = None, memory_rerank_candidate_limit: int = 30, + tag_max_per_artifact: int = MAX_TARGET_TAGS, + tag_max_query_labels: int = MAX_QUERY_TAG_LABELS, recall_channel_weights: RecallChannelWeights = DEFAULT_RECALL_CHANNEL_WEIGHTS, id_factory: IdFactory | None = None, handoff_artifact_id: str = "handoff", @@ -534,6 +537,8 @@ def __init__( model_usage_flush_timeout_seconds: float = 0.5, ) -> None: self.database = database + self._tag_max_per_artifact = tag_max_per_artifact + self._tag_max_query_labels = tag_max_query_labels self.scopes = ScopeApplication(database, cursor_secret=cursor_secret) self.source_registry = source_registry or BUILTIN_SOURCE_REGISTRY self.topic_memory_index = NoTopicMemoryIndex() if topic_memory_index is None else topic_memory_index @@ -581,6 +586,8 @@ def __init__( id_factory=id_factory, preview_signer=preview_signer, restore_retry_budget=atomic_memory_restore_retry_budget, + tag_limit=tag_max_per_artifact, + tag_query_limit=tag_max_query_labels, ) topic_memory_repository = TopicMemoryRepository( artifacts=artifact_repository, @@ -615,6 +622,7 @@ def __init__( artifact_content_decoder=artifact_repository.decode_content, candidate_decoder=self.repositories.candidates.decode_candidate, source_decoder=source_repository.decode_source, + tag_limit=self._tag_max_per_artifact, ) self.list_skills = SkillArtifactSearcher(database, self.repositories.artifacts, self.experience_index) self._model_usage = _ModelUsageRecorder( @@ -703,6 +711,8 @@ def __init__( cursor_secret=cursor_secret, projection_hook=atomic_memory_index.refresh_tags, atomic_write_authorizer=self._authorize_atomic_tag_write, + tag_limit=self._tag_max_per_artifact, + tag_query_limit=self._tag_max_query_labels, ) self.records = RelationalRecordService( database, @@ -714,6 +724,7 @@ def __init__( processing_pending=self.repositories.processing_pending, source_processing_bindings=(TOPIC_MEMORY_SOURCE_WINDOW_BINDING,), tags=self.tags, + tag_query_limit=self._tag_max_query_labels, topic_memory_list_reader=TopicMemoryArtifactListReader( database=database, artifacts=artifact_repository, @@ -744,6 +755,7 @@ def __init__( self._memory_reranker = memory_reranker self._decision_model = decision_model self._memory_rerank_candidate_limit = memory_rerank_candidate_limit + self._tag_max_per_artifact = tag_max_per_artifact self._handoff_artifact_id = handoff_artifact_id self._tracing = tracing self._scope_states: dict[str, _ScopeState] = {} @@ -797,6 +809,7 @@ def catalog_changes(self, scope_id: str, connection: AsyncConnection | None = No id_factory=services.id_factory, tags=self.tags, connection=connection, + tag_limit=self._tag_max_per_artifact, ) def dream( diff --git a/src/powercontext/builtin/tags.py b/src/powercontext/builtin/tags.py index 846b198c05..9280eda382 100644 --- a/src/powercontext/builtin/tags.py +++ b/src/powercontext/builtin/tags.py @@ -28,6 +28,11 @@ from powercontext.artifacts import ArtifactRef from powercontext.builtin.records import BaseAccessError, BaseArtifactFamily, InvalidBaseAccessRequestError +from powercontext.limits import ( + MAX_QUERY_TAG_LABELS_CEILING, + MAX_TARGET_TAGS, + MAX_TARGET_TAGS_CEILING, +) TaggableArtifactFamily = str @@ -48,7 +53,6 @@ def _require_taggable(family: str) -> str: TagMatch = Literal["all", "any"] TagTargetType = Literal["artifact"] -MAX_TARGET_TAGS = 32 class _TagModel(BaseModel): @@ -71,6 +75,13 @@ def validate_family(cls, value: str) -> str: TagTarget = ArtifactTagTarget +def require_tag_query_limit(tags: tuple[str, ...], limit: int) -> None: + """Reject an embedded query whose label count exceeds the deployment limit.""" + + if len(tags) > limit: + raise InvalidBaseAccessRequestError("tags", f"must contain at most the deployment's {limit}-label query limit") + + def normalize_tags( tags: tuple[str, ...], *, maximum: int = MAX_TARGET_TAGS, allow_empty: bool = True ) -> dict[str, str]: @@ -106,12 +117,12 @@ class TagFilter(_TagModel): @field_validator("tags") @classmethod def validate_tags(cls, value: tuple[str, ...]) -> tuple[str, ...]: - normalize_tags(value, maximum=16, allow_empty=False) + normalize_tags(value, maximum=MAX_QUERY_TAG_LABELS_CEILING, allow_empty=False) return value @property def keys(self) -> tuple[str, ...]: - return tuple(normalize_tags(self.tags, maximum=16, allow_empty=False)) + return tuple(normalize_tags(self.tags, maximum=MAX_QUERY_TAG_LABELS_CEILING, allow_empty=False)) class ArtifactTagSet(_TagModel): @@ -129,7 +140,7 @@ def etag(self) -> str: def tag_set(scope_id: str, target: TagTarget, tags: tuple[str, ...]) -> ArtifactTagSet: - ordered = tuple(normalize_tags(tags).values()) + ordered = tuple(normalize_tags(tags, maximum=MAX_TARGET_TAGS_CEILING).values()) digest = "sha256:" + sha256(rfc8785.dumps({"tags": list(ordered)})).hexdigest() return ArtifactTagSet(scope_id=scope_id, target=target, tags=ordered, tag_digest=digest) diff --git a/src/powercontext/cli/archive.py b/src/powercontext/cli/archive.py index 0e604f0aa0..87712d7026 100644 --- a/src/powercontext/cli/archive.py +++ b/src/powercontext/cli/archive.py @@ -53,6 +53,7 @@ from powercontext.builtin.runtime import BuiltinConfig, open_builtin_runtime from powercontext.builtin.runtime.relational import BUILTIN_ARTIFACT_TYPES, BUILTIN_CANDIDATE_PROPOSAL_TYPES from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY +from powercontext.limits import MAX_TARGET_TAGS from powercontext.server.configuration import server_settings_context HELP_OPTION_NAMES = ("-h", "--help") @@ -162,24 +163,36 @@ async def _validate_only(source: Path, /, *, env_file: Path | None) -> BundleVal existing = database.is_persistent and await asyncio.to_thread(_database_file_exists, database.url) if existing: async with SQLiteProfile.open_readonly(database) as profile: - return await _validate_with_database(profile.database, source, settings.plugins_dir) + return await _validate_with_database( + profile.database, source, settings.plugins_dir, settings.runtime.tag_max_per_artifact + ) engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=database.echo, hide_parameters=True) validation_database = AsyncDatabase.own(engine, shared_connection=True) try: - return await _validate_with_database(validation_database, source, settings.plugins_dir) + return await _validate_with_database( + validation_database, source, settings.plugins_dir, settings.runtime.tag_max_per_artifact + ) finally: await validation_database.close() if isinstance(database, OceanBaseConfig): async with OceanBaseProfile.open(database, tables=()) as profile: - return await _validate_with_database(profile.database, source, settings.plugins_dir) + return await _validate_with_database( + profile.database, source, settings.plugins_dir, settings.runtime.tag_max_per_artifact + ) if isinstance(database, SeekDBConfig): async with SeekDBProfile.open(database, tables=()) as profile: - return await _validate_with_database(profile.database, source, settings.plugins_dir) + return await _validate_with_database( + profile.database, source, settings.plugins_dir, settings.runtime.tag_max_per_artifact + ) assert_never(database) async def _validate_with_database( - database: AsyncDatabase, source: Path, plugins_dir: Path | None = None, / + database: AsyncDatabase, + source: Path, + plugins_dir: Path | None = None, + tag_limit: int = MAX_TARGET_TAGS, + /, ) -> BundleValidation: async def projection_capability(_scopes: tuple[str, ...], /) -> None: return None @@ -193,6 +206,7 @@ async def projection_capability(_scopes: tuple[str, ...], /) -> None: artifact_content_decoder=artifacts.decode_content, candidate_decoder=CandidateRepository(BUILTIN_CANDIDATE_PROPOSAL_TYPES).decode_candidate, source_decoder=SourceRepository(BUILTIN_SOURCE_REGISTRY).decode_source, + tag_limit=tag_limit, ) await _register_plugins(archive, plugins_dir) return await archive.validate(source, progress=_emit_progress) diff --git a/src/powercontext/http/_generated/models.py b/src/powercontext/http/_generated/models.py index ed3f2e58db..3dbe468b13 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -3666,7 +3666,7 @@ class TagFilter(BaseModel): model_config = ConfigDict( extra="forbid", ) - tags: Annotated[list[Tag3], Field(max_length=16, min_length=1)] + tags: Annotated[list[Tag3], Field(max_length=64, min_length=1)] match: TagMatch = TagMatch.ALL @@ -3674,14 +3674,14 @@ class ReplaceArtifactTagsRequest(BaseModel): model_config = ConfigDict( extra="forbid", ) - tags: Annotated[list[Tag3], Field(max_length=32, min_length=0)] + tags: Annotated[list[Tag3], Field(max_length=256, min_length=0)] class QueryArtifactTagsRequest(BaseModel): model_config = ConfigDict( extra="forbid", ) - tags: Annotated[list[Tag3], Field(max_length=16, min_length=1)] + tags: Annotated[list[Tag3], Field(max_length=64, min_length=1)] match: TagMatch = TagMatch.ALL families: Annotated[ list[TaggableArtifactFamily] | None, @@ -3703,7 +3703,7 @@ class ArtifactTagSet(BaseModel): ) scope_id: StrictStr target: TagTarget - tags: Annotated[list[Tag3], Field(max_length=32, min_length=0)] + tags: Annotated[list[Tag3], Field(max_length=256, min_length=0)] tag_digest: Annotated[ StrictStr, Field( @@ -3719,7 +3719,7 @@ class TaggedTarget(BaseModel): ) scope_id: StrictStr target: TagTarget - tags: Annotated[list[Tag3], Field(max_length=32, min_length=0)] + tags: Annotated[list[Tag3], Field(max_length=256, min_length=0)] tag_digest: Annotated[ StrictStr, Field( @@ -3746,7 +3746,7 @@ class ListArtifactsRequest(BaseModel): model_config = ConfigDict( extra="forbid", ) - tag: Annotated[list[TagItem] | None, Field(max_length=16, min_length=1)] = None + tag: Annotated[list[TagItem] | None, Field(max_length=64, min_length=1)] = None tag_match: TagMatch | None = None limit: Annotated[StrictInt, Field(ge=1, le=100)] = 50 cursor: Annotated[StrictStr | None, Field(max_length=4096, min_length=1)] = None @@ -4693,8 +4693,8 @@ class CatalogChangeProposal(BaseModel): target: TagTarget expected_etag: Annotated[StrictStr, Field(min_length=1)] basis_ref: ArtifactReference - before_tags: Annotated[list[BeforeTag], Field(max_length=32)] - after_tags: Annotated[list[AfterTag], Field(max_length=32)] + before_tags: Annotated[list[BeforeTag], Field(max_length=256)] + after_tags: Annotated[list[AfterTag], Field(max_length=256)] class CatalogTagResult(BaseModel): @@ -4703,7 +4703,7 @@ class CatalogTagResult(BaseModel): ) scope_id: Annotated[StrictStr, Field(min_length=1)] target: TagTarget - tags: Annotated[list[Tag3], Field(max_length=32)] + tags: Annotated[list[Tag3], Field(max_length=256)] tag_digest: Annotated[StrictStr, Field(min_length=1)] etag: Annotated[StrictStr, Field(min_length=1)] @@ -4812,7 +4812,7 @@ class RecallManifestRequest(BaseModel): ) scope_id: Annotated[StrictStr, Field(max_length=256, min_length=1, pattern=".*\\S.*")] kind: Annotated[StrictStr | None, Field(min_length=1)] = None - tags: Annotated[list[Tag] | None, Field(max_length=16)] = None + tags: Annotated[list[Tag] | None, Field(max_length=64)] = None tag_match: TagMatch | None = None limit: Annotated[StrictInt, Field(ge=1, le=100)] = 50 cursor: Annotated[StrictStr | None, Field(max_length=4096)] = None @@ -4949,7 +4949,7 @@ class ListAtomicMemoryRequest(BaseModel): scope_id: Annotated[StrictStr, Field(max_length=256, min_length=1, pattern=".*\\S.*")] states: list[AtomicMemoryState] | None = None kind: Annotated[StrictStr | None, Field(min_length=1)] = None - tags: Annotated[list[Tag] | None, Field(max_length=16)] = None + tags: Annotated[list[Tag] | None, Field(max_length=64)] = None tag_match: TagMatch | None = None limit: Annotated[StrictInt, Field(ge=1, le=100)] = 50 cursor: Annotated[StrictStr | None, Field(max_length=4096)] = None @@ -4971,7 +4971,7 @@ class SearchAtomicMemoryRequest(BaseModel): query: Annotated[StrictStr, Field(max_length=8192, min_length=1)] mode: AtomicMemorySearchMode = AtomicMemorySearchMode.TEXT kind: Annotated[StrictStr | None, Field(min_length=1)] = None - tags: Annotated[list[Tag] | None, Field(max_length=16)] = None + tags: Annotated[list[Tag] | None, Field(max_length=64)] = None tag_match: TagMatch | None = None limit: Annotated[StrictInt, Field(ge=1, le=100)] = 20 diff --git a/src/powercontext/http/_generated/schema.py b/src/powercontext/http/_generated/schema.py index e2e7fd8f0c..a9cbf35358 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -5377,7 +5377,7 @@ "schema": { "type": "array", "minItems": 1, - "maxItems": 16, + "maxItems": 64, "items": {"type": "string", "minLength": 1, "maxLength": 64}, }, }, @@ -7065,7 +7065,7 @@ "properties": { "scope_id": {"type": "string", "maxLength": 256, "minLength": 1, "pattern": ".*\\S.*"}, "kind": {"type": "string", "minLength": 1, "nullable": True}, - "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 16}, + "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 64}, "tag_match": {"$ref": "#/components/schemas/TagMatch"}, "limit": {"type": "integer", "maximum": 100.0, "minimum": 1.0, "default": 50}, "cursor": {"type": "string", "maxLength": 4096, "nullable": True}, @@ -7306,7 +7306,7 @@ "scope_id": {"type": "string", "maxLength": 256, "minLength": 1, "pattern": ".*\\S.*"}, "states": {"items": {"$ref": "#/components/schemas/AtomicMemoryState"}, "type": "array"}, "kind": {"type": "string", "minLength": 1, "nullable": True}, - "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 16}, + "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 64}, "tag_match": {"$ref": "#/components/schemas/TagMatch"}, "limit": {"type": "integer", "maximum": 100.0, "minimum": 1.0, "default": 50}, "cursor": {"type": "string", "maxLength": 4096, "nullable": True}, @@ -7330,7 +7330,7 @@ "query": {"type": "string", "maxLength": 8192, "minLength": 1}, "mode": {"$ref": "#/components/schemas/AtomicMemorySearchMode", "default": "text"}, "kind": {"type": "string", "minLength": 1, "nullable": True}, - "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 16}, + "tags": {"items": {"type": "string", "minLength": 1}, "type": "array", "maxItems": 64}, "tag_match": {"$ref": "#/components/schemas/TagMatch"}, "limit": {"type": "integer", "maximum": 100.0, "minimum": 1.0, "default": 20}, }, @@ -15028,7 +15028,7 @@ "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 16, + "maxItems": 64, "minItems": 1, }, "match": {"$ref": "#/components/schemas/TagMatch", "default": "all"}, @@ -15036,13 +15036,16 @@ "additionalProperties": False, "type": "object", "required": ["tags"], + "description": "Exact label filter. The deployment's " + "configured query-label limit, 16 by " + "default, applies.", }, "ReplaceArtifactTagsRequest": { "properties": { "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, "minItems": 0, } }, @@ -15051,22 +15054,26 @@ "required": ["tags"], "description": "Replace all labels " "atomically. Empty " - "clears the set. Labels " - "preserve display text, " - "use NFC then casefold " - "for exact matching, and " - "reject normalized " - "duplicates, outer " - "whitespace, and Unicode " - "control, surrogate or " - "unassigned characters.", + "clears the set. The " + "deployment's configured " + "Artifact tag limit, 32 " + "by default, applies. " + "Labels preserve display " + "text, use NFC then " + "casefold for exact " + "matching, and reject " + "normalized duplicates, " + "outer whitespace, and " + "Unicode control, " + "surrogate or unassigned " + "characters.", }, "QueryArtifactTagsRequest": { "properties": { "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 16, + "maxItems": 64, "minItems": 1, }, "match": {"$ref": "#/components/schemas/TagMatch", "default": "all"}, @@ -15100,7 +15107,7 @@ "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, "minItems": 0, }, "tag_digest": { @@ -15128,7 +15135,7 @@ "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, "minItems": 0, }, "tag_digest": { @@ -15164,7 +15171,7 @@ "tag": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 16, + "maxItems": 64, "minItems": 1, }, "tag_match": {"$ref": "#/components/schemas/TagMatch"}, @@ -16413,12 +16420,12 @@ "before_tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, }, "after_tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, }, }, "additionalProperties": False, @@ -16432,7 +16439,7 @@ "tags": { "items": {"type": "string", "maxLength": 64, "minLength": 1}, "type": "array", - "maxItems": 32, + "maxItems": 256, }, "tag_digest": {"type": "string", "minLength": 1}, "etag": {"type": "string", "minLength": 1}, diff --git a/src/powercontext/limits.py b/src/powercontext/limits.py index 53d277e0ce..68bc865f5c 100644 --- a/src/powercontext/limits.py +++ b/src/powercontext/limits.py @@ -14,6 +14,8 @@ """Shared identity limits that remain safe for utf8mb4 relational indexes.""" +from dataclasses import dataclass + MAX_SCOPE_ID_LENGTH = 256 MAX_SCOPE_TITLE_LENGTH = 256 MAX_SCOPE_SUMMARY_LENGTH = 2_000 @@ -43,3 +45,17 @@ MAX_EXTERNAL_SKILL_LOCATOR_LENGTH = 2_000 MAX_POLICY_REVISION_LENGTH = 64 MAX_ARTIFACT_HANDLE_KEY_LENGTH = 128 +# Tag admission bounds. The defaults are the historical behaviour; a deployment may raise the effective +# limits up to these ceilings, which the contract and the generated clients also accept. +MAX_TARGET_TAGS = 32 +MAX_TARGET_TAGS_CEILING = 256 +MAX_QUERY_TAG_LABELS = 16 +MAX_QUERY_TAG_LABELS_CEILING = 64 + + +@dataclass(frozen=True, slots=True) +class TagLimits: + """Effective tag admission policy for one runtime.""" + + max_per_artifact: int = MAX_TARGET_TAGS + max_query_labels: int = MAX_QUERY_TAG_LABELS diff --git a/src/powercontext/server/app.py b/src/powercontext/server/app.py index c1480ac4d9..dcc12ade19 100644 --- a/src/powercontext/server/app.py +++ b/src/powercontext/server/app.py @@ -22,6 +22,7 @@ import ipaddress import json import logging +import re from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence from contextlib import asynccontextmanager, suppress from copy import deepcopy @@ -955,7 +956,12 @@ Operation, ) from powercontext.http._generated.schema import OPENAPI_SCHEMA -from powercontext.limits import MAX_SOURCE_CONTENT_CHARS, MAX_SOURCE_CONTENT_CHARS_CEILING +from powercontext.limits import ( + MAX_QUERY_TAG_LABELS_CEILING, + MAX_SOURCE_CONTENT_CHARS, + MAX_SOURCE_CONTENT_CHARS_CEILING, + TagLimits, +) from powercontext.server import mapping from powercontext.server.artifact_read_observation import observe_artifact_read from powercontext.server.atomic_memory import add_atomic_memory_routes @@ -1509,6 +1515,7 @@ def create_app( access_mode: Literal["disabled", "enforced"] | None = None, authentication_provider: AuthenticationProvider | None = None, allow_insecure_remote_http: bool = False, + tag_limits: TagLimits | None = None, ) -> FastAPI: """Build the HTTP adapter around an optional Runtime application binding.""" @@ -1526,6 +1533,7 @@ def create_app( app.state.plugin_manager = None app.state.plugin_api_max_body_bytes = 32 * 1024 * 1024 app.state.source_content_max_chars = MAX_SOURCE_CONTENT_CHARS + app.state.tag_limits = tag_limits or TagLimits() app.state.application = application app.state.capability_provider = capability_provider app.state.readiness_probe = readiness_probe @@ -3217,10 +3225,12 @@ def _list_artifacts_query( http_request: Request, limit: Annotated[int, Query(ge=1, le=100)] = 50, cursor: Annotated[str | None, Query(min_length=1, max_length=4096)] = None, - tag: Annotated[list[str] | None, Query(min_length=1, max_length=16)] = None, + tag: Annotated[list[str] | None, Query(min_length=1, max_length=MAX_QUERY_TAG_LABELS_CEILING)] = None, tag_match: Annotated[TagMatch | None, Query()] = None, ) -> ListArtifactsRequest: _require_strict_query(http_request, {"limit", "cursor", "tag", "tag_match"}, repeatable={"tag"}) + if tag is not None: + _require_tag_admission(http_request, len(tag), write=False, location=("query", "tag")) if tag is None and tag_match is not None: raise InvalidBaseAccessRequestError("tag_match", "requires at least one tag") return ListArtifactsRequest.model_validate({"limit": limit, "cursor": cursor, "tag": tag, "tag_match": tag_match}) @@ -3503,6 +3513,7 @@ async def replace_artifact_tags( application: Annotated[ServerApplication, Depends(_require_application)], if_match: Annotated[str | None, Header(alias="If-Match")] = None, ) -> ArtifactTagSet: + _require_tag_admission(http_request, len(request.tags), write=True, location=("body", "tags")) target = ArtifactTagTarget(family=_tag_family(family), artifact_id=artifact_id) if target.family == "atomic-memory": await _authorize_atomic_tag_write(http_request, scope_id, artifact_id, "replace_artifact_tags") @@ -3549,6 +3560,28 @@ async def replace_memory_entry_tags( raise BaseOperationNotSupportedError("artifact_family", "memory", "entry tags") +def _require_tag_admission( + request: Request, + count: int, + *, + write: bool, + location: tuple[str | int, ...], +) -> None: + """Reject tag arrays beyond the deployment's effective policy, inside the contract ceiling.""" + + limits = request.app.state.tag_limits + limit = limits.max_per_artifact if write else limits.max_query_labels + if count > limit: + kind = "Artifact" if write else "query" + raise RequestValidationError([ + { + "type": "too_long", + "loc": location, + "msg": f"tags must not exceed the deployment's {limit}-label {kind} limit.", + } + ]) + + def _if_none_match_matches(if_none_match: str | None, etag: str) -> bool: if if_none_match is None: return False @@ -3574,6 +3607,7 @@ async def query_artifact_tags( http_request: Request, application: Annotated[ServerApplication, Depends(_require_application)], ) -> ArtifactTagPage: + _require_tag_admission(http_request, len(request.tags), write=False, location=("body", "tags")) principal = current_principal() caller = ( f"{principal.type}:{principal.id}" @@ -4629,6 +4663,10 @@ async def search_memory( application: Annotated[ServerApplication, Depends(_require_application)], http_request: Request, ) -> SearchMemoryResponse: + if request.tag_filter is not None: + _require_tag_admission( + http_request, len(request.tag_filter.tags), write=False, location=("body", "tag_filter", "tags") + ) result = await _scoped_atomic_memory(application, request.scope_id).search( request.query, mode="text" if request.mode.value == "fts" else request.mode.value, @@ -5049,6 +5087,10 @@ async def list_memory_entries( application: Annotated[ServerApplication, Depends(_require_application)], http_request: Request, ) -> ListMemoryEntriesResponse: + if request.tag_filter is not None: + _require_tag_admission( + http_request, len(request.tag_filter.tags), write=False, location=("body", "tag_filter", "tags") + ) result = await _scoped_atomic_memory(application, request.scope_id).list( states=("active", "forgotten", "merged", "retired") if request.include_inactive else ("active",), limit=request.limit, @@ -7765,6 +7807,7 @@ def _map_scope_error(error: Exception) -> tuple[int, str, str, dict[str, Any] | _CANDIDATE_ERROR_REASONS = { + ("after_tags", "the candidate exceeds the deployment's"): ("after_tags", "tag_limit_exceeded"), ("artifacts", "must include the exact target"): ("artifact_refs", "target_not_in_artifact_refs"), ("artifacts", "new managed Skill lineage"): ("artifact_refs", "skill_lineage_not_permitted"), ("artifacts", "managed Skill lineage"): ("artifact_refs", "target_not_in_artifact_refs"), @@ -7776,7 +7819,12 @@ def _map_scope_error(error: Exception) -> tuple[int, str, str, dict[str, Any] | def _candidate_error_details(error: InvalidCandidateError) -> dict[str, Any] | None: for (field, prefix), (public_field, reason) in _CANDIDATE_ERROR_REASONS.items(): if error.field == field and error.detail.startswith(prefix): - return {"field": public_field, "reason": reason} + details: dict[str, Any] = {"field": public_field, "reason": reason} + if field == "after_tags": + limit = re.search(r"deployment's (\d+)-tag", error.detail) + if limit is not None: + details["limit"] = int(limit.group(1)) + return details # Internal-only fields (audit, basis, family) and reasons shared by several # public fields (evidence) have no stable name a caller can act on. return None diff --git a/src/powercontext/server/factory.py b/src/powercontext/server/factory.py index 4304ea83e5..3c555d449e 100644 --- a/src/powercontext/server/factory.py +++ b/src/powercontext/server/factory.py @@ -373,6 +373,8 @@ def bind_supervisor(supervisors) -> None: storage_root=powercontext_data_dir() / "plugins", snapshot_root=powercontext_data_dir() / "plugin-versions", rescan_seconds=resolved.plugins_rescan_seconds, + tag_max_per_artifact=resolved.runtime.tag_max_per_artifact, + tag_max_query_labels=resolved.runtime.tag_max_query_labels, # Host processes authorize callers in every role that serves requests. host_security_builder=lambda: build_host_security( resolved, @@ -482,6 +484,7 @@ def current_capabilities() -> Capabilities: access_mode=resolved.access.mode, authentication_provider=configured_authentication, allow_insecure_remote_http=resolved.allow_insecure_http, + tag_limits=resolved.runtime.tag_limits, ) app.state.source_content_max_chars = resolved.source_content_max_chars # Admission must see the outward send; only non-buffering instrumentation diff --git a/src/powercontext/server/plugins.py b/src/powercontext/server/plugins.py index 0ac998e62f..1cec534435 100644 --- a/src/powercontext/server/plugins.py +++ b/src/powercontext/server/plugins.py @@ -75,6 +75,7 @@ from powercontext.builtin.runtime.processing_discovery import SourceProcessingPendingProvider from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY from powercontext.http._generated.models import PluginPage, PluginScopePage, PluginScopeState, PluginState +from powercontext.limits import MAX_QUERY_TAG_LABELS, MAX_TARGET_TAGS from powercontext.plugins import Cron, Interval from powercontext.server.plugin_hosts import READY_TIMEOUT_SECONDS, HostProcessBudget, PluginHost from powercontext.server.plugin_versions import ( @@ -241,6 +242,8 @@ async def start(self, assignment: Any) -> Any: inference=self._manager.inference_config, storage_root=self._manager.storage_root, source_bindings=() if manifest.artifact is not None else self._manager.source_bindings(), + tag_max_per_artifact=self._manager.tag_max_per_artifact, + tag_max_query_labels=self._manager.tag_max_query_labels, ) entrypoint = run_plugin_worker if manifest.artifact is not None else run_source_collect_worker return await SpawnArtifactProcessingWorkerLauncher(partial(entrypoint, spec)).start(assignment) @@ -269,6 +272,8 @@ def __init__( serve_requests: bool = True, host_processes: Mapping[str, int] | None = None, host_processes_total: int | None = None, + tag_max_per_artifact: int = MAX_TARGET_TAGS, + tag_max_query_labels: int = MAX_QUERY_TAG_LABELS, ) -> None: self.database = database self.register_merge = register_merge @@ -295,6 +300,8 @@ def __init__( self.serve_requests = serve_requests self.host_processes = dict(host_processes or {}) self.host_budget = HostProcessBudget(host_processes_total) + self.tag_max_per_artifact = tag_max_per_artifact + self.tag_max_query_labels = tag_max_query_labels # Snapshots this process made; it deletes only these, once nothing here uses them. self._created: set[Path] = set() # Snapshots kept after they stopped being current: Workers or retiring host processes may still use them. @@ -715,6 +722,8 @@ def _host_spec(self, manifest: PluginManifest, directory: Path) -> PluginHostSpe plugin_families=families, source_bindings=bindings, storage_root=self.storage_root, + tag_max_per_artifact=self.tag_max_per_artifact, + tag_max_query_labels=self.tag_max_query_labels, ) async def _ensure_supervisor(self) -> ArtifactProcessingSupervisors: @@ -755,6 +764,7 @@ async def _register(self, plugin: _Plugin, *, definitions: bool = True) -> None: ArtifactMergeAccess(generate.family), SourceRepository(BUILTIN_SOURCE_REGISTRY), metadata=revision_metadata(manifest.name, manifest.fingerprint), + tag_limit=self.tag_max_per_artifact, ) ) unregister_source_binding(manifest.binding_name) diff --git a/tests/builtin/plugins/test_plugin_writer.py b/tests/builtin/plugins/test_plugin_writer.py index 152af7acd2..025d6be18f 100644 --- a/tests/builtin/plugins/test_plugin_writer.py +++ b/tests/builtin/plugins/test_plugin_writer.py @@ -430,3 +430,49 @@ async def scenario(): assert await writer.get("a") == result.artifact asyncio.run(scenario()) + + +def test_plugin_listing_applies_the_configured_query_limit(runtime) -> None: + from powercontext.builtin.records import InvalidBaseAccessRequestError + + async def scenario(): + async with open_builtin_contexts(runtime) as contexts: + scope = await _scope(contexts) + database = contexts.database + async with _writer(database, scope, tag_query_limit=40).transaction() as tx: + page = await tx.list(tags=[f"label-{index}" for index in range(40)]) + assert page.items == () + with pytest.raises(InvalidBaseAccessRequestError, match="40-label query limit"): + async with _writer(database, scope, tag_query_limit=40).transaction() as tx: + await tx.list(tags=[f"label-{index}" for index in range(41)]) + with pytest.raises(InvalidBaseAccessRequestError, match="16-label query limit"): + async with _writer(database, scope).transaction() as tx: + await tx.list(tags=[f"label-{index}" for index in range(17)]) + + asyncio.run(scenario()) + + +def test_plugin_listing_keeps_the_requested_page_size(runtime) -> None: + async def scenario(): + async with open_builtin_contexts(runtime) as contexts: + scope = await _scope(contexts) + database = contexts.database + writer = _writer(database, scope) + async with writer.transaction() as tx: + for index in range(20): + artifact_id = f"tagged-{index:02d}" + await tx.put(artifact_id, content={"text": f"tagged {index}"}) + await tx.set_tags(artifact_id, ["selected"]) + + first = await writer.list(tags=["selected"], limit=1) + assert len(first.items) == 1 + assert first.next_cursor is not None + second = await writer.list(tags=["selected"], limit=1, cursor=first.next_cursor) + assert len(second.items) == 1 + assert second.items[0].ref.artifact_id != first.items[0].ref.artifact_id + + page = await writer.list(tags=["selected"], limit=20) + assert len(page.items) == 20 + assert page.next_cursor is None + + asyncio.run(scenario()) diff --git a/tests/test_archive_cli.py b/tests/test_archive_cli.py index b0e0ce51ca..77bee51270 100644 --- a/tests/test_archive_cli.py +++ b/tests/test_archive_cli.py @@ -27,8 +27,9 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.persistence.tables import SCOPES_TABLE from powercontext.builtin.records import ArtifactWrite -from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts, open_builtin_runtime +from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_contexts, open_builtin_runtime from powercontext.builtin.scope import ScopeDraft +from powercontext.builtin.tags import ArtifactTagTarget from powercontext.cli import archive as archive_module from powercontext.cli.app import create_cli from powercontext.cli.archive import archive_app @@ -416,3 +417,52 @@ async def prepare() -> None: assert result.exit_code == 0, result.output assert json.loads(result.stdout)["compatible"] assert not target_path.parent.exists() + + +def test_archive_cli_dry_run_uses_the_configured_tag_write_limit(tmp_path, monkeypatch) -> None: + archive = tmp_path / "tags.pcb" + source_url = sqlite_url(tmp_path / "tags-source.db") + target_url = sqlite_url(tmp_path / "tags-target.db") + source_config = BuiltinConfig( + database=SQLiteConfig(url=source_url), + runtime=RuntimeConfig(artifact_processing_families=(), tag_max_per_artifact=64), + ) + + async def seed() -> None: + async def authorize(_scopes: tuple[str, ...]) -> None: + pass + + async with open_builtin_contexts(source_config) as source: + scope = await source.scopes.create( + ScopeDraft(title="Tagged archive", summary="Dry-run limit", idempotency_key="tagged-archive") + ) + created = await source.records.create_artifact( + scope.scope_id, "profile", ArtifactWrite(content={"content": "# Profile\n\nThirty-three labels."}) + ) + target = ArtifactTagTarget(family="profile", artifact_id=created.artifact_id) + current = await source.records.get_tags(scope.scope_id, target) + await source.records.replace_tags( + scope.scope_id, + target, + tuple(f"label-{index}" for index in range(33)), + expected_etag=current.etag, + ) + await source.portability.export([scope.scope_id], archive, authorize=authorize) + async with open_builtin_contexts(BuiltinConfig(database=SQLiteConfig(url=target_url))): + pass + + asyncio.run(seed()) + monkeypatch.setenv("POWERCONTEXT_HOME", str(tmp_path / "home")) + monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_KIND", "sqlite") + monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_URL", target_url) + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT", "64") + runner = CliRunner() + cli = create_cli([archive_app]) + + compatible = runner.invoke(cli, ["archive", "restore", str(archive), "--dry-run"]) + assert compatible.exit_code == 0, compatible.output + + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_TAG_MAX_PER_ARTIFACT", "32") + rejected = runner.invoke(cli, ["archive", "restore", str(archive), "--dry-run"]) + assert rejected.exit_code == 2, rejected.output + assert "tag set has invalid labels" in rejected.output diff --git a/tests/test_tag_limits.py b/tests/test_tag_limits.py new file mode 100644 index 0000000000..5de45585fc --- /dev/null +++ b/tests/test_tag_limits.py @@ -0,0 +1,427 @@ +# 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. + +"""Deployment-configured per-Artifact and per-query tag admission limits.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from powercontext.artifacts import ArtifactRef +from powercontext.builtin.catalog_changes.models import CatalogChangeProposal as CandidateProposal +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.records import ArtifactWrite, InvalidBaseAccessRequestError +from powercontext.builtin.review import InvalidCandidateError +from powercontext.builtin.runtime import ( + BuiltinConfig, + InferenceConfig, + RuntimeConfig, + open_builtin_contexts, + open_builtin_runtime, +) +from powercontext.builtin.scope import ScopeDraft +from powercontext.builtin.tags import ArtifactTagTarget, TagFilter, TagQuery +from powercontext.http._generated import models +from powercontext.limits import ( + MAX_QUERY_TAG_LABELS, + MAX_QUERY_TAG_LABELS_CEILING, + MAX_TARGET_TAGS, + MAX_TARGET_TAGS_CEILING, +) +from powercontext.server.factory import create_server_app +from powercontext.server.settings import McpConfig, ServerSettings + + +def _app(tmp_path: Path, *, artifact: int | None = None, query: int | None = None): + return create_server_app( + settings=ServerSettings( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'tags.db'}"), + inference=InferenceConfig(generation_model="test"), + runtime=RuntimeConfig( + artifact_processing_families=(), + tag_max_per_artifact=MAX_TARGET_TAGS if artifact is None else artifact, + tag_max_query_labels=MAX_QUERY_TAG_LABELS if query is None else query, + ), + mcp=McpConfig(enabled=False), + ) + ) + + +def _scope(client: TestClient, key: str = "tag-limits") -> str: + response = client.post( + "/v1/scopes", + json={"title": "tags", "summary": "limit contract", "idempotency_key": key}, + ) + assert response.status_code == 201, response.text + return response.json()["scope_id"] + + +def _entry(client: TestClient, scope_id: str) -> tuple[str, str]: + response = client.post( + "/v1/memory/remember", + json={"scope_id": scope_id, "kind": "fact", "text": "A durable fact for tag limits.", "description": "limit"}, + ) + assert response.status_code == 200, response.text + artifact = response.json()["records"][0]["artifact"] + return artifact[ + "artifact_id" + ], f"/v1/scopes/{scope_id}/artifacts/{artifact['family']}/{artifact['artifact_id']}/tags" + + +def _replace(client: TestClient, path: str, tags: list[str], etag: str): + return client.put(path, json={"tags": tags}, headers={"If-Match": etag}) + + +def _etag(client: TestClient, path: str) -> str: + response = client.get(path) + assert response.status_code == 200, response.text + return response.headers["ETag"] + + +def test_default_artifact_limit_is_unchanged(tmp_path: Path) -> None: + with TestClient(_app(tmp_path)) as client: + scope = _scope(client) + _, path = _entry(client, scope) + accepted = _replace(client, path, [f"label-{index}" for index in range(MAX_TARGET_TAGS)], _etag(client, path)) + rejected = _replace( + client, path, [f"label-{index}" for index in range(MAX_TARGET_TAGS + 1)], _etag(client, path) + ) + + assert accepted.status_code == 200, accepted.text + assert rejected.status_code == 422, rejected.text + assert f"{MAX_TARGET_TAGS}-label Artifact limit" in rejected.text + + +def test_configured_artifact_limit_allows_more_tags(tmp_path: Path) -> None: + with TestClient(_app(tmp_path, artifact=40)) as client: + scope = _scope(client) + _, path = _entry(client, scope) + accepted = _replace(client, path, [f"label-{index}" for index in range(40)], _etag(client, path)) + rejected = _replace(client, path, [f"label-{index}" for index in range(41)], _etag(client, path)) + + assert accepted.status_code == 200, accepted.text + assert rejected.status_code == 422, rejected.text + assert "40-label Artifact limit" in rejected.text + + +def test_query_limit_applies_to_tag_queries(tmp_path: Path) -> None: + with TestClient(_app(tmp_path)) as client: + scope = _scope(client) + accepted = client.post( + f"/v1/scopes/{scope}/artifact-tags/query", + json={"tags": [f"label-{index}" for index in range(MAX_QUERY_TAG_LABELS)]}, + ) + rejected = client.post( + f"/v1/scopes/{scope}/artifact-tags/query", + json={"tags": [f"label-{index}" for index in range(MAX_QUERY_TAG_LABELS + 1)]}, + ) + + assert accepted.status_code == 200, accepted.text + assert rejected.status_code == 422, rejected.text + assert f"{MAX_QUERY_TAG_LABELS}-label query limit" in rejected.text + + +def test_configured_query_limit_applies_to_artifact_filters(tmp_path: Path) -> None: + with TestClient(_app(tmp_path, query=20)) as client: + scope = _scope(client) + accepted = client.get( + f"/v1/scopes/{scope}/artifacts/atomic-memory", + params=[("tag", f"label-{index}") for index in range(20)], + ) + rejected = client.get( + f"/v1/scopes/{scope}/artifacts/atomic-memory", + params=[("tag", f"label-{index}") for index in range(21)], + ) + + assert accepted.status_code == 200, accepted.text + assert rejected.status_code == 400, rejected.text + assert "20-label query limit" in rejected.text + + +def test_query_limit_applies_to_memory_search_filters(tmp_path: Path) -> None: + with TestClient(_app(tmp_path)) as client: + scope = _scope(client) + body = {"query": "fact", "tag_filter": {"tags": [f"label-{index}" for index in range(17)]}} + rejected = client.post("/v1/memory/search", json={"scope_id": scope, **body}) + accepted = client.post( + "/v1/memory/search", + json={"scope_id": scope, "query": "fact", "tag_filter": {"tags": ["label-0"]}}, + ) + + assert rejected.status_code == 422, rejected.text + assert f"{MAX_QUERY_TAG_LABELS}-label query limit" in rejected.text + assert accepted.status_code == 200, accepted.text + + +def test_lowering_the_artifact_limit_keeps_existing_tags_readable_and_replaceable(tmp_path: Path) -> None: + with TestClient(_app(tmp_path, artifact=40)) as client: + scope = _scope(client) + _, path = _entry(client, scope) + original = [f"label-{index}" for index in range(40)] + assert _replace(client, path, original, _etag(client, path)).status_code == 200 + + with TestClient(_app(tmp_path, artifact=10)) as client: + readable = client.get(path) + lowered = _replace(client, path, [f"label-{index}" for index in range(10)], readable.headers["ETag"]) + rejected = _replace(client, path, [f"label-{index}" for index in range(11)], lowered.headers["ETag"]) + cleared = _replace(client, path, [], lowered.headers["ETag"]) + + assert readable.status_code == 200, readable.text + assert sorted(readable.json()["tags"]) == sorted(original) + assert lowered.status_code == 200, lowered.text + assert rejected.status_code == 422, rejected.text + assert cleared.status_code == 200, cleared.text + assert cleared.json()["tags"] == [] + + +def test_configuration_above_the_ceiling_is_rejected() -> None: + with pytest.raises(ValidationError): + RuntimeConfig(tag_max_per_artifact=MAX_TARGET_TAGS_CEILING + 1) + with pytest.raises(ValidationError): + RuntimeConfig(tag_max_query_labels=MAX_QUERY_TAG_LABELS_CEILING + 1) + + +def test_atomic_memory_routes_apply_the_query_limit(tmp_path: Path) -> None: + with TestClient(_app(tmp_path, query=2)) as client: + scope = _scope(client) + listed = client.post("/v1/atomic-memory/list", json={"scope_id": scope, "tags": ["a", "b", "c"]}) + searched = client.post( + "/v1/atomic-memory/search", json={"scope_id": scope, "query": "fact", "tags": ["a", "b", "c"]} + ) + + assert listed.status_code == 422, listed.text + assert "2-label query limit" in listed.text + assert searched.status_code == 422, searched.text + assert "2-label query limit" in searched.text + + +def test_candidate_proposal_accepts_labels_above_the_default_limit() -> None: + labels = [f"label-{index}" for index in range(40)] + proposal = models.CatalogChangeProposal.model_validate({ + "target": {"type": "artifact", "family": "profile", "artifact_id": "candidate"}, + "expected_etag": "etag", + "basis_ref": {"family": "profile", "artifact_id": "basis", "revision": 1}, + "before_tags": labels, + "after_tags": labels, + }) + + assert len(proposal.before_tags) == 40 + assert len(proposal.after_tags) == 40 + + +def test_embedded_runtime_queries_apply_the_query_limit(tmp_path: Path) -> None: + async def scenario() -> None: + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'embedded.db'}"), + runtime=RuntimeConfig(artifact_processing_families=(), tag_max_query_labels=2), + ) + async with open_builtin_runtime(config) as runtime: + assert runtime.scopes is not None + scope = await runtime.scopes.create( + ScopeDraft(title="Embedded limits", summary="query limit", idempotency_key="embedded-limits") + ) + records = runtime.records.for_scope(scope.scope_id) + with pytest.raises(InvalidBaseAccessRequestError, match="2-label query limit"): + await records.query_tags(TagQuery(tags=("one", "two", "three"))) + with pytest.raises(InvalidBaseAccessRequestError, match="2-label query limit"): + await records.query_artifacts( + "profile", limit=5, cursor=None, tag_filter=TagFilter(tags=("one", "two", "three")) + ) + + asyncio.run(scenario()) + + +def _candidate_proposal( + client: TestClient, scope_id: str, artifact_id: str, path: str, after_tags: list[str] +) -> CandidateProposal: + del scope_id + current = client.get(path) + assert current.status_code == 200, current.text + return CandidateProposal( + target=ArtifactTagTarget(family="atomic-memory", artifact_id=artifact_id), + expected_etag=current.headers["ETag"], + basis_ref=ArtifactRef(family="atomic-memory", artifact_id=artifact_id, revision=1), + before_tags=tuple(current.json()["tags"]), + after_tags=tuple(after_tags), + ) + + +def test_candidate_larger_than_the_default_limit_approves_over_http(tmp_path: Path) -> None: + labels = [f"label-{index}" for index in range(40)] + with TestClient(_app(tmp_path, artifact=64)) as client: + scope = _scope(client) + artifact_id, path = _entry(client, scope) + support_id, _ = _entry(client, scope) + app = client.app + assert isinstance(app, FastAPI) + service = app.state.application.catalog_changes.for_scope(scope) + candidate = asyncio.run( + service.propose( + _candidate_proposal(client, scope, artifact_id, path, labels), + reason="forty labels", + artifacts=(ArtifactRef(family="atomic-memory", artifact_id=support_id, revision=1),), + ) + ) + candidate_id = candidate.candidate_id + + fetched = client.post("/v1/candidates/get", json={"scope_id": scope, "candidate_id": candidate_id}) + assert fetched.status_code == 200, fetched.text + listed = client.post("/v1/candidates/list", json={"scope_id": scope}) + assert listed.status_code == 200, listed.text + assert candidate_id in {item["candidate_id"] for item in listed.json()["candidates"]} + approved = client.post( + "/v1/candidates/approve", + json={"scope_id": scope, "candidate_id": candidate_id, "expected_version": 1}, + ) + assert approved.status_code == 200, approved.text + current = client.get(path) + assert current.status_code == 200 + assert set(current.json()["tags"]) == set(labels) + + +def test_candidate_proposal_and_revision_respect_the_effective_limit(tmp_path: Path) -> None: + with TestClient(_app(tmp_path)) as client: + scope = _scope(client) + artifact_id, path = _entry(client, scope) + support_id, _ = _entry(client, scope) + app = client.app + assert isinstance(app, FastAPI) + service = app.state.application.catalog_changes.for_scope(scope) + with pytest.raises(InvalidCandidateError, match="32-tag"): + asyncio.run( + service.propose( + _candidate_proposal(client, scope, artifact_id, path, [f"label-{index}" for index in range(33)]), + reason="over limit", + artifacts=(ArtifactRef(family="atomic-memory", artifact_id=support_id, revision=1),), + ) + ) + candidate = asyncio.run( + service.propose( + _candidate_proposal(client, scope, artifact_id, path, [f"label-{index}" for index in range(32)]), + reason="at limit", + artifacts=(ArtifactRef(family="atomic-memory", artifact_id=support_id, revision=1),), + ) + ) + with pytest.raises(InvalidCandidateError, match="32-tag"): + asyncio.run( + service.revise( + candidate.candidate_id, + 1, + after_tags=tuple(f"label-{index}" for index in range(33)), + reason="over limit revision", + ) + ) + + +def test_lowering_the_limit_keeps_candidates_readable_but_not_approvable(tmp_path: Path) -> None: + labels = [f"label-{index}" for index in range(40)] + with TestClient(_app(tmp_path, artifact=64)) as client: + scope = _scope(client) + artifact_id, path = _entry(client, scope) + support_id, _ = _entry(client, scope) + app = client.app + assert isinstance(app, FastAPI) + service = app.state.application.catalog_changes.for_scope(scope) + candidate = asyncio.run( + service.propose( + _candidate_proposal(client, scope, artifact_id, path, labels), + reason="forty labels", + artifacts=(ArtifactRef(family="atomic-memory", artifact_id=support_id, revision=1),), + ) + ) + candidate_id = candidate.candidate_id + + with TestClient(_app(tmp_path, artifact=32)) as client: + fetched = client.post("/v1/candidates/get", json={"scope_id": scope, "candidate_id": candidate_id}) + assert fetched.status_code == 200, fetched.text + rejected = client.post( + "/v1/candidates/approve", + json={"scope_id": scope, "candidate_id": candidate_id, "expected_version": 1}, + ) + assert rejected.status_code == 422, rejected.text + assert "after_tags" in rejected.text + assert "tag_limit_exceeded" in rejected.text + assert '"limit":32' in rejected.text + current = client.get(path) + assert current.status_code == 200 + assert current.json()["tags"] == [] + + +def test_embedded_runtime_rejects_tag_writes_above_the_configured_limit(tmp_path: Path) -> None: + async def scenario() -> None: + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'write-limit.db'}"), + runtime=RuntimeConfig(artifact_processing_families=(), tag_max_per_artifact=2), + ) + async with open_builtin_runtime(config) as runtime: + assert runtime.scopes is not None + scope = await runtime.scopes.create( + ScopeDraft(title="Write limit", summary="embedded write", idempotency_key="write-limit") + ) + records = runtime.records.for_scope(scope.scope_id) + created = await records.create_artifact( + "profile", ArtifactWrite(content={"content": "# Profile\n\nWrite limit."}) + ) + target = ArtifactTagTarget(family="profile", artifact_id=created.artifact_id) + current = await records.get_tags(target) + with pytest.raises(InvalidBaseAccessRequestError, match="2-label"): + await records.replace_tags(target, ("one", "two", "three"), expected_etag=current.etag) + + asyncio.run(scenario()) + + +def test_export_survives_a_lowered_write_limit(tmp_path: Path) -> None: + archive = tmp_path / "lowered.pcb" + database_url = f"sqlite+aiosqlite:///{tmp_path / 'lowered.db'}" + + async def scenario() -> None: + async def authorize(_scopes: tuple[str, ...]) -> None: + pass + + async with open_builtin_contexts( + BuiltinConfig( + database=SQLiteConfig(url=database_url), + runtime=RuntimeConfig(artifact_processing_families=(), tag_max_per_artifact=64), + ) + ) as contexts: + scope = await contexts.scopes.create( + ScopeDraft(title="Export limit", summary="lowered", idempotency_key="export-limit") + ) + created = await contexts.records.create_artifact( + scope.scope_id, "profile", ArtifactWrite(content={"content": "# Profile\n\nExport limit."}) + ) + target = ArtifactTagTarget(family="profile", artifact_id=created.artifact_id) + current = await contexts.records.get_tags(scope.scope_id, target) + await contexts.records.replace_tags( + scope.scope_id, target, tuple(f"label-{index}" for index in range(40)), expected_etag=current.etag + ) + await contexts.portability.export([scope.scope_id], archive, authorize=authorize) + + async with open_builtin_contexts( + BuiltinConfig( + database=SQLiteConfig(url=database_url), + runtime=RuntimeConfig(artifact_processing_families=(), tag_max_per_artifact=32), + ) + ) as contexts: + second = tmp_path / "lowered-second.pcb" + await contexts.portability.export([scope.scope_id], second, authorize=authorize) + assert second.exists() + + asyncio.run(scenario())