From 2c8001e0c959569c11afdc7bc83cd2d53c45513d Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Mon, 7 Sep 2026 14:48:59 +0800 Subject: [PATCH 1/4] docs(rfc): propose user profile artifacts --- docs/en/rfcs/0000_profile_artifact.md | 2054 +++++++++++++++++++++++++ docs/zh/rfcs/0000_profile_artifact.md | 1791 +++++++++++++++++++++ 2 files changed, 3845 insertions(+) create mode 100644 docs/en/rfcs/0000_profile_artifact.md create mode 100644 docs/zh/rfcs/0000_profile_artifact.md diff --git a/docs/en/rfcs/0000_profile_artifact.md b/docs/en/rfcs/0000_profile_artifact.md new file mode 100644 index 0000000000..ba50e0012d --- /dev/null +++ b/docs/en/rfcs/0000_profile_artifact.md @@ -0,0 +1,2054 @@ +- Proposal Name: `profile_artifact` +- Start Date: 2026-09-07 +- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), + [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), + [RFC 1345](1345_scope_organization_and_agent_integration.md), + [RFC 1396](1396_handoff_access_control.md), and [RFC 1437](1437_source_artifact_rest_api.md) + +# Summary + +This RFC adds the `profile` Artifact Family to PowerContext. The first release defines only one fixed user Profile; it +does not expose a profile-type field, other Profile types, or a Profile Schema Registry. + +A Profile is a rebuildable, Source-derived complete snapshot, not a source of truth. A user Profile has a fixed address: + +```text +Head identity: +(root_scope_id, family="profile", artifact_id="profile:user") + +Exact revision identity: +(root_scope_id, family="profile", artifact_id="profile:user", revision) +``` + +`subject_key` is the business `user_id` supplied directly by the caller when creating a Source. PowerContext does not +generate another user identifier or interpret, concatenate, or normalize this value. The name `subject_key` allows the +`subject_key -> root_scope_id` subject-addressing and Source-projection mechanism to be reused by other Artifact Families +in the future; the first release still fixes the subject to a user. + +Scope organization uses one design: + +- each `subject_key` maps one-to-one to a user Root Scope; +- a shared business Scope is not attached beneath any user's Root; +- a Source with a `subject_key` is written in one transaction to both the business Scope and that user's Root Scope, for + exactly two persisted Source records; +- the Profile Processor consumes only the Source journal in a Root Scope, so one user never triggers another user's + Profile processing; +- an ordinary Scope without a `subject_key` may still explicitly enable a Scope-local Profile. + +Profile content is not split into Claim categories, Claim rows, or risk levels. The LLM produces complete Markdown, +stored as `ProfileContent.content` in the existing `pc_artifacts.content` BLOB. Automatic generation runs daily at +`02:00` by default in the deployment's configured IANA time zone, which defaults to `Asia/Shanghai`; callers may change +the Cron expression and time zone or request immediate generation. + +# Motivation + +User-facing Agents need to apply one long-lived Profile across sessions, tasks, and business Scopes. Generating a +Profile only inside each original business Scope creates multiple Profiles for the same user. Adding a generic +`user_id` column to every Source and Artifact would instead conflate storage ownership, content subject, content author, +and authorization principal. + +Multi-party conversations make this distinction clearer. One group-chat Scope can contain messages from U1, U2, and +U3, but `pc_scopes.parent_scope_id` has only one value: the group Scope cannot simultaneously be a child of all three +user Roots. The correct design preserves the group Scope's original organization, copies each user's own Sources +precisely into that user's Root, and generates the user Profile in the Root. + +This design keeps general-purpose Source, Scope, and Artifact as the fact and artifact infrastructure, while adding a +narrow convenience layer for subject routing. The integrating application remains responsible for deciding how +business users, conversations, and Sources correspond. PowerContext provides stable Root resolution, reliable +dual-Scope Source writes, background Profile generation, and Revision maintenance. + +## Goals + +1. Add the `profile` Artifact Family while reusing the existing internal Artifact record, Head, Revision, Lineage, and + CAS semantics. The first release does not add Profile to the generic Artifact Create/Replace request unions. +2. Support only a fixed user Profile in the first release; do not design profile-type extension, Claim categories, or a + per-Claim risk model. +3. Use the caller's business `user_id` as `subject_key` and establish an immutable one-to-one + `subject_key <-> root_scope_id` mapping. +4. Support Sources from different users in a shared Scope, while ensuring that a new Source from one user advances only + that user's Root journal. +5. Persist a Source with a `subject_key` exactly twice: once in the original business Scope and once in the corresponding + user Root. +6. Generate Profiles in the background at `02:00` daily by default, with configurable Cron and time zone, without making + the business Source write path wait for an LLM. +7. Store complete Markdown Profiles in the existing `pc_artifacts.content` BLOB, without adding a Claim table or Profile + content columns. +8. Activate revisions automatically by default, while allowing an entire Revision to enter Review according to its + Profile Scope policy. +9. Support manual creation, replacement, review, history inspection, diffing, and non-destructive rollback. +10. Specify every new table and API, all uses of existing tables, and all changes to existing APIs. +11. Allow future Artifact Families to reuse Subject Root and Root-local Sources, without implementing other subject + types or other artifact derivation in the first release. + +## Non-goals + +The first release explicitly excludes: + +- other Profile types such as `team`, `agent`, `customer`, or `driver`; +- custom Profile types, subject types, Profile Schema registration, or arbitrary Claim Schemas; +- user registration, authentication, account aliases, anonymous-to-registered conversion, account merging, or user-ID + generation; +- guessing from natural language which user owns a Source; +- binding one Source to multiple `subject_key` values; +- adding a generic `subject_key` column to `pc_sources` or `pc_artifacts`; +- accepting `family="profile"` through the generic Artifact Create or Replace endpoints in the first release; +- automatically attaching a shared business Scope beneath a user Root, or treating Scope Parent as authorization; +- automatically copying existing Memory, Skill, Experience, Topic Memory, or other Artifacts from a shared Scope; +- automatically rebuilding a Profile because the model, prompt, or implementation version changed when no new Source + exists; +- a general deletion, withdrawal, and forgetting protocol for every Source and Artifact Family; however, the minimum + consistent-cleanup semantics for the Origin/Root duplicate must be decided before this RFC merges; +- implementing the complete subject-derived lifecycle for Artifact Families other than Profile. + +# Guide-level explanation + +## Terminology and invariants + +| Term | Meaning | +| --- | --- | +| `subject_key` | The business `user_id` supplied directly by the caller; it denotes only a user subject in the first release | +| `root_scope_id` | An ordinary `pc_scopes.scope_id` that PowerContext creates for a `subject_key`, serving as the stable storage anchor for that user's long-lived artifacts | +| Business Scope | A Scope organized by a conversation, group chat, project, or application; it may contain Sources from multiple users | +| Root Source | The same Source copied from a business Scope into a user Root; its content is identical to the origin Source | +| Scope-local Profile | A local Profile generated directly from the Sources of an ordinary Scope without using `subject_key` | +| Profile Head | The current Profile Revision at the fixed `artifact_id` within a Scope | + +The following invariants must hold: + +```text +one subject_key -> exactly one root_scope_id +one root_scope_id -> at most one subject_key + +one subject-keyed Source -> one origin Source + one Root Source +one origin Source -> at most one subject_key + +one user Root -> at most one Profile Head +``` + +`subject_key` answers "which user subject's data should this Source enter?" It is not equivalent to: + +- who is currently signed in; +- who owns the underlying resource; +- which users are mentioned in the content; +- who is authorized to read the Root; +- the general unique key of a Source or Artifact. + +The caller must ensure that `subject_key` is unique, stable, and never reused within one PowerContext deployment and +database. PowerContext performs a case-sensitive, byte-exact comparison of the complete string. Callers should use an +internal user ID, not a directly identifying value such as a name, phone number, email address, or government ID. + +## Scope organization + +### Group chat example: exactly four Scopes + +When group chat G1 contains users U1, U2, and U3, there are exactly four Scopes: + +```mermaid +flowchart LR + K1["subject_key = U1"] --> R1["root_scope_id = R_U1"] + K2["subject_key = U2"] --> R2["root_scope_id = R_U2"] + K3["subject_key = U3"] --> R3["root_scope_id = R_U3"] + G["business scope_id = S_GROUP
U1 + U2 + U3 group chat"] + + G -. "U1 Source copy" .-> R1 + G -. "U2 Source copy" .-> R2 + G -. "U3 Source copy" .-> R3 +``` + +| Scope | Purpose | `parent_scope_id` | +| --- | --- | --- | +| `R_U1` | U1's Root Sources, Profile, and future user-level artifacts | `NULL` | +| `R_U2` | U2's Root Sources, Profile, and future user-level artifacts | `NULL` | +| `R_U3` | U3's Root Sources, Profile, and future user-level artifacts | `NULL` | +| `S_GROUP` | Stores the complete original group-chat record | Preserves the business-defined parent; does not point to `R_U1/R_U2/R_U3` | + +The dashed lines represent Source projections, not `parent_scope_id` or `pc_scope_context_references`. This RFC does not +automatically write a Scope Parent or Context Reference because a user participates in a group chat. + +### What a Root Scope records + +A Root Scope is itself an ordinary `pc_scopes` row. This RFC adds no `profile_root_scope` table and does not place user +information in `pc_scopes.title` or `summary`: + +```text +pc_scopes + scope_id = R_U1 + title = "Subject Root" + summary = "User subject data root" + parent_scope_id= NULL + version = 1 +``` + +The mapping between `subject_key=U1` and `R_U1` is stored in the new `pc_subject_roots` table. Actual content is stored +in: + +- `pc_sources`: Sources projected for U1 from different business Scopes; +- `pc_artifacts` / `pc_artifact_heads`: U1's Profile Revisions and Head; +- the Lineage, Cursor, Pending, Policy, and Profile Revision metadata tables. + +The Root Scope is a storage and aggregation anchor, not a user-account record. It does not perform authentication or +automatically grant access. + +### Parent rules + +1. A user Root's `parent_scope_id` is always `NULL`. +2. A Scope registered as a Root cannot later receive a Parent through Scope Update. +3. A shared business Scope preserves its own business organization and is not automatically reparented to any user + Root. +4. When the business genuinely has a single-user child Scope, it may explicitly create that Scope as a descendant of a + Root; this is not a Source Create side effect. +5. Context aggregation by `subject_key` selects the Root and its true descendants by default; a shared group-chat Scope + is not in any user's subtree. + +### Source is stored exactly twice + +After one Source from U1 is written in the group chat, the database contains exactly two Sources with identical content: + +```text +(S_GROUP, source_type="content", source_id="source_01") # origin +(R_U1, source_type="content", source_id="source_01") # Root copy +``` + +Source identity includes `scope_id`, so both records may reuse the same `source_type + source_id`. The new path first +generates a deployment-unique Source ID and then reuses the same `ContentSource` in both Scopes. Their `payload` values +are therefore identical, but their `journal_position` values are assigned independently by the `S_GROUP` and `R_U1` +Source journals. A new relationship table records the exact address and content digest on each side. + +U1's Source is not written to `R_U2` or `R_U3`; a U1 write therefore advances only the `S_GROUP` and `R_U1` journals. + +There is one exception: if the caller creates a Source with `subject_key=U1` directly in `R_U1`, the origin Scope is +already the target Root, so only one Source is stored and no self-copy is created. + +A user Root is a protected subject storage boundary. A public Source Create request that writes directly into a Root +must include the `subject_key` matching that Root's mapping. A missing or mismatched key is rejected, preventing +unattributed Sources from contaminating the global Profile. + +### Multi-user Source boundary + +Each Source Create request may carry at most one `subject_key`. In a group chat, the integrating application should +split Sources by speaker or independently attributable message: + +```python +await client.sources.create( + scope_id="S_GROUP", + content={"role": "user", "text": "Please give me the concise conclusion first"}, + subject_key="U1", +) + +await client.sources.create( + scope_id="S_GROUP", + content={"role": "user", "text": "I prefer a detailed analysis"}, + subject_key="U2", +) +``` + +A batch Source containing messages from multiple users must be split first; PowerContext does not ask an LLM to guess +which user owns the entire content. A Source without `subject_key` is stored only in the current Scope and enters no +user Root. If that ordinary Scope has explicitly enabled a Scope-local Profile through `pc_profile_policies`, the same +Source transaction also upserts the current Scope's `profile-source-window` Pending row so the daily Scheduler can +discover it. + +### Root creation and authorization + +`subject_key` never derives a Principal. The calling Principal comes only from authentication middleware or a trusted +internal bridge. Optional `root_contributor` is an explicit existing `PrincipalRef`; when omitted it defaults to the +calling Principal, and its type can only be `user` or `service`. + +When a Root does not exist, automatic creation must close the complete authorization loop: + +1. The calling Principal must have `scope.contribute` on the Origin Scope. +2. The same calling Principal must also have `server.admin`. A deployment may instead configure a trusted provisioning + service Principal to exercise `server.admin` internally, but that does not replace the calling Principal's + `scope.contribute` on the Origin. +3. In one coordinated transaction, create the `pc_scopes` Root, `pc_subject_roots` mapping, and default + `pc_profile_policies`, and use the Access Control `RelationshipWriter` to create a `scope.contributor` Binding for the + explicit `root_contributor`. +4. Only after the Binding succeeds does the routing service's internal branch write the first Root Source, projection + relationship, and Pending row. A failure at any step commits neither the Origin Source, the Root, nor a one-sided + authorization relationship. + +If an external Authorization Provider's `RelationshipWriter` cannot participate in this coordinated transaction, +automatic creation must return `503 relationship_management_unavailable`. The deployment must first use a trusted +provisioning flow to create the Root, mapping, Policy, and Binding, and only then submit the business Source. It must not +write the Origin first and fill in authorization asynchronously. + +An existing Root does not require `server.admin`, but the calling Principal must have `scope.contribute` on both the +Origin and Root Scopes. A request's `root_contributor` cannot modify an existing Binding and cannot impersonate the +calling Principal. + +### Atomic write flow + +```mermaid +sequenceDiagram + participant App as Application + participant API as Source API + participant PEP as Access Control + participant DB as PowerContext DB + + App->>API: Create Source(scope=S_GROUP, subject_key=U1) + API->>PEP: require scope.contribute on Origin + alt Root absent + API->>PEP: require server.admin or trusted provisioner + else Root exists + API->>PEP: require scope.contribute on Root + end + API->>DB: BEGIN + API->>DB: resolve or atomically provision U1 -> R_U1 + API->>DB: if new, bind explicit root_contributor + API->>DB: insert origin Source into S_GROUP journal + API->>DB: insert identical Source into R_U1 journal + API->>DB: insert pc_subject_source_projections relation + API->>DB: upsert Profile pending for R_U1 + API->>DB: COMMIT + API-->>App: 201 Source + committed subject projection +``` + +The diagram uses the HTTP Source API to illustrate the call, but the dual write is not private logic in the HTTP +handler. The Runtime API, Python SDK, MCP, Connectors, and other business-ingestion adapters must all enter the same +`SubjectSourceRoutingService` application service whenever they carry a `subject_key`. That service consistently +performs Root Resolve, dual-Scope locking, the dual Source write, projection recording, and Pending upsert. No entry +point may implement only part of this flow or bypass it by directly writing an Origin Source with subject attribution. + +The business entry request types explicitly extended in the first release are `CreateSourceRequest`, +`CaptureContentSourceRequest`, and `SubmitSourceObservationRequest`. All three share the +`subject_key/root_contributor` routing fields and the same application service. A Connector submitting an observation +must not bypass this service. + +Internal `lineage_only` system Sources generated as Artifact-write provenance, and internal domain Sources maintained by +an Artifact Family, are not business entry Sources. They do not accept `subject_key` or enter the subject-projection +service. They remain in the target Scope and are written directly by the corresponding domain service. + +The dual write must satisfy the following requirements: + +- the origin Source, Root Source, projection relationship, and Root Profile Pending row commit in the same database + transaction; any failure rolls back the whole transaction; +- when locking two Source journals, locks are acquired in `scope_id` order to avoid concurrent deadlocks; +- an internal retry of one Source operation reuses the same `source_type + source_id`; an identical payload is an + idempotent success, while a different payload returns a conflict; the Source ID must be deployment-unique when it is + generated; +- database uniqueness constraints and the transaction jointly enforce the one-to-one mapping between `subject_key` and + Root; +- a Source is an immutable fact record. An incorrect `subject_key` cannot be reassigned in place; the caller appends a + corrective Source and a later Profile Revision incorporates the correction. + +## Profile Artifact + +### Identity and singleton + +A subject-keyed user Profile is fixed at: + +```text +(root_scope_id, family="profile", artifact_id="profile:user") +``` + +The first write in a Root uses the Profile Create convenience endpoint. A subsequent Profile Create when `profile:user` +already exists returns `409 Conflict`; later writes must use Profile Replace. Profile Replace must echo the current +Head's opaque `ETag` unchanged in `If-Match`. Profile APIs first resolve `ProfileTarget` to the scoped fixed address and +then reuse the internal `RecordService` persistence and Head CAS primitives. They do not derive an ID through a generic +family writer and do not introduce a second concurrency contract in which a Revision in the request body replaces the +HTTP precondition. + +The generic Artifact Create and Replace endpoints do not accept `profile` in the first release. Exact generic Artifact +Get, List, and Get Revision do accept `family="profile"`, because they read an already resolved Artifact identity rather +than choosing which Profile singleton to write. + +An ordinary Scope without a `subject_key` may explicitly enable a Scope-local Profile: + +```text +(scope_id, family="profile", artifact_id="profile:local") +``` + +A shared or multi-user Scope does not enable a Scope-local Profile by default, preventing U1, U2, and U3 from being +combined into one Profile. + +### Profile content + +A Profile Revision is a complete current Markdown snapshot. The first release defines no Claim categories, Claim keys, +structured Claim list, or per-Claim risk levels. + +To preserve the existing Artifact Repository constraint that family content is a Pydantic Model, Profile uses a model +with a single body payload: + +```python +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +class ProfileContent(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema: Literal["powercontext.profile.v1"] = "powercontext.profile.v1" + media_type: Literal["text/markdown"] = "text/markdown" + content: Annotated[str, Field(min_length=1)] + + @field_validator("content") + @classmethod + def validate_markdown(cls, value: str) -> str: + normalized = normalize_profile_markdown(value) + if len(normalized.encode("utf-8")) > 262_144: + raise ValueError("profile Markdown exceeds 256 KiB") + return normalized +``` + +Logical content example: + +```json +{ + "schema": "powercontext.profile.v1", + "media_type": "text/markdown", + "content": "# User Profile\n\nThe user prefers concise answers in Chinese. For hotels in China, the user usually selects a king room with a typical budget of CNY 500-700.\n" +} +``` + +The `content` is generated entirely by an LLM or edited by an authorized user, and its format is Markdown: + +```markdown +# User Profile + +The user prefers concise answers in Chinese. For hotels in China, the user usually selects a king room with a typical +budget of CNY 500-700. +``` + +Normalization is fixed to UTF-8, Unicode NFC, LF newlines, no BOM, and exactly one trailing newline. The server validates +that the document is non-empty, within the size limit, and has valid Markdown document boundaries. It does not interpret +heading levels as database categories. + +### Physical BLOB encoding + +The existing `pc_artifacts.content` is already a `BLOB`, or `MEDIUMBLOB` in the OceanBase/MySQL variant, so no schema +change is required. The first release keeps the current Artifact codec: it serializes `ProfileContent` as Pydantic JSON +UTF-8 bytes into the BLOB. In other words, the BLOB contains model bytes whose string field is Markdown. It is not a new +Claim column, nor raw text written around the Artifact Repository. + +```text +pc_artifacts.content + = UTF8_BYTES('{"schema":"powercontext.profile.v1",' + '"media_type":"text/markdown",' + '"content":"# User Profile\\n...\\n"}') +``` + +Profile-specific APIs decode this value and return a string. The general Artifact API continues to return a `content` +object, so the existing `ArtifactRevision.content: object` response shape does not change. + +### Revision lineage and generation metadata + +Every automatic generation, manual creation, manual replacement, approval, and rollback creates a new immutable +Revision: + +- an automatically generated or approved Revision references the Root-local business Sources actually consumed in + this run through `pc_artifact_lineage_sources`; it does not reference `lineage_only` Sources filtered out of the + window; +- manual Profile Create, Replace, and Rollback resolve the fixed scoped identity and reuse the internal Artifact + `RecordService` and CAS transaction primitives described by [RFC 1437](1437_source_artifact_rest_api.md). They + preserve the `lineage_only` system Source generated by the write command and place it at ordinal 0 in the new + Revision's direct Source lineage; +- `pc_artifact_lineage_artifacts` references the exact previous Profile Revision on update; +- `pc_profile_revision_metadata` stores the generation mode, Source Window, generator version, and rollback source; +- runtime cursors and internal task state are not mixed into the Markdown. + +The system Source produced by a manual write remains auditable provenance, but the Profile Processor must filter it out. +A Profile edit must not become evidence for the next Profile generation. + +### Update rules + +The model input for an automatic update is: + +```text +current Profile Markdown ++ Root Source window (cursor, source_through] +-> full next Profile Markdown | NOOP +``` + +Merge rules: + +1. An automatic LLM call is allowed only when the Root Source journal contains unconsumed business Sources. Changes to + the model, prompt, or code version, and the arrival of only `lineage_only` Sources, do not trigger a rebuild. +2. Before invoking the LLM, the Worker filters every `lineage_only` Source and deduplicates by exact Source address and + content digest. If a window contains only filtered items, it does not invoke the LLM or create a Revision, but still + advances the Cursor with CAS so the same items are not scanned forever. +3. The LLM reads the current complete Markdown and the new Sources and preserves only stable, cross-session user + information with durable value. +4. Exact duplicates are merged. A new, explicit user statement supersedes a conflicting older statement. When evidence + is insufficient, the old statement remains and no sensitive inference is made. +5. Trust applies only to a complete Profile Revision. When the current Head's `generation_mode` is `manual_create`, + `manual_replace`, `review_approved`, or `rollback`, the whole current document takes precedence over an unconfirmed + generated replacement unless a new Source explicitly records a user correction. The first release does not infer + that individual paragraphs within a Markdown document have different trust levels. +6. The LLM must return complete Markdown or `NOOP`; it cannot operate on database fields directly. +7. The server normalizes the result and calculates a digest. If it matches the current Head, no empty Revision is + created; only the Cursor advances. +8. A validation failure, model failure, or CAS conflict does not advance the Cursor. On a CAS conflict, the Worker + rereads the Head and performs the merge again. + +Removing the Claim structure means that the first release provides Revision-level lineage only, not Claim-level +queries, risk classification, or citations. Those capabilities should later be implemented as rebuildable indexes +rather than by writing Claim classifications back into the fact tables. + +## Background automatic generation + +### Schedule configuration + +By default, one automatic Profile processing wave begins every day at `02:00` in the deployment time zone: + +```python +from typing import Annotated +from zoneinfo import ZoneInfo + +from pydantic import BaseModel, Field + +class ProfileGenerationSchedule(BaseModel): + enabled: bool = True + cron: str = "0 2 * * *" + timezone: str = "Asia/Shanghai" + source_window_limit: Annotated[int, Field(ge=1, le=1000)] = 200 + max_concurrency: Annotated[int, Field(ge=1, le=128)] = 8 + worker_timeout_seconds: Annotated[int, Field(ge=30, le=3600)] = 900 + retry_max_delay_seconds: Annotated[int, Field(ge=30, le=86_400)] = 1800 + + def tzinfo(self) -> ZoneInfo: + return ZoneInfo(self.timezone) +``` + +`02:00` is the default off-peak time. A deployment may change the Cron expression and IANA time zone. A large +deployment may configure scheduling jitter, but the default has no jitter. The implementation must use a time-zone-aware +CronTrigger rather than an IntervalTrigger that runs every 86,400 seconds, because service restarts and daylight-saving +time would otherwise cause drift. + +### Scheduled call flow + +```mermaid +sequenceDiagram + participant Cron as Profile Cron Scheduler + participant Sup as Artifact Processing Supervisor + participant DB as Metadata + Artifact DB + participant Worker as Profile Worker + participant LLM as LLM + + Cron->>Sup: daily wave at 02:00 + Sup->>DB: acquire/renew global lease + Sup->>DB: page pending(binding=profile-source-window) + DB-->>Sup: dirty Profile scopes and source_through + Sup->>Worker: assign(scope, after, through, generation) + Worker->>DB: read Cursor + current Profile + fixed Source window + Worker->>LLM: current Markdown + new Sources + LLM-->>Worker: complete Markdown or NOOP + Worker->>Worker: normalize, validate, digest + alt automatic and changed + Worker->>DB: CAS Create/Replace Revision + metadata + Cursor + else review_required and changed + Worker->>DB: create full-Markdown Candidate; wait for decision + else NOOP + Worker->>DB: CAS advance Cursor only + end + Worker-->>Sup: success / review_pending / failure +``` + +Detailed flow: + +1. In the business Source write transaction, the unified `SubjectSourceRoutingService` has already upserted the Root + journal high-water mark into `pc_artifact_processing_pending`, without invoking an LLM. When an ordinary Scope + explicitly enables a Scope-local Profile, its own journal high-water mark is registered as a separate target. A + shared Scope is disabled by default. +2. At `02:00` every day, the instance holding the Supervisor lease starts that day's wave. The persistent scheduler uses + `coalesce=true`, so it runs once after recovering from a missed execution time. +3. The Supervisor pages dirty targets with `binding_name="profile-source-window"` and schedules them fairly up to + `max_concurrency`. +4. A Worker freezes the current `source_through`, reads `after` from `pc_source_cursors`, reads Source Windows in batches + of at most 200 by default, and excludes `lineage_only` items before invoking the model. A Source that arrives during + inference has a position greater than `through` and remains for the next wave. +5. If `after >= through`, or the fixed Window is empty after filtering, the Worker skips the LLM; in the latter case it + still advances the Cursor. Once the Cursor reaches the Pending high-water mark, Pending is cleared. +6. The Worker reads the current Profile and fixed Source Window and invokes the LLM outside a transaction, avoiding + locks held by a long transaction. +7. The Worker validates the complete Markdown. In automatic mode, it commits the Revision, Lineage, Revision Metadata, + and Cursor in one short transaction protected by Head CAS, Cursor CAS, and Supervisor fencing. +8. When there is no semantic change, the Worker creates no Revision and only advances the Cursor with CAS. +9. In `review_required` mode, the Worker creates a full-Profile Candidate, persists its Source Window, and claims the + Policy's single `pending_candidate_id` in one transaction. Scheduled and Manual Generate paths do not create a + duplicate while a Candidate is pending. Approval creates a Revision and advances through the Candidate's + `source_through`. Rejection must explicitly select `reject_and_consume` or `reject_and_retry`: the former advances + the Cursor so the same proposal is not recreated the next day; the latter leaves the Cursor unchanged and retains + Pending so a later wave may regenerate the same window. +10. A failure for one user does not block other users. Failure does not advance the Cursor or remove Pending, and is + retried with exponential backoff capped at 30 minutes by default. + +### Why a durable dirty set instead of a Job history table + +Profile reuses the general `pc_artifact_processing_pending`, `pc_artifact_processing_leases`, and `pc_source_cursors` +defined by the Topic Memory RFC. Pending means that a `(binding_name, scope_id)` pair still has unconsumed Sources; it is +not an ever-growing task history. + +The first release adds no `pc_profile_generation_jobs`. Processing status is derived from Pending, Cursor, the current +journal head, and the latest Profile Revision Metadata. Runtime logs and metrics observe individual attempts. If Topic +Memory's general processing tables have not landed before Profile is implemented, they are added as general tables by +this RFC and must not be described as pre-existing tables. + +### Manual generation + +`POST /v1/profile/generate` does not wait synchronously for an LLM. It reads the current Source journal head, increments +Pending's `flush_generation`, wakes the Supervisor, and always returns HTTP `200`. The response body's `status` is +`accepted`, `idle`, or `review_pending`. With no new Source it returns `idle` and does not rebuild the current Profile; +with an existing automatic Candidate it returns `review_pending` without creating another Candidate. + +## Review, edit and rollback + +Because Claim categories and risk levels have been removed, the review unit is the entire Markdown Revision: + +```python +from typing import Literal + +from pydantic import BaseModel, ConfigDict + +class ProfilePolicy(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + generation_enabled: bool = True + activation_mode: Literal["automatic", "review_required"] = "automatic" + version: int +``` + +- `automatic`: the default; valid new Markdown is created or replaced and immediately becomes the Head; +- `review_required`: generated content is written to the existing Artifact Candidate tables and becomes a new Revision + only after approval; +- the policy is set by server configuration or changed for a target Scope by an authorized user through the Policy API; + the LLM does not choose it; +- there is no configuration that activates one Claim risk level automatically while requiring Review for another, + because the first release has no Claim-level structure. + +When rejecting an automatic Candidate, the review request must explicitly submit a `disposition`: + +- `reject_and_consume`: record the rejection, advance the Cursor to the Candidate's `source_through`, update Pending, + and clear the Policy pointer; +- `reject_and_retry`: record the rejection, leave the Cursor unchanged, retain or re-upsert Pending, and clear the + Policy pointer. + +A manual edit submits complete Markdown, a reason, and the current Head's `If-Match`, and creates a new Revision. A +rollback does not move the Head pointer backward. It reads the Markdown from the selected old Revision and copies it +into the next Revision after the current Head. Revision Metadata records `restored_from_revision`, and the HTTP request +also uses `If-Match` to protect the current Head. + +Candidate approval, manual editing, and rollback all use Artifact Head CAS. If the Head changes during review, approval +returns a conflict and requires regeneration or Candidate revision; content based on an old Head must not silently +overwrite a new Head. + +Human confirmation applies to the complete Candidate proposal and the resulting complete Head. It is represented by the +Revision's `generation_mode="review_approved"`, not by paragraph annotations. The conflict resolver must not describe a +paragraph as human-confirmed merely because some other part of the same Markdown Revision was edited or reviewed. + +## Subject context aggregation + +`subject_key` is not only a way to find a Profile. It also defines a stable query entry point reusable by different +Artifact Families: + +```mermaid +flowchart LR + K["subject_key"] --> Resolve["resolve root_scope_id"] + Resolve --> Select["root + true descendants"] + Select --> Auth["authorize every Scope and Artifact"] + Auth --> Profile["exact Profile Head"] + Auth --> Recall["family-specific recall"] + Recall --> Dedup["exact + semantic dedup"] + Profile --> Compose["conflict-aware composition"] + Dedup --> Compose + Compose --> Budget["rank + family quota + max_bytes"] +``` + +Scope selection follows these rules: + +1. The server obtains the unique `root_scope_id` from `pc_subject_roots`. +2. Candidate Scopes are the Root and its true descendants. Parent expresses organization only; every Scope and Artifact + still requires authorization. +3. A shared group-chat Scope is not part of any user Root subtree and is not implicitly selected because the user + participates in the chat. +4. Profile is read exactly at its fixed address and does not participate in ordinary vector recall. Memory, Topic + Memory, Skill, Experience, and other families use their own recall providers. +5. Each `(scope_id, family, artifact_id, revision)` is kept once; the same Head and its exact Revision are not injected + twice. Cross-Scope results must use `ArtifactAddress`, which includes `scope_id`; they cannot return an `ArtifactRef` + that is complete only within one Scope. +6. Within a family, content is first deduplicated by stable identity and content digest, then semantically deduplicated. + Procedural knowledge from different families is not merged merely because its text is similar. +7. When a Markdown Profile conflicts with another artifact, ranking can use only the current Head's whole-document + `generation_mode`, time, and direct evidence. Revision-level manual mode must not be interpreted as paragraph-level + trust. If the conflict remains unresolved, the result includes a conflict summary and both exact + `ArtifactAddress` values without modifying any source Artifact. +8. Final composition applies family quotas and the request's `max_bytes`. The server measures actual UTF-8 bytes, and + truncated content preserves a complete address that callers can expand. + +A Memory Entry or another family-owned subresource must likewise return a complete address containing `scope_id`. +Subject aggregation results cannot contain a bare `ArtifactRef`, Entry ref, or other subresource ref that can be +dereferenced only by assuming a current Scope. + +The existing Prepare Context path processes only the Scope range explicitly supplied by the caller and does not +automatically traverse a Subject Root. The Subject Context API in this RFC resolves the range server-side and then +reuses each family's existing recall capability. + +Profile is the only user-level artifact generated automatically in the first release. If another Artifact Family later +reuses this design, it should consume evidence from the Root-local Source journal and write results into the Root or a +true child Scope. Artifacts already present in a shared Scope do not automatically become cross-Scope merely because a +Source was copied. + +# Reference-level explanation + +## Database metadata design + +### Relationship diagram + +```mermaid +erDiagram + PC_SCOPES ||--o| PC_SUBJECT_ROOTS : "root_scope_id" + PC_SCOPES ||--o{ PC_SOURCES : owns + PC_SUBJECT_ROOTS ||--o{ PC_SUBJECT_SOURCE_PROJECTIONS : routes + PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "origin Source" + PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "Root Source" + PC_SCOPES ||--o{ PC_ARTIFACTS : owns + PC_ARTIFACTS ||--o| PC_PROFILE_REVISION_METADATA : "Profile subset" + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : cites + PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : evidence + PC_SCOPES ||--o| PC_PROFILE_POLICIES : configures + PC_ARTIFACT_CANDIDATE_HEADS ||--o| PC_PROFILE_CANDIDATE_METADATA : tracks_window + PC_SCOPES ||--o{ PC_SOURCE_CURSORS : consumes + PC_SCOPES ||--o{ PC_ARTIFACT_PROCESSING_PENDING : marks_dirty +``` + +At runtime, `pc_artifact_processing_leases` fences Worker commits with the Supervisor's +`holder_id + supervisor_generation`. It has no database foreign key to Pending and therefore is not shown as a solid ER +relationship. The `root_contributor` authorization binding is persisted in the existing +`pc_access_relationships` table. That table identifies resources through its access-control resource columns and hash, +not a foreign key to `pc_subject_roots`, so the binding is also not drawn as a solid ER edge. + +### New table: `pc_subject_roots` + +This family-neutral table maps a subject to its Root Scope: + +| Field | Type | Constraint | Meaning | +| --- | --- | --- | --- | +| `subject_key` | `VARCHAR(256)` binary collation | PK | Caller-provided business `user_id`, matched exactly | +| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, UNIQUE, FK -> `pc_scopes.scope_id` | User Root generated by PowerContext | +| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | Mapping creation time | + +An additional `UNIQUE(subject_key, root_scope_id)` supports the composite foreign key from the projection table. Once +created, a mapping cannot be rebound. Account merging and migration require a separate design. + +### New table: `pc_subject_source_projections` + +This table records the exact one-to-one projection between a business-Scope Source and a Root Source: + +| Field | Type | Constraint | +| --- | --- | --- | +| `origin_scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_sources.scope_id` | +| `origin_source_type` | `VARCHAR(128)` binary collation | PK part, FK part | +| `origin_source_id` | `VARCHAR(256)` binary collation | PK part, FK part | +| `subject_key` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | +| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | +| `projected_source_type` | `VARCHAR(128)` binary collation | NOT NULL, FK part -> `pc_sources` | +| `projected_source_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_sources` | +| `content_digest` | `VARCHAR(71)` binary collation | NOT NULL, `sha256:` | +| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | + +Constraints: + +```text +PRIMARY KEY (origin_scope_id, origin_source_type, origin_source_id) +UNIQUE (root_scope_id, projected_source_type, projected_source_id) +FOREIGN KEY (origin_scope_id, origin_source_type, origin_source_id) + REFERENCES pc_sources(scope_id, source_type, source_id) +FOREIGN KEY (root_scope_id, projected_source_type, projected_source_id) + REFERENCES pc_sources(scope_id, source_type, source_id) +FOREIGN KEY (subject_key, root_scope_id) + REFERENCES pc_subject_roots(subject_key, root_scope_id) +CHECK (origin_scope_id <> root_scope_id) +``` + +In the first release, `projected_source_type/id` equal those of the origin Source. Separate fields preserve complete +addresses on both sides and allow a future internal Source adapter to define a different address. + +### New table: `pc_profile_policies` + +This table supports both Subject Root Profiles and explicitly enabled Scope-local Profiles: + +| Field | Type | Constraint | Default | +| --- | --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK, FK -> `pc_scopes.scope_id` | - | +| `generation_enabled` | `BOOLEAN` | NOT NULL | `TRUE` for Subject Root | +| `activation_mode` | `VARCHAR(32)` binary collation | NOT NULL, CHECK `automatic/review_required` | `automatic` | +| `pending_candidate_id` | `VARCHAR(128)` binary collation | nullable, FK part -> `pc_artifact_candidate_heads` | `NULL` | +| `version` | `BIGINT` | NOT NULL, CHECK > 0 | `1` | +| `updated_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | current time | + +Creating a Subject Root also creates its default Policy. The absence of a Policy for an ordinary Scope means that its +Scope-local Profile is disabled; the caller must configure it explicitly before it participates in the daily scan. + +Together with the same row's `scope_id`, `pending_candidate_id` forms a foreign key to +`pc_artifact_candidate_heads(scope_id, candidate_id)`. A Worker may create an automatic Profile Candidate only when this +field is `NULL`, and sets it in the same transaction. Approve/Reject clears it after completing Cursor/Pending handling. +This single pointer guarantees at most one pending automatic Candidate for each Profile Scope, including concurrent +Manual Generate paths. + +### New table: `pc_profile_revision_metadata` + +Markdown contains only Profile content; runtime metadata is associated separately with the Artifact Revision: + +| Field | Type | Constraint | +| --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifacts` | +| `family` | `VARCHAR(128)` binary collation | PK part, FK part, CHECK `family='profile'` | +| `artifact_id` | `VARCHAR(128)` binary collation | PK part, FK part | +| `revision` | `INTEGER` | PK part, FK part | +| `generation_mode` | `VARCHAR(32)` binary collation | `automatic/manual_create/manual_replace/review_approved/rollback` | +| `generator_id` | `VARCHAR(128)` binary collation | NULL for manual operations | +| `generator_version` | `VARCHAR(128)` binary collation | NULL for manual operations | +| `source_after` | `BIGINT` | nullable, CHECK >= 0 | +| `source_through` | `BIGINT` | nullable, CHECK >= `source_after` | +| `restored_from_revision` | `INTEGER` | nullable, CHECK > 0; composite FK with the same `scope_id/family/artifact_id` | +| `operation_reason` | `TEXT` | nullable | +| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | + +Constraints: + +```text +PRIMARY KEY (scope_id, family, artifact_id, revision) +FOREIGN KEY (scope_id, family, artifact_id, revision) + REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) +FOREIGN KEY (scope_id, family, artifact_id, restored_from_revision) + REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) +CHECK (family = 'profile') +CHECK (generation_mode IN + ('automatic', 'manual_create', 'manual_replace', 'review_approved', 'rollback')) +CHECK ((source_after IS NULL) = (source_through IS NULL)) +CHECK (source_after IS NULL OR (source_after >= 0 AND source_through >= source_after)) +CHECK ( + (generation_mode IN ('automatic', 'review_approved') AND source_after IS NOT NULL) + OR + (generation_mode IN ('manual_create', 'manual_replace', 'rollback') AND source_after IS NULL) +) +CHECK ( + (generation_mode = 'rollback' AND restored_from_revision IS NOT NULL) + OR + (generation_mode <> 'rollback' AND restored_from_revision IS NULL) +) +``` + +The nullable composite foreign key is inactive for non-rollback rows. These mode checks prevent a manual Revision from +claiming a generated Source Window and prevent an automatic or approved generated Revision from omitting its exact +Window. + +### New table: `pc_profile_candidate_metadata` + +The existing Candidate tables do not store a generation window, so a rejection cannot reliably determine how far to +advance the Cursor. An automatic Profile Candidate therefore receives one narrow processing-metadata row: + +| Field | Type | Constraint | +| --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifact_candidate_heads` | +| `candidate_id` | `VARCHAR(128)` binary collation | PK part, FK part | +| `binding_name` | `VARCHAR(128)` binary collation | NOT NULL, CHECK `binding_name='profile-source-window'` | +| `source_after` | `BIGINT` | NOT NULL, CHECK >= 0 | +| `source_through` | `BIGINT` | NOT NULL, CHECK >= `source_after` | +| `claimed_flush_generation` | `BIGINT` | NOT NULL, CHECK >= 0 | +| `rejection_disposition` | `VARCHAR(32)` binary collation | nullable; `reject_and_consume/reject_and_retry` | +| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | + +```text +PRIMARY KEY (scope_id, candidate_id) +FOREIGN KEY (scope_id, candidate_id) + REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) +CHECK (binding_name = 'profile-source-window') +CHECK (source_through >= source_after) +CHECK (rejection_disposition IS NULL OR rejection_disposition IN + ('reject_and_consume', 'reject_and_retry')) +``` + +Candidate Create writes the Candidate, this metadata, and `pc_profile_policies.pending_candidate_id` together, but does +not advance the Cursor. Approve commits the Profile Revision, Revision Metadata, Candidate status, Cursor/Pending state, +and Policy pointer in one transaction. Reject creates no Artifact: `reject_and_consume` advances through +`source_through` and updates Pending in one transaction, while `reject_and_retry` preserves the Cursor and retains or +re-upserts Pending. Both record `rejection_disposition` and the rejection reason and clear the Policy pointer. If the +Head changed in the meantime, the operation conflicts and preserves the Candidate without advancing the Cursor. + +### New generic tables shared with Topic Memory + +If Topic Memory has not already created the following two tables, this RFC adds them. + +`pc_artifact_processing_pending`: + +| Field | Type | Constraint | +| --- | --- | --- | +| `binding_name` | `VARCHAR(128)` binary collation | PK part | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_scopes.scope_id` | +| `source_through` | `BIGINT` | NOT NULL, CHECK >= 1 | +| `flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK >= 0 | +| `handled_flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK between 0 and `flush_generation` | + +Profile uses `binding_name="profile-source-window"`. + +`pc_artifact_processing_leases`: + +| Field | Type | Constraint | +| --- | --- | --- | +| `supervisor_group` | `VARCHAR(128)` binary collation | PK; fixed to `global` in the first release | +| `holder_id` | `VARCHAR(128)` binary collation | NOT NULL | +| `supervisor_generation` | `BIGINT` | NOT NULL, CHECK > 0 | +| `lease_expires_at` | `DateTime(timezone=True)`, normalized to UTC | nullable for single-process SQLite | + +These two tables are general Artifact processing substrate, not part of the Profile content model. + +### Existing tables: no physical schema changes + +This RFC changes no columns, primary keys, or foreign keys in the following existing tables: + +| Existing table | Use in this RFC | DDL change | +| --- | --- | --- | +| `pc_scopes` | Stores business Scopes and user Roots; Root has `parent_scope_id=NULL` | None | +| `pc_scope_bindings` | Not used for Subject Root mappings in this design | None | +| `pc_scope_context_references` | Not written automatically by Source Create | None | +| `pc_access_relationships` | Stores the explicit `root_contributor` / `scope.contributor` binding created during authorized Root bootstrap | None | +| `pc_sources` | Stores an identical Source once in the origin Scope and once in the Root | None | +| `pc_source_journal_heads` | Maintains an independent journal high-water mark for each Scope | None | +| `pc_source_cursors` | Stores the consumption position for `profile-source-window` | None | +| `pc_artifacts` | Stores immutable Profile Revisions; `content` is already BLOB/MEDIUMBLOB | None | +| `pc_artifact_heads` | Stores the current Head for `profile:user` or `profile:local` | None | +| `pc_artifact_lineage_sources` | Profile cites only same-Scope Root Sources | None | +| `pc_artifact_lineage_artifacts` | A new Profile Revision cites the previous Revision | None | +| `pc_artifact_candidate_versions` | Stores the complete ProfileContent proposal in `review_required` mode | None | +| `pc_artifact_candidate_heads` | Stores the current review state of a Profile Candidate | None | +| `pc_artifact_publications` | Artifact Publication is not used for Source copies in this RFC | None | +| `powercontext_scheduler_jobs` | The APScheduler sidecar gains one Profile Cron job row | No schema change | + +Although database DDL does not change, the Artifact and Candidate family enums in code and OpenAPI must add `profile`, +as described in the API changes. + +### Example rows for one U1 message + +```text +pc_subject_roots + (U1, R_U1) + +pc_sources + (S_GROUP, content, source_01, payload=P, journal_position=101) + (R_U1, content, source_01, payload=P, journal_position=42) + +pc_subject_source_projections + (S_GROUP, content, source_01, U1, R_U1, content, source_01, sha256:...) + +pc_artifact_processing_pending + (profile-source-window, R_U1, source_through=42, ...) +``` + +The Roots, journals, Cursors, and Pending rows for U2 and U3 do not change. + +## API design + +### Python request and response types + +```python +from __future__ import annotations + +from typing import Annotated, Any, Generic, Literal, Mapping, TypeVar + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +SubjectKey = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] +ETag = Annotated[str, Field(min_length=1)] + + +class PrincipalRef(BaseModel): + type: Literal["user", "service"] + id: Annotated[str, Field(min_length=1, max_length=256)] + description: str | None = None + + +class SubjectRoutingFields(BaseModel): + subject_key: SubjectKey | None = None + root_contributor: PrincipalRef | None = None + + +class CreateSourceRequest(SubjectRoutingFields): + # Existing fields remain unchanged. + source_type: Literal["content"] = "content" + content: Any + + +class CaptureContentSourceRequest(SubjectRoutingFields): + # Existing fields remain unchanged. + scope_id: str + source_id: str + content: str + metadata: dict[str, Any] | None = None + + +class SubmitSourceObservationRequest(SubjectRoutingFields): + # The existing SourceObservation schema remains unchanged. + scope_id: str + observation: Any + + +class SourceAddress(BaseModel): + scope_id: str + source_type: str + source_id: str + + +class SubjectProjectionReceipt(BaseModel): + subject_key: SubjectKey + root_scope_id: str + origin_source: SourceAddress + root_source: SourceAddress + status: Literal["committed", "already_in_root"] + + +# DELTA ONLY: this is not a replacement definition for SourceRecord. +# SourceRecord retains every existing field, including receipt_identity. +class SourceRecordDelta(BaseModel): + subject_projection: SubjectProjectionReceipt | None = None + + +class ArtifactRef(BaseModel): + family: str + artifact_id: str + revision: int + + +class ArtifactAddress(BaseModel): + scope_id: str + artifact: ArtifactRef + + +class MemoryEntryAddress(BaseModel): + memory: ArtifactAddress + entry_id: str + entry_version_id: str + + +class ProfileTarget(BaseModel): + subject_key: SubjectKey | None = None + scope_id: str | None = None + + @model_validator(mode="after") + def exactly_one_target(self): + if (self.subject_key is None) == (self.scope_id is None): + raise ValueError("provide exactly one of subject_key or scope_id") + return self + + +class ResolvedProfileTarget(BaseModel): + scope_id: str + artifact_id: Literal["profile:user", "profile:local"] + # Both are populated for a subject-keyed Profile and null for Scope-local. + subject_key: SubjectKey | None = None + root_scope_id: str | None = None + + +class ResolveSubjectRequest(BaseModel): + subject_key: SubjectKey + create_if_absent: bool = True + origin_scope_id: str | None = None + root_contributor: PrincipalRef | None = None + + @model_validator(mode="after") + def require_origin_for_create(self): + if self.create_if_absent and self.origin_scope_id is None: + raise ValueError("origin_scope_id is required when create_if_absent=true") + return self + + +class ResolveSubjectResponse(BaseModel): + subject_key: SubjectKey + root_scope_id: str + created: bool + + +class ProfileGenerationMetadata(BaseModel): + mode: Literal[ + "automatic", + "manual_create", + "manual_replace", + "review_approved", + "rollback", + ] + source_after: int | None = None + source_through: int | None = None + restored_from_revision: int | None = None + created_at: str + + +class ProfileRecord(BaseModel): + target: ResolvedProfileTarget + artifact: ArtifactAddress + media_type: Literal["text/markdown"] = "text/markdown" + content: str + content_digest: str + generation: ProfileGenerationMetadata + + +class ProfileResponse(BaseModel): + """Python SDK wrapper; the wire body is ProfileRecord and ETag is a header.""" + + record: ProfileRecord + etag: ETag + + +class CreateProfileRequest(BaseModel): + target: ProfileTarget + content: str + reason: str + + +class GetProfileRequest(BaseModel): + target: ProfileTarget + + +class ListProfileChangesRequest(BaseModel): + target: ProfileTarget + limit: Annotated[int, Field(ge=1, le=100)] = 50 + cursor: str | None = None + + +class ProfileChange(BaseModel): + artifact: ArtifactAddress + generation: ProfileGenerationMetadata + content_digest: str + + +class ProfileChangesPage(BaseModel): + target: ResolvedProfileTarget + items: tuple[ProfileChange, ...] + next_cursor: str | None = None + + +class DiffProfileRequest(BaseModel): + target: ProfileTarget + from_revision: Annotated[int, Field(ge=1)] + to_revision: Annotated[int, Field(ge=1)] + + +class ProfileDiffHunk(BaseModel): + old_start: int + old_lines: int + new_start: int + new_lines: int + lines: tuple[str, ...] + + +class ProfileDiff(BaseModel): + from_artifact: ArtifactAddress + to_artifact: ArtifactAddress + hunks: tuple[ProfileDiffHunk, ...] + + +class ReplaceProfileRequest(BaseModel): + # If-Match is an HTTP header, not a body field. + target: ProfileTarget + content: str + reason: str + + +class RollbackProfileRequest(BaseModel): + # If-Match is an HTTP header, not a body field. + target: ProfileTarget + restore_revision: Annotated[int, Field(ge=1)] + reason: str + + +class GenerateProfileRequest(BaseModel): + target: ProfileTarget + + +class ProfileGenerationResponse(BaseModel): + target: ResolvedProfileTarget + status: Literal["accepted", "idle", "review_pending"] + binding_name: Literal["profile-source-window"] + source_through: int | None = None + flush_generation: int | None = None + + +class GetProfileProcessingRequest(BaseModel): + target: ProfileTarget + + +class ProfileProcessingStatus(BaseModel): + target: ResolvedProfileTarget + journal_head: int + cursor_after: int + pending_through: int | None = None + pending_flush_generation: int | None = None + pending_candidate_id: str | None = None + last_result: Literal["success", "noop", "review_pending", "failure"] | None = None + + +class GetProfilePolicyRequest(BaseModel): + target: ProfileTarget + + +class ProfilePolicyRecord(BaseModel): + target: ResolvedProfileTarget + generation_enabled: bool + activation_mode: Literal["automatic", "review_required"] + version: int + + +class UpdateProfilePolicyRequest(BaseModel): + target: ProfileTarget + generation_enabled: bool + activation_mode: Literal["automatic", "review_required"] + expected_version: Annotated[int, Field(ge=1)] + + +ContextAddress = ArtifactAddress | MemoryEntryAddress + + +class PrepareSubjectContextRequest(BaseModel): + subject_key: SubjectKey + query: Annotated[str, Field(min_length=1)] + families: tuple[Literal["profile", "memory", "topic-memory", "skill", "experience"], ...] + max_bytes: Annotated[int, Field(ge=1, le=4_194_304)] + + +class SubjectContextItem(BaseModel): + address: ContextAddress + content: str + selected_bytes: int + + +class SubjectContextConflict(BaseModel): + summary: str + left: ContextAddress + right: ContextAddress + + +class PreparedSubjectContext(BaseModel): + subject_key: SubjectKey + root_scope_id: str + scope_ids: tuple[str, ...] + items: tuple[SubjectContextItem, ...] + conflicts: tuple[SubjectContextConflict, ...] + used_bytes: int + max_bytes: int + truncated: bool + + +T = TypeVar("T") + + +class HttpResult(BaseModel, Generic[T]): + body: T + headers: Mapping[str, str] + + +def with_profile_metadata(result: HttpResult[ProfileRecord]) -> ProfileResponse: + """Shared SDK helper used by Profile Create, Get, Replace, and Rollback.""" + + etag = result.headers.get("ETag") + if etag is None: + raise RuntimeError("Profile response omitted required ETag") + return ProfileResponse(record=result.body, etag=etag) +``` + +`ProfileTarget(subject_key=...)` resolves to `root_scope_id + profile:user`. `ProfileTarget(scope_id=...)` first checks +whether the Scope is registered in `pc_subject_roots`: a user Root also normalizes to `profile:user`, while only an +ordinary Scope resolves to `profile:local`. Different selectors therefore cannot create two Profile Heads in the same +user Root. `ResolvedProfileTarget.subject_key` and `root_scope_id` are nullable precisely for the Scope-local case; its +scoped `ArtifactAddress` remains complete. + +Every Profile Create, Get, Replace, and Rollback HTTP success returns `ProfileRecord` in the response body and the +current opaque value in the HTTP `ETag` header. The generated transport client gains a metadata-aware response helper +that reads that header and returns `ProfileResponse(record=..., etag=...)`; the high-level synchronous and asynchronous +Python Profile clients use this helper rather than discarding response metadata. Replace and Rollback accept +`if_match: str` in Python and send it as `If-Match`, not as a JSON field. + +The `SourceRecordDelta` block above shows only the field added by this RFC. The final `SourceRecord` retains every +existing field, including `receipt_identity`, and adds optional `subject_projection`; the delta must not replace the +existing schema. + +### Existing API changes + +| Existing API/Schema | Change | Compatibility | +| --- | --- | --- | +| All business Source write application services | Add optional `subject_key` and `root_contributor` to `CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest`; when a key is present, uniformly use `SubjectSourceRoutingService` | Behavior is unchanged when omitted; HTTP, Runtime, MCP, and Connectors share the path | +| `POST /v1/scopes/{scope_id}/sources` | The HTTP adapter passes the extended `CreateSourceRequest` to the unified service above | Behavior is unchanged without a key; additive change | +| `POST /v1/sources/content` | The explicit-ID capture adapter passes the extended `CaptureContentSourceRequest` to the same routing service | Behavior is unchanged without a key; additive change | +| `POST /v1/source-observations` | The observation adapter passes the extended `SubmitSourceObservationRequest` to the same service and routes the materialized business Source with its actual `source_type` | Behavior is unchanged without a key; additive change | +| `SourceRecord` | Add optional `subject_projection` containing the Root and Root Source addresses while retaining existing `receipt_identity` | Old clients may ignore the new field | +| Source Create on a Root Scope | Require the `subject_key` matching the Root mapping; internal projections are exempt | Ordinary Scope behavior is unchanged; adds Root-boundary validation | +| `PUT /v1/scopes/{scope_id}` | When the target is a registered user Root, forbid changing `parent_scope_id` to a non-null value | Request shape is unchanged; adds a Root-invariant conflict | +| `BaseArtifactFamily` | Add `profile` for generic Artifact read addresses and responses | Additive change | +| `CreateArtifactRequest` / `ReplaceArtifactRequest` | Do not add a Profile union branch; generic Artifact Create/Replace rejects `family=profile` in v1 | Existing write unions and family-owned ID derivation remain unchanged | +| Generic Artifact Get Head, Get Revision, and List | Accept `family=profile`; content remains a `ProfileContent` object | Paths and response shape are unchanged | +| `CandidateFamily` | Add `profile` to the enum | Additive change | +| `ArtifactCandidate.proposal` / `ReviseArtifactCandidateRequest.proposal` | Add `ProfileContent` to the wire union; add `ProfileContent` to Runtime `ReviewedProposal` | Additive discriminator branch | +| `/v1/artifact-candidates/list|get|approve|reject|revise` | Support a complete-Markdown Profile Candidate; generic Reject gains optional `disposition`, which is mandatory after the server loads a Profile Candidate; Approve/Reject atomically coordinates Cursor, Pending, window metadata, and the Policy pointer | Paths are unchanged; the Profile branch adds atomic side effects | +| `GET /v1/capabilities` | Include `profile` in `artifact_families` and add the `profile_generation` capability | Additive change | + +Except for the Root Parent protection and optional Source projection information in this table, the semantics of Scope, +exact Source identity, Artifact identity, ETag, Revision, and Candidate status do not change. The first release still +adds no Source Update; callers express new facts or corrections by creating another Source. + +`CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest` are three distinct wire +schemas and all gain the same optional `subject_key` and `root_contributor`. Their HTTP adapters and corresponding Runtime, Python Client, +Connector, and MCP call paths dispatch through `SubjectSourceRoutingService`. Internal `lineage_only` provenance +Sources, Artifact-domain Sources, processor-created Sources, and the Root copy created inside the routing service do not +accept `subject_key` and must not recursively re-enter routing. + +Source Create and exact Source Get currently share `SourceRecord`. Therefore, adding an optional field to +`SourceRecord` means that both operations receive the additive field. Reading an Origin Source may return its projection +relationship; reading a Root Source may return its Origin. If an implementation wants only Create to return the receipt, +it must add `CreateSourceResponse` and change the `201` response type from `SourceRecord`; it cannot change only the +server response without updating OpenAPI. The code block above is an explicit `SourceRecord` delta and retains the +existing optional `receipt_identity` field. + +Although the Candidate database tables are family-neutral, current wire `ArtifactCandidate.proposal`, +`ReviseArtifactCandidateRequest.proposal`, Runtime `ReviewedProposal`, and Review Service branches handle only +Experience and Skill. All four must add `ProfileContent`. The Review Service loads the Candidate before validating an +optional Reject `disposition`, requires it for Profile, forbids it for other families, and dispatches approval through +the Profile service to the resolved `profile:user` or `profile:local` identity with the same Head CAS. Extending only +`CandidateFamily` is insufficient. + +Existing non-HTTP configuration and Python assembly also receive additive changes: + +| Location | Change | +| --- | --- | +| Runtime configuration | Add Profile Cron, IANA time zone, Window limit, concurrency, and timeout settings; existing Memory/Experience interval settings remain unchanged | +| Scheduler assembly | Add `configure_profile_generation_job` and a CronTrigger with its own time zone; reuse `powercontext_scheduler_jobs` instead of substituting a daily 86,400-second Interval | +| Artifact registry / Profile service | Register the `Profile` content codec and a Profile-only adapter that resolves the fixed scoped identity before calling internal `RecordService` and CAS primitives; do not register Profile in generic Create/Replace request unions | +| System provenance Source target | Allow `family="profile"`; manual Create/Replace/Rollback preserves `lineage_only` Sources, while an automatic Profile Window filters them | +| Review Service | Extend `ReviewedProposal` and the wire proposal unions with `ProfileContent`; add Profile approval/rejection branches and coordinate them atomically with Cursor/Pending | +| Subject/Profile HTTP and Python adapters | Add new resolve, Profile lifecycle, processing, policy, and Subject Context adapters; add a metadata-aware Python response helper that preserves HTTP `ETag` | +| Subject Context composition | Add new Profile exact-read, Topic Memory, Skill, and Experience adapters plus cross-family conflict handling and `max_bytes` composition; these are new implementation work, not behavior supplied by existing Prepare Context | + +### New APIs + +PowerContext already uses operation-style POST endpoints. This RFC carries `subject_key` in the request body rather than +exposing the business user ID in the URL path and access logs. + +| New endpoint | Purpose | Success result | +| --- | --- | --- | +| `POST /v1/subjects/resolve` | Idempotently resolve or create `subject_key -> root_scope_id` | `200`; body `created` distinguishes outcomes | +| `POST /v1/profile/create` | Manually create the first complete Markdown Profile | `201` + `ETag`; `409` if it exists | +| `POST /v1/profile/get` | Get the current Head by `ProfileTarget` | `200` + `ETag` | +| `POST /v1/profile/changes` | List Revisions and generation metadata | `200` | +| `POST /v1/profile/diff` | Compare two Markdown Revisions | `200` unified/structured line diff | +| `POST /v1/profile/replace` | Manually submit complete Markdown with the current Head's `If-Match` | `200` new Revision + `ETag` | +| `POST /v1/profile/rollback` | Copy old content into a new Head Revision with the current Head's `If-Match` | `200` new Revision + `ETag` | +| `POST /v1/profile/generate` | Request immediate processing of existing new Sources without waiting for an LLM | `200`; body status `accepted/idle/review_pending` | +| `POST /v1/profile/processing/get` | Read journal head, Cursor, Pending, and latest result | `200` | +| `POST /v1/profile/policy/get` | Read the automatic/Review Policy | `200` | +| `POST /v1/profile/policy/update` | Update the Policy using its expected version | `200` | +| `POST /v1/subjects/context/prepare` | Resolve the Root and aggregate authorized Artifacts in the Root and its true descendants | `200` | + +Every operation has exactly one success status because the current OpenAPI generator requires one 2xx response per +operation. Resolve always uses HTTP `200` and the body carries `created: bool`. Generate always uses HTTP `200` and the +body carries `status: accepted | idle | review_pending`. Profile Create has the single success status `201`; Profile Get, +Changes, Diff, Replace, Rollback, Processing Get, Policy Get/Update, and Subject Context Prepare each have the single +success status `200`. + +Profile review reuses the existing Artifact Candidate list/get/approve/reject/revise endpoints rather than creating a +second review state machine. The existing Reject request retains `scope_id`, `candidate_id`, `expected_version`, and +`reason`, and gains an optional wire field named `disposition`. After loading the Candidate under version CAS, the +server requires `disposition` for `family="profile"` and rejects it for every other family. This keeps one request schema +without weakening the existing concurrency contract. + +```python +from typing import Annotated, Literal, TypeAlias + +from pydantic import BaseModel, ConfigDict, Field + +# Wire proposal unions after this RFC. +CandidateProposal: TypeAlias = ExperienceProposal | SkillProposal | ProfileContent +# ArtifactCandidate.proposal: CandidateProposal +# ReviseArtifactCandidateRequest.proposal: CandidateProposal + + +# Runtime union after transport mapping. +ReviewedProposal: TypeAlias = ExperienceContent | SkillContent | ProfileContent + + +class RejectArtifactCandidateRequest(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + scope_id: str + candidate_id: str + expected_version: Annotated[int, Field(ge=1)] + reason: Annotated[str, Field(min_length=1, max_length=2_000)] + disposition: Literal["reject_and_consume", "reject_and_retry"] | None = None +``` + +`ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, transport mapping, Runtime +`ReviewedProposal`, Candidate repository validation, and `ReviewService` approve/reject/revise dispatch all gain the +Profile branch together. A Profile revision request still submits a complete `ProfileContent`; approval commits that +exact reviewed proposal through the Profile service. + +For example, when a reviewer determines that the window should not change the Profile: + +```json +{ + "scope_id": "R_U1", + "candidate_id": "candidate_profile_01", + "expected_version": 1, + "reason": "This content is a one-time request and should not become part of the long-lived Profile", + "disposition": "reject_and_consume" +} +``` + +### Resolve Subject Root + +```http +POST /v1/subjects/resolve +Content-Type: application/json +``` + +```json +{ + "subject_key": "U1", + "create_if_absent": true, + "origin_scope_id": "S_GROUP", + "root_contributor": {"type": "user", "id": "principal-u1"} +} +``` + +```json +{ + "subject_key": "U1", + "root_scope_id": "R_U1", + "created": true +} +``` + +Once created, a Root mapping cannot be rebound. If `create_if_absent=false` and no mapping exists, the endpoint returns +`404`. Both the existing and newly created cases return HTTP `200`; callers inspect `created`. Creating the mapping +requires `server.admin` or the trusted provisioning service Principal and atomically creates the Root Scope, mapping, +default Policy, and `root_contributor` binding. Merely knowing `subject_key` never identifies the Principal receiving +that binding. + +### Create Source with subject_key + +```http +POST /v1/scopes/S_GROUP/sources +Content-Type: application/json +``` + +```json +{ + "source_type": "content", + "content": { + "role": "user", + "text": "Please give me the concise conclusion first" + }, + "subject_key": "U1" +} +``` + +```json +{ + "scope_id": "S_GROUP", + "source_type": "content", + "source_id": "source_01", + "content": { + "role": "user", + "text": "Please give me the concise conclusion first" + }, + "position": 101, + "content_digest": "sha256:...", + "subject_projection": { + "subject_key": "U1", + "root_scope_id": "R_U1", + "origin_source": { + "scope_id": "S_GROUP", + "source_type": "content", + "source_id": "source_01" + }, + "root_source": { + "scope_id": "R_U1", + "source_type": "content", + "source_id": "source_01" + }, + "status": "committed" + } +} +``` + +`201` means both Sources and the projection relationship have committed; it does not mean that a Profile has been +generated. `subject_projection` always uses `origin_source` and `root_source` to make direction explicit and returns the +same address pair when either side of the relationship is read. + +The idempotency guarantee covers only one server-side operation and retries of its database transaction: the server +reuses the Source ID it has already generated and does not insert a duplicate Root Source. The current HTTP Create +Source endpoint has no `Idempotency-Key`. If a client retries the HTTP request after the commit succeeded but its +response was lost, the retry still creates a new Source and a new Root copy. A general HTTP-create idempotency design +belongs in a separate RFC; this design does not implicitly broaden the current semantics. + +### Get Profile + +```http +POST /v1/profile/get +Content-Type: application/json +``` + +```json +{ + "target": {"subject_key": "U1"} +} +``` + +```http +HTTP/1.1 200 OK +ETag: "profile:R_U1:profile:user:12:sha256-abc" +Content-Type: application/json +``` + +```json +{ + "target": { + "scope_id": "R_U1", + "artifact_id": "profile:user", + "subject_key": "U1", + "root_scope_id": "R_U1" + }, + "artifact": { + "scope_id": "R_U1", + "artifact": { + "family": "profile", + "artifact_id": "profile:user", + "revision": 12 + } + }, + "media_type": "text/markdown", + "content": "# User Profile\n\nThe user prefers concise answers in Chinese.\n", + "content_digest": "sha256:...", + "generation": { + "mode": "automatic", + "source_after": 37, + "source_through": 42, + "created_at": "2026-09-07T02:04:18+08:00" + } +} +``` + +The Profile-specific response flattens internal `ProfileContent.content` into a Markdown string. General Artifact Get +continues to return the complete `ProfileContent` object. The HTTP body is `ProfileRecord`; the Python Client returns +`ProfileResponse(record=profile_record, etag='"profile:R_U1:profile:user:12:sha256-abc"')` after reading the response +header. For a Scope-local Profile, `target.subject_key` and `target.root_scope_id` are JSON `null`, while `artifact` +remains a complete `ArtifactAddress` for `profile:local`. + +### Create, replace and rollback + +First manual creation: + +```python +created: ProfileResponse = await client.profile.create( + target=ProfileTarget(subject_key=app_user.user_id), + content="# User Profile\n\nThe user prefers answers in Chinese.\n", + reason="user confirmed initial profile", +) +``` + +Replace must echo the opaque ETag from Get/Create unchanged. The Python Client maps `if_match` to the HTTP `If-Match` +header: + +```python +updated: ProfileResponse = await client.profile.replace( + target=ProfileTarget(subject_key=app_user.user_id), + content="# User Profile\n\nThe user prefers concise answers in Chinese.\n", + if_match=created.etag, + reason="user edited profile", +) +``` + +Rollback creates a new Revision: + +```python +restored: ProfileResponse = await client.profile.rollback( + target=ProfileTarget(subject_key=app_user.user_id), + restore_revision=3, + if_match=updated.etag, + reason="restore user-confirmed version", +) +``` + +Profile Replace and Rollback return `428 Precondition Required` when `If-Match` is absent and +`412 Precondition Failed` when it does not match the current Head's ETag. The ETag must remain opaque; a client cannot +construct it from the Revision. Profile Create, Get, Replace, and Rollback all expose the current Head's `ETag`; the +Profile-specific metadata-aware Python helper returns it without requiring callers to use the low-level HTTP response. + +### Generate now + +```python +receipt = await client.profile.generate( + target=ProfileTarget(subject_key=app_user.user_id), +) +``` + +```json +{ + "status": "accepted", + "scope_id": "R_U1", + "binding_name": "profile-source-window", + "source_through": 42, + "flush_generation": 8 +} +``` + +This endpoint only asks processing to begin immediately for new Sources that already exist. With no new Source, it +returns HTTP `200` with `{"status":"idle", ...}`. If an automatic Candidate is already pending, it returns HTTP `200` +with `status="review_pending"` and its `pending_candidate_id`. `accepted` also uses HTTP `200`; none of these states uses +`202`. + +### Subject context aggregation API + +```http +POST /v1/subjects/context/prepare +Content-Type: application/json +``` + +```json +{ + "subject_key": "U1", + "query": "Recommend a hotel suitable for the user", + "families": ["profile", "memory", "topic-memory", "skill", "experience"], + "max_bytes": 262144 +} +``` + +```json +{ + "subject_key": "U1", + "root_scope_id": "R_U1", + "scope_ids": ["R_U1", "S_U1_PROJECT"], + "items": [ + { + "address": { + "scope_id": "R_U1", + "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} + }, + "content": "# User Profile\n\nThe user prefers concise answers in Chinese.\n", + "selected_bytes": 67 + }, + { + "address": { + "memory": { + "scope_id": "S_U1_PROJECT", + "artifact": {"family": "memory", "artifact_id": "memory", "revision": 7} + }, + "entry_id": "hotel-preference", + "entry_version_id": "mev_01" + }, + "content": "For hotels in China, the user prefers a king room.", + "selected_bytes": 53 + } + ], + "conflicts": [ + { + "summary": "Budget information conflicts across time", + "left": { + "scope_id": "R_U1", + "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} + }, + "right": { + "scope_id": "S_U1_PROJECT", + "artifact": {"family": "topic-memory", "artifact_id": "travel", "revision": 4} + } + } + ], + "used_bytes": 120, + "max_bytes": 262144, + "truncated": false +} +``` + +The server resolves `R_U1`, selects the Root and true descendants after authorizing each Scope, then performs +family-specific recall, exact deduplication, semantic deduplication, conflict annotation, ranking, and `max_bytes` +composition. This is a new `SubjectContextAdapter` plus new HTTP/Python adapters; it does not mean the existing Prepare +Context path already traverses Subject Roots. Every Artifact is exposed through the cross-Scope `ArtifactAddress`, +which is its globally complete address; a Memory Entry or another subresource uses a family-owned address containing +an `ArtifactAddress`. The shared group chat `S_GROUP` is not included merely because U1 participates, and existing +Artifacts in that Scope are not automatically copied in the first release. + +If a future Artifact Family reuses this design, it should register its own processing binding for Root Sources and +generate user-level Artifacts into `R_U1` or a true child Scope. They then naturally enter the same subject query range +without adding `subject_key` to the general Artifact table. + +## Access control and privacy + +The implementation reuses the existing `scope.*` and `artifact.*` actions from +[RFC 1396](1396_handoff_access_control.md). It adds no `subject.*` or `profile.*` action vocabulary: + +```python +ARTIFACT_FAMILY_PROFILES["profile"] = ArtifactFamilyAccessProfile( + family="profile", + enabled=True, + share_unit="artifact", + shareable_states=frozenset({"committed"}), + base_action=AccessAction.ARTIFACT_READ, + additional_actions=frozenset(), + grantable_roles=frozenset({AccessRole.ARTIFACT_VIEWER}), + selector="forbidden", + transitivity="none", + mutation_semantics=frozenset({AccessAction.ARTIFACT_WRITE}), +) +``` + +Thus the exact access contract is: enabled family, whole-Artifact share unit, only `committed` state shareable, +`artifact.read` base action, `artifact.viewer` grantable role, no selector, no transitivity, and `artifact.write` mutation +semantics. A pending Candidate is not a committed Profile Artifact and remains governed by `scope.review`. + +| Profile/Subject operation | Existing action | +| --- | --- | +| Resolve an existing Subject Root | Require `scope.read` on the Root before returning the mapping; insufficient authorization always returns `403` | +| Create a Subject Root | Require Origin `scope.contribute` plus either caller `server.admin` or invocation of the configured trusted provisioning service Principal; atomically create Root, mapping, Policy, and the explicit `root_contributor` / `scope.contributor` binding | +| Write a subject-keyed business Source | Always require Origin `scope.contribute`; for an existing Root, also require Root `scope.contribute`; first creation uses the bootstrap rule above | +| Profile Get, Changes, Diff | Require `artifact.read` on the logical Profile; discovery through a Scope list also requires `scope.read` | +| Manually create the first Profile or request Generate | Require `scope.contribute` on the target Scope; establish the owner through the existing Artifact flow after creation | +| Profile Replace, Rollback | Require a system-managed owner relation and `artifact.write` on the logical Profile | +| Review a Profile Candidate | Require `scope.review` on the target Scope | +| Profile Policy Get/Update | Get requires `scope.read`; Update requires `scope.admin` | +| Subject Context Prepare | Require `scope.read` on every included Scope and `artifact.read` for exact-resource authorization paths | + +Parent, Root mappings, and `subject_key` do not grant authorization. This RFC never derives a Principal from the business +`user_id`. During first-time bootstrap, the authenticated initiating Principal is recorded as the subject of the +explicit `root_contributor` binding with the existing `scope.contributor` role; a trusted provisioning service may +instead install the business Principal supplied through its authorized provisioning context. Root, mapping, default +Policy, and binding commit atomically. For an existing Root, the PEP must allow `scope.contribute` on both Origin and +Root before the dual write. Any denial or bootstrap failure prevents all Source and metadata writes. + +Profile must be registered in RFC 1396's Artifact Family Access Profile registry exactly as shown above. This adds no +Profile-specific action. A background Processor must run with its configured service/system Principal; an empty +Principal cannot execute generation. + +Privacy requirements: + +- logs, metrics, and errors do not include the raw `subject_key`, Source content, or Markdown by default; +- the database stores the business `user_id` directly as `subject_key`; reads, backups, and audits protect it according + to policies for user identifiers; +- a Root Source is a copy of original content and must use the same encryption, retention, and deletion policies as the + origin Source; +- a Root Scope title or summary does not contain a user ID; +- aggregation authorizes every Scope and Artifact and does not disclose the existence or count of unauthorized Scopes; +- review, edit, and rollback record the actor, time, reason, and target Revision. + +## Error semantics + +| Scenario | Recommended result | +| --- | --- | +| `subject_key` is empty or longer than 256 characters | `422 invalid_subject_key` | +| `subject_key` does not exist and Root creation is forbidden | `404 subject_root_not_found` | +| Root is absent and the calling Principal lacks Origin `scope.contribute` or required `server.admin` | `403 Forbidden` | +| `root_contributor.type` is not `user/service` | `422 invalid_root_contributor` | +| The Authorization Provider cannot create a Binding transactionally and no trusted provisioner is available | `503 relationship_management_unavailable` | +| Two keys attempt to bind the same Root | `409 subject_root_binding_conflict` | +| The current Scope is another user's Root | `409 subject_key_mismatch` | +| A public request writes a user Root without a key | `422 subject_key_required` | +| An Origin Source has already been projected to another key | `409 source_subject_conflict` | +| Origin and Root Sources have the same identity but different payloads | `409 source_projection_content_conflict` | +| Any step of the dual write fails | Roll back the whole transaction; leave no one-sided Source | +| Subject Resolve creates or finds a Root | Always `200 OK`; distinguish with `created` | +| Generate is called with no new Source | `200 idle` | +| An automatic Profile Candidate is already pending | `200 review_pending`; do not generate a duplicate | +| Profile processing has been awakened | `200 accepted` | +| Background LLM or validation fails | Preserve the old Head, do not advance the Cursor, and retry | +| Head or Cursor CAS conflicts | Reread the latest state and process again | +| Profile Create finds an existing Head | `409 profile_already_exists` | +| Replace/Rollback omits `If-Match` | `428 Precondition Required` | +| Replace/Rollback ETag does not match the current Head | `412 Precondition Failed` | +| The Head changed during Review | `409 profile_revision_conflict`; preserve the Candidate and do not advance the Cursor | +| Rollback target Revision does not exist | `404 profile_revision_not_found` | +| Root or child Scope is unauthorized | `403 forbidden` | + +## Configuration + +```yaml +profile: + enabled: true + artifact_id: "profile:user" + local_artifact_id: "profile:local" + max_content_bytes: 262144 + processing_binding: "profile-source-window" + schedule: + cron: "0 2 * * *" + timezone: "Asia/Shanghai" + source_window_limit: 200 + max_concurrency: 8 + worker_timeout_seconds: 900 + retry_max_delay_seconds: 1800 +``` + +Schedule is deployment-level configuration. `generation_enabled` and `activation_mode` are Scope-level Policy. The +first release does not expose an individual Cron schedule for each user, avoiding a separate scheduler job for every +user; one daily wave processes all dirty targets fairly. + +## OpenAPI impact + +`openapi/powercontext.yaml` is the source of truth for the contract. Implementation must make the following changes and +regenerate code: + +1. Accept `profile` in exact generic Artifact Get, Get Revision, List, Artifact response, and capability schemas while + keeping the generic `CreateArtifactRequest` and `ReplaceArtifactRequest` unions unchanged; their endpoints reject + Profile writes in v1. +2. Add `profile` to `CandidateFamily` and register the exact `ArtifactFamilyAccessProfile` defined above. +3. Add optional `subject_key` and `root_contributor` to `CreateSourceRequest`, `CaptureContentSourceRequest`, and + `SubmitSourceObservationRequest`. +4. Add optional `subject_projection` to `SourceRecord` without removing existing `receipt_identity`. +5. Keep `ArtifactRevision.content` as an object rather than changing it to a raw string. +6. Add `ProfileContent` to `ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, transport mapping, + and Runtime `ReviewedProposal`; add optional `disposition` to the existing Reject request and require it for Profile + after Candidate lookup. +7. Expose the readable `profile` family, `profile_generation`, and the Subject Context adapter capability through + Capabilities. +8. Define `ETag` response headers for Profile Create/Get/Replace/Rollback and an `If-Match` request header for + Replace/Rollback; preserve `428/412` for missing or mismatched preconditions. +9. Give every new operation exactly one 2xx response: Resolve and Generate both use `200`, with `created` or `status` in + the body. +10. Add Subject resolve/context prepare and Profile create/get/changes/diff/replace/rollback/generate/processing/policy + operations, including pagination, `ArtifactAddress`, conflict, and `max_bytes` schemas. +11. Generate metadata-aware Python transport helpers for Profile Create/Get/Replace/Rollback so their high-level sync + and async methods return `ProfileResponse(record, etag)`. +12. Continue generating checked-in sources through `make api-generate`; do not edit + `src/powercontext/http/_generated/` manually. + +## Implementation plan + +1. Add the Profile family, `ProfileContent` codec, fixed-identity Profile service, and Markdown normalization; exact + generic reads support Profile, while generic Artifact Create/Replace does not. +2. Add `pc_subject_roots`, implementing Root Resolve, uniqueness constraints, Root Parent protection, and atomic + authorization bootstrap with the explicit `root_contributor` binding. +3. Add the shared `SubjectSourceRoutingService` and route `CreateSourceRequest`, `CaptureContentSourceRequest`, and + `SubmitSourceObservationRequest` through it so every business Source entry point carrying a `subject_key` performs + dual-Scope locking, the dual Source write, projection recording, and Pending upsert in one transaction. Exclude + internal lineage/domain Sources from routing. +4. Implement or reuse general Pending, Cursor, Lease, and Artifact Processing Supervisor support. +5. Add a time-zone-aware Profile CronTrigger, defaulting to `02:00 Asia/Shanghai` daily. +6. Implement the Profile Worker: fixed Window, read-before-write, LLM Markdown, NOOP, and Head/Cursor CAS. +7. Add Revision Metadata, Candidate Window Metadata, the single pending pointer in Policy, complete-Markdown Candidate + unions, and Profile-aware Review Service branches. +8. Implement Profile convenience HTTP adapters, metadata-aware Python sync/async clients, history, Diff, manual + replacement, rollback, and ETag propagation. +9. Implement the authorized aggregation endpoint and new family composition adapters over the Subject Root range, + returning cross-Scope `ArtifactAddress` values under the request's `max_bytes` budget. +10. Add tests for concurrent first Resolve, authorization bootstrap, dual-write atomicity, group-chat isolation, + scheduler recovery, one-success-status OpenAPI generation, ETag preservation, Candidate Reject dispositions, + failure retry, Review, and rollback. + +## Acceptance criteria + +### Scope and identity + +- U1, U2, U3, and one group chat produce exactly four Scopes: `R_U1/R_U2/R_U3/S_GROUP`. +- The group-chat Scope is not automatically set as any user Root's child or context reference. +- Concurrent Resolve operations for one `subject_key` produce only one Root. +- First Resolve requires Origin `scope.contribute` plus `server.admin` or the trusted provisioning service Principal and + atomically creates Root, mapping, Policy, and the explicit `root_contributor` / `scope.contributor` binding. +- `subject_key` never derives or authenticates a Principal; an existing Root requires `scope.contribute` on both Origin + and Root. +- Different `subject_key` values cannot map to the same Root. +- A Root's Parent is always `NULL`. +- Accessing the Profile through `subject_key=U1` or `scope_id=R_U1` normalizes to the same `profile:user`; callers cannot + create `profile:local` in the Root. +- Profile content and identity use only `subject_key`, `root_scope_id`, and the fixed Profile Artifact address; they add + no second user identifier or Profile-type field. + +### Source routing + +- Without `subject_key`, every business Source entry point preserves its existing persistence behavior. +- `CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest` all accept the optional key + and use the same routing service; internal lineage/domain Sources do not accept it. +- With `subject_key`, exactly two Sources are written: one Origin and one corresponding Root Source. +- Both Sources have identical payloads, while each Scope assigns its journal position independently. +- A failure at any step leaves no one-sided write. +- A U1 Source does not change the journal, Pending, or Cursor for the U2/U3 Roots. +- A database-transaction retry of the same server operation does not create a duplicate Root Source; a new HTTP Create + request still creates a new Source under existing semantics. +- Multi-user batch content cannot be written as one subject-keyed Source. + +### Profile content and revision + +- Profile content consists only of complete Markdown; no Claim category, Claim table, or per-Claim risk level exists. +- `ProfileContent` encodes Markdown into the existing BLOB; the existing Artifact tables require no DDL change. +- A Root has only one `profile:user` Head, and `artifact_id` is part of its unique identity. +- Create conflicts when a Head exists; Replace uses CAS. +- Profile Create/Get/Replace/Rollback expose HTTP `ETag`; Python returns `ProfileResponse(record, etag)` and preserves + the opaque header for `If-Match`. +- Generic Artifact Create/Replace does not accept Profile in v1; exact generic Get/List/Get Revision does. +- Automatic generation, manual editing, approval, and rollback all create immutable Revisions. +- No semantic change creates no empty Revision. + +### Automatic generation + +- Processing starts at `02:00 Asia/Shanghai` daily by default, with configurable Cron and time zone. +- Committing a business Source does not wait for an LLM. +- The Scheduler recovers one coalesced wave after a missed time. +- A Worker freezes an `(after, through]` Window. +- A Worker excludes `lineage_only` system Sources; a window empty after filtering skips the LLM but may still advance + the Cursor. +- The same Profile is processed serially; different Profiles run in parallel within the configured concurrency limit. +- A failure does not advance the Cursor or affect another user. +- Scheduled and manual Generate do not rebuild without a new Source. +- Resolve and Generate each expose exactly one HTTP success status (`200`); Generate distinguishes + `accepted/idle/review_pending` in the body. + +### Review and correction + +- The complete Profile activates automatically by default. +- Policy can switch the complete Profile to `review_required`. +- Candidate review reuses the existing Candidate state machine. +- `ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, Runtime `ReviewedProposal`, and Review Service + all support complete `ProfileContent`. +- Each Profile Scope has at most one pending automatic Candidate, whose Source Window can be recovered after restart. +- Reject requires an explicit `reject_and_consume` or `reject_and_retry`, with tests that respectively advance or + preserve the Cursor. +- Manual Replace and Rollback must use the current Head's opaque `ETag` as `If-Match`. +- Rollback creates a new Revision; it neither deletes history nor moves the Head backward. +- Human confirmation applies only to the complete Revision/Head through `generation_mode`; no paragraph-level trust is + inferred. + +### Database and API inventory + +- Every new table has primary keys, uniqueness constraints, foreign keys, and idempotency semantics. +- `restored_from_revision` has an exact Artifact Revision foreign key, and generation-mode, generator/window, rollback, + and Candidate binding fields have explicit CHECK constraints. +- The existing-table change matrix explicitly records that there are no physical DDL changes. +- OpenAPI enums, unions, Source schemas, and all new operations have contract tests. +- Python SDK examples cover Resolve, the dual Source write, and Profile Get/Replace/Rollback/Generate. +- Subject Context enforces its `max_bytes` budget and returns complete `ArtifactAddress` values for results and + conflicts. + +## Decision summary + +1. Add the `profile` Artifact Family, supporting only user Profiles in the first release. +2. Use the caller's business `user_id` directly as `subject_key`; support no other subject type initially. +3. Map one `subject_key` one-to-one to one `root_scope_id`; the Root is an ordinary Scope whose Parent is always `NULL`. +4. A group chat with U1, U2, and U3 uses four Scopes including the shared group-chat Scope; the shared Scope belongs to + no user Root subtree. +5. Persist each subject-keyed Source exactly twice: the original Source in the business Scope and the Root Source in the + corresponding user Root, committed in one transaction. +6. Do not add `subject_key` to existing Source or Artifact tables; use new mapping and projection tables. +7. Use the fixed `(root_scope_id, profile, profile:user)` identity in a user Root; an ordinary Scope may explicitly + enable `profile:local`. +8. Profile content is complete Markdown encoded through `ProfileContent.content` into the existing BLOB; define no + Claim categories, per-Claim risks, or Claim table. +9. Generate in the background at `02:00 Asia/Shanghai` daily by default, with configurable Cron and time zone; Manual + Generate processes only existing new Sources. +10. Trigger automatic updates only from a new Source Window; no new Source means no rebuild, and no semantic change + means no new Revision. +11. Activate the entire Revision automatically by default, with per-Profile-Scope `review_required` configuration. +12. Manual creation, replacement, approval, and rollback all create immutable Revisions; Create/Get/Replace/Rollback + return `ETag`, and Replace/Rollback use `If-Match`. +13. Add `pc_subject_roots`, `pc_subject_source_projections`, `pc_profile_policies`, + `pc_profile_revision_metadata`, and `pc_profile_candidate_metadata`; if the general processing substrate has not + landed, also add `pc_artifact_processing_pending` and `pc_artifact_processing_leases`. +14. Make no physical DDL change to existing tables including `pc_scopes`, `pc_sources`, `pc_artifacts`, Heads, Lineage, + Cursor, and Candidates. +15. Extend the three general business Source requests, Candidate proposal unions, and Capabilities additively; do not + add Profile to the generic Artifact write unions. Route every business Source entry point carrying `subject_key` + through the shared subject-routing service, and add Subject and Profile convenience APIs. +16. Future Artifact Families may reuse Subject Root and Root Sources, but existing Artifacts in a shared Scope do not + automatically become cross-Scope. + +# Drawbacks + +- Each subject-keyed Source is stored twice, increasing storage, backup, retention, and deletion costs. +- The dual Source write expands a formerly single-Scope transaction to two Scopes, requiring consistent lock order and + stricter concurrency testing. +- The existing HTTP Source Create endpoint has no client idempotency key, so a request-level retry after a lost response + may still create duplicate facts and corresponding Root copies. +- Correct `subject_key` assignment depends on the caller; PowerContext does not merge accounts or correct a mistaken + identity. +- Daily generation means normal Profile latency can approach one day; applications needing an immediate result must + call Generate. +- A single Markdown document simplifies storage and reading but gives up Claim-level queries, risk classification, and + fine-grained provenance in the first release. +- Existing Artifacts in a shared Scope do not automatically become user-level artifacts; another family must explicitly + consume Root Sources and generate into the Root. +- Root copies of original Source content expand the privacy and forgetting surface. + +# Rationale and alternatives + +## Why Subject Root is not the group Scope parent + +A Scope has only one Parent, while a group chat can have many users. Attaching the shared Scope to any one user would +misrepresent organizational ownership; attaching it to multiple users cannot be represented by the current model. This +RFC therefore expresses the subject relationship through Source projection and reserves Parent for genuine +organization. + +## Why subject_key is family-neutral + +In the first release, `subject_key` equals the business `user_id` directly; it introduces neither an opaque key nor a +second identity. The `subject` name allows future families such as Memory, Topic Memory, and Experience to reuse the same +Root addressing and Root-local Sources without each defining another user key. + +## Why a ProfileContent wrapper instead of raw BLOB bytes + +The current Artifact Repository requires family content to be a Pydantic Model, and general +`ArtifactRevision.content` is an object. Encoding Markdown into the existing BLOB through `ProfileContent` preserves +both the shared tables and the general response shape. Writing raw Markdown bytes would require changes to the Artifact +Repository codec, runtime records, and the OpenAPI response union, which the first release does not need. + +## Why a daily Cron plus manual Generate + +Daily off-peak batching coalesces frequent Sources and reduces LLM call volume and concurrency pressure. Manual Generate +provides an explicit escape hatch for applications that need a Profile immediately. The default time is operational +policy rather than Source or Artifact semantics, so deployments may change it. + +## Why no Claim categories + +The primary first-release consumer needs a human-editable Profile document that can be injected directly into context. +Splitting content into fixed Claim categories expands extraction, schema, migration, and review complexity. Complete +Markdown is a better way to validate user value first. If structured retrieval becomes necessary, a rebuildable index +can be derived from Artifact Revisions without changing the fact source or artifact identity. + +# Prior art + +Existing PowerContext designs provide reusable foundations for this RFC: + +- [RFC 0019](0019_local_source_memory_runtime.md) defines Source journals, consumption Cursors, and local Runtime + transaction boundaries; +- [RFC 0050](0050_artifact_candidate_review_inbox.md) defines immutable Candidates and the review state machine; +- the [Topic Memory RFC](0000_topic_memory.md) defines general Artifact processing Pending, leases, Supervisor, and fixed + Source Windows; +- [RFC 1345](1345_scope_organization_and_agent_integration.md) defines Scope organization, isolation, and sharing; +- [RFC 1437](1437_source_artifact_rest_api.md) defines public Source and Artifact identity, Create, Replace, and Revision + APIs. + +This RFC reuses those mechanisms instead of creating a second Source, Artifact, Candidate, or background-task identity +space for Profile. + +The [official TencentDB Agent Memory README](https://github.com/Tencent/TencentDB-Agent-Memory/blob/main/README.md) +describes layered long-term memory and Persona processing. The +[official OpenViking Session documentation](https://github.com/volcengine/OpenViking/blob/main/docs/en/concepts/08-session.md#memory-extraction) +describes asynchronous Memory Extraction, the user memory namespace, and `profile.md`. These specific designs informed +the engineering choices around layered background processing, checkpoints, user Roots, and updating after reading an +existing Profile. + +This RFC borrows only their engineering ideas around asynchronous processing, cursors, and incremental generation after +reading the old Profile; it does not reuse their identity models. This document independently defines PowerContext's +`subject_key <-> root_scope_id`, shared-Scope dual writes, and authorization boundary. + +# Unresolved questions + +The first-release feature and identity model are decided. Before the RFC merges, the minimum consistent-deletion +semantics for a Root Source and its Origin Source must still be specified: deleting or forgetting either side must use +`pc_subject_source_projections` to find and process the other side in the same authorized operation, so the Profile +cannot later consume a copy that the user requested to forget. Physical deletion, logical tombstones, retention of +generated Revisions, and audit rules must align with the project's unified data-deletion protocol. + +The following questions do not block this RFC and should be designed separately after concrete requirements emerge: + +- anonymous-to-registered user conversion, account aliases, account merging, and `subject_key` migration; +- cross-request `Idempotency-Key` support for HTTP Source Create; +- a Claim-level query, citation, or risk-analysis index derived from Profile Revisions; +- how Artifact Families other than Profile select and consume Subject Root Sources. + +# Future possibilities + +Future Artifact Families may register their own Root-local Source processing bindings and derive user-level Memory, +Topic Memory, Experience, or Skill into the Subject Root and its true child Scopes without changing the general identity +of `pc_sources` or `pc_artifacts`. Each Family's own design should decide whether to enable this derivation. + +Profile Markdown may produce a rebuildable structured retrieval index for paragraph-level recall, conflict prompts, or +evidence location. Such an index must always derive from immutable Profile Revisions and exact Source lineage. It must +not become another source of truth or change the single-Markdown content contract of Profile. + +Subject Context aggregation may evolve family quotas, conflict explanations, progressive expansion, and observability, +but it must preserve per-Scope and per-Artifact authorization and the boundary that participation does not automatically +place a shared business Scope in a user's Root subtree. + +After general Source-create idempotency, subject migration, and data-forgetting protocols each become stable, Subject +Root routing can reuse those capabilities to further reduce the operational cost of network retries, account lifecycle, +and original-content duplication. diff --git a/docs/zh/rfcs/0000_profile_artifact.md b/docs/zh/rfcs/0000_profile_artifact.md new file mode 100644 index 0000000000..c6cd28e6fb --- /dev/null +++ b/docs/zh/rfcs/0000_profile_artifact.md @@ -0,0 +1,1791 @@ +- Proposal Name: `profile_artifact` +- Start Date: 2026-09-07 +- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), + [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), + [RFC 1345](1345_scope_organization_and_agent_integration.md), + [RFC 1396](1396_handoff_access_control.md),以及 [RFC 1437](1437_source_artifact_rest_api.md) + +# Summary + +本 RFC 为 PowerContext 增加 `profile` Artifact Family。首期只设计固定的用户画像,不提供画像类型字段、其他画像类型或 Profile Schema Registry。 + +画像是由 Source 派生的、可重建的完整快照,不是事实源。用户画像使用固定地址: + +```text +Head identity: +(root_scope_id, family="profile", artifact_id="profile:user") + +Exact revision identity: +(root_scope_id, family="profile", artifact_id="profile:user", revision) +``` + +`subject_key` 是调用方在业务 Source 写入时直接传入的业务 `user_id`。PowerContext 不生成另一套用户标识,也不解释、 +拼接或归一化该值。命名为 `subject_key`,是为了让 `subject_key -> root_scope_id` 的主体寻址和 Source 投影机制将来可被 +其他 Artifact Family 复用;首期主体仍固定为用户。 + +Scope 组织采用唯一方案: + +- 每个 `subject_key` 一一对应一个用户 Root Scope; +- 共享业务 Scope 不挂到任一用户 Root 下; +- 带 `subject_key` 的 Source 在同一事务内写入业务 Scope 和该用户 Root Scope,总共保存两条 Source 记录; +- Profile Processor 只消费 Root Scope 内的 Source journal,因此不同用户互不触发; +- 没有 `subject_key` 的普通 Scope 仍可显式启用 Scope-local Profile。 + +Profile 不再拆分 Claim category、Claim 行或风险等级。LLM 输出完整 Markdown,作为 `ProfileContent.content` 保存到现有 `pc_artifacts.content` BLOB。自动生成默认每天 `02:00` 执行,使用部署配置的 IANA 时区,默认 `Asia/Shanghai`;调用方可以修改 Cron 与时区,也可以请求立即生成。 + +# Motivation + +面向用户的 Agent 需要跨会话、跨任务和跨业务 Scope 使用同一份长期画像。仅在原业务 Scope 内生成画像会导致同一个用户在多个 Scope 中形成多份画像;直接给所有 Source 和 Artifact 增加 `user_id` 列,又会把存储归属、内容主体、内容产生者和权限主体混为一谈。 + +多人会话进一步说明了这种区别。一个群聊 Scope 可以同时包含 U1、U2、U3 的发言,但 `pc_scopes.parent_scope_id` 只有一个值,群聊 Scope 不可能同时成为三个用户 Root 的子 Scope。正确做法是保留群聊 Scope 的原始组织关系,把每个用户自己的 Source 精确复制到自己的 Root,再在 Root 中生成用户画像。 + +本设计把通用 Source、Scope 和 Artifact 保持为事实与制品基础设施,只增加一套窄化的主体路由便利能力。接入方仍负责决定业务用户、会话和 Source 如何对应;PowerContext 负责稳定解析 Root、可靠双写 Source、后台生成画像和维护 Revision。 + +## Goals + +1. 新增 `profile` Artifact Family,复用现有 Artifact Head、Revision、Lineage 和 CAS 语义;写入由 Profile 专用入口 + 调用内部 RecordService,不扩展通用 Artifact Create/Replace 的公开写入联合类型。 +2. 首期只支持固定用户画像;不设计画像类型扩展、Claim category 和逐 Claim 风险模型。 +3. 以调用方业务 `user_id` 作为 `subject_key`,建立不可变的一一映射 `subject_key <-> root_scope_id`。 +4. 支持共享 Scope 中不同用户的 Source,且一个用户的新 Source 只推进该用户 Root 的 journal。 +5. 将一条带 `subject_key` 的 Source 总共保存两份:原业务 Scope 一份、对应用户 Root 一份。 +6. 默认每天 `02:00` 后台生成画像,Cron 与时区可配置,不让业务 Source 写入入口等待 LLM。 +7. 将完整 Markdown 画像保存到现有 `pc_artifacts.content` BLOB,不增加 Claim 表或 Profile 内容列。 +8. 默认自动生效;允许按 Profile Scope 配置整篇 Revision 进入 Review。 +9. 支持人工创建、替换、审核、查看历史、比较差异和非破坏性回退。 +10. 明确全部新增表、新增接口、现有表用法和现有接口变更。 +11. 让未来 Artifact Family 可以复用 Subject Root 与 Root-local Source,但不在首期实现其他主体类型或其他制品的自动派生。 + +## Non-goals + +首期明确不包括: + +- `team`、`agent`、`customer`、`driver` 等其他画像类型; +- 自定义画像类型、主体类型、Profile Schema 注册或任意 Claim Schema; +- 用户注册、认证、账号别名、匿名转实名、账号合并和用户 ID 生成; +- 从自然语言中猜测 Source 属于哪个用户; +- 一条 Source 同时绑定多个 `subject_key`; +- 给 `pc_sources` 或 `pc_artifacts` 增加通用 `subject_key` 列; +- 把共享业务 Scope 自动挂到用户 Root,或把 Scope Parent 当作授权关系; +- 自动复制共享 Scope 内已有的 Memory、Skill、Experience、Topic Memory 等 Artifact; +- 没有新 Source 时,因模型、Prompt 或实现版本变化自动 rebuild 画像; +- 面向所有 Source 和 Artifact Family 的通用删除、撤回和遗忘协议;但 Origin/Root 双副本的最低一致清理语义必须在本 RFC 合并前确定; +- 为 Profile 以外的 Artifact Family 实现完整的主体派生生命周期。 + +# Guide-level explanation + +## Terminology and invariants + +| 名称 | 含义 | +| --- | --- | +| `subject_key` | 调用方直接传入的业务 `user_id`;首期只表示用户主体 | +| `root_scope_id` | PowerContext 为一个 `subject_key` 创建的普通 `pc_scopes.scope_id`,是该用户长期制品的稳定存储锚点 | +| 业务 Scope | 会话、群聊、项目或应用自己组织的 Scope;可以包含多个用户的 Source | +| Root Source | 从业务 Scope 复制到用户 Root 的同一条 Source;其内容与原 Source 完全一致 | +| Scope-local Profile | 不经过 `subject_key`,直接由普通 Scope 的 Source 生成的局部画像 | +| Profile Head | 一个 Scope 内固定 `artifact_id` 的当前画像 Revision | + +必须满足以下不变量: + +```text +one subject_key -> exactly one root_scope_id +one root_scope_id -> at most one subject_key + +one subject-keyed Source -> one origin Source + one Root Source +one origin Source -> at most one subject_key + +one user Root -> at most one Profile Head +``` + +`subject_key` 回答“这条 Source 归入哪个用户主体的数据”,不等于: + +- 谁当前登录; +- 谁拥有底层资源; +- 正文里提到了哪些用户; +- 谁有权读取 Root; +- Source 或 Artifact 的通用唯一键。 + +调用方必须保证 `subject_key` 在同一 PowerContext 部署、同一数据库范围内唯一、稳定且不复用。PowerContext 按完整字符串进行大小写敏感、字节精确比较。调用方应使用内部用户 ID,不应使用姓名、手机号、邮箱或身份证号等直接标识信息。 + +## Scope organization + +### Group chat example: exactly four Scopes + +群聊 G1 有 U1、U2、U3 三个用户时,共有 4 个 Scope: + +```mermaid +flowchart LR + K1["subject_key = U1"] --> R1["root_scope_id = R_U1"] + K2["subject_key = U2"] --> R2["root_scope_id = R_U2"] + K3["subject_key = U3"] --> R3["root_scope_id = R_U3"] + G["business scope_id = S_GROUP
U1 + U2 + U3 group chat"] + + G -. "U1 Source copy" .-> R1 + G -. "U2 Source copy" .-> R2 + G -. "U3 Source copy" .-> R3 +``` + +| Scope | 作用 | `parent_scope_id` | +| --- | --- | --- | +| `R_U1` | U1 的 Root Source、Profile 和未来用户级制品 | `NULL` | +| `R_U2` | U2 的 Root Source、Profile 和未来用户级制品 | `NULL` | +| `R_U3` | U3 的 Root Source、Profile 和未来用户级制品 | `NULL` | +| `S_GROUP` | 保存完整群聊原始记录 | 保持业务原有父关系;不指向 `R_U1/R_U2/R_U3` | + +图中的虚线表示 Source 投影关系,不是 `parent_scope_id`,也不是 `pc_scope_context_references`。本 RFC 不因用户参与群聊而自动写 Scope Parent 或 Context Reference。 + +### What a Root Scope records + +Root Scope 本身就是一条普通 `pc_scopes` 记录,不新增 `profile_root_scope` 表,也不把用户信息塞入 `pc_scopes.title` 或 `summary`: + +```text +pc_scopes + scope_id = R_U1 + title = "Subject Root" + summary = "用户主体数据根" + parent_scope_id= NULL + version = 1 +``` + +`subject_key=U1` 与 `R_U1` 的映射保存在新增的 `pc_subject_roots`。真正的内容分别保存在: + +- `pc_sources`:U1 从不同业务 Scope 投影来的 Source; +- `pc_artifacts` / `pc_artifact_heads`:U1 的 Profile Revision 与 Head; +- Lineage、Cursor、Pending、Policy 和 Profile Revision 元数据表。 + +Root Scope 是存储与聚合锚点,不是用户账号记录,不承担认证,也不自动授予访问权限。 + +### Parent rules + +1. 用户 Root 的 `parent_scope_id` 固定为 `NULL`。 +2. 已登记为 Root 的 Scope 不允许再通过 Scope Update 设置 Parent。 +3. 共享业务 Scope 保持自己的业务组织关系,不自动 reparent 到任何用户 Root。 +4. 业务确实拥有单用户子 Scope 时,可以由业务显式创建为某个 Root 的 descendant;该行为不是 Source Create 的副作用。 +5. 按 `subject_key` 聚合上下文时,默认选择 Root 及其真实 descendants;共享群聊 Scope 不在任一用户子树中。 + +### Source is stored exactly twice + +U1 在群聊中的一条 Source 写入后,数据库中总共存在两条内容相同的 Source: + +```text +(S_GROUP, source_type="content", source_id="source_01") # origin +(R_U1, source_type="content", source_id="source_01") # Root copy +``` + +Source identity 包含 `scope_id`,所以两条记录可以复用同一个 `source_type + source_id`。新路径先生成部署内唯一的 Source ID,再在两个 Scope 中复用同一个 `ContentSource`;因此两条记录的 `payload` 相同,但 `journal_position` 分别由 `S_GROUP` 和 `R_U1` 的 Source journal 分配。新增关系表记录两者的精确地址和内容摘要。 + +U1 的 Source 不写入 `R_U2` 或 `R_U3`;因此一次 U1 写入只会使 `S_GROUP` 与 `R_U1` 的 journal 前进。 + +例外:如果调用方直接在 `R_U1` 创建 `subject_key=U1` 的 Source,原 Scope 已经是目标 Root,只保存一条 Source,不做自我复制。 + +用户 Root 是受保护的主体存储边界。通过公开 Source Create 直接写 Root 时必须携带与映射一致的 `subject_key`;缺少 key 或 key 不一致都被拒绝,避免无法归属的 Source 污染全局画像。 + +### Multi-user Source boundary + +每次 Source Create 最多携带一个 `subject_key`。在群聊中,接入应用应按说话人或可独立归属的消息拆分 Source: + +```python +await client.sources.create( + scope_id="S_GROUP", + content={"role": "user", "text": "请优先给我简洁结论"}, + subject_key="U1", +) + +await client.sources.create( + scope_id="S_GROUP", + content={"role": "user", "text": "我希望看到详细分析"}, + subject_key="U2", +) +``` + +一个包含多名用户发言的批量 Source 必须先拆分;PowerContext 不让 LLM 猜测整份内容该归入哪个用户。没有 `subject_key` 的 Source 只保存在当前 Scope,不进入任何用户 Root;如果该普通 Scope 已通过 `pc_profile_policies` 显式启用 Scope-local Profile,同一 Source 事务还要 upsert 当前 Scope 的 `profile-source-window` Pending,使每日 Scheduler 能发现它。 + +### Root creation and authorization + +`subject_key` 永远不推导 Principal。调用 Principal 只来自认证 middleware 或可信 internal bridge;可选 +`root_contributor` 是请求明确指定的既有 `PrincipalRef`,省略时取调用 Principal,且类型只能是 `user` 或 `service`。 + +Root 不存在时,自动创建必须形成完整授权闭环: + +1. 调用 Principal 对 Origin Scope 必须拥有 `scope.contribute`。 +2. 同一个调用 Principal 还必须拥有 `server.admin`;部署也可以配置一个可信 provisioning service principal,由它在 + 内部承担 `server.admin`,但不能替代调用 Principal 对 Origin Scope 的 `scope.contribute`。 +3. 在同一协调事务中创建 `pc_scopes` Root、`pc_subject_roots` 映射、默认 `pc_profile_policies`,并通过 Access Control + RelationshipWriter 为明确的 `root_contributor` 建立 `scope.contributor` Binding。 +4. Binding 建立成功后,路由服务以内部分支完成首次 Root Source 写入、投影关系与 Pending;任一步失败都不提交 + Origin Source、Root 或单边授权关系。 + +若外部 Authorization Provider 的 RelationshipWriter 不能参加该协调事务,自动创建必须返回 +`503 relationship_management_unavailable`;部署应先通过可信 provisioning 流程创建 Root、映射、Policy 和 Binding, +再提交业务 Source,不能先写 Origin 后异步补权限。 + +Root 已存在时不需要 `server.admin`,但调用 Principal 对 Origin Scope 和 Root Scope 都必须拥有 +`scope.contribute`。请求中的 `root_contributor` 不得改变已有 Binding,也不能用于冒充当前调用 Principal。 + +### Atomic write flow + +```mermaid +sequenceDiagram + participant App as Application + participant API as Source API + participant PEP as Access Control + participant DB as PowerContext DB + + App->>API: Create Source(scope=S_GROUP, subject_key=U1) + API->>PEP: require scope.contribute on Origin + alt Root absent + API->>PEP: require server.admin or trusted provisioner + else Root exists + API->>PEP: require scope.contribute on Root + end + API->>DB: BEGIN + API->>DB: resolve or atomically provision U1 -> R_U1 + API->>DB: if new, bind explicit root_contributor + API->>DB: insert origin Source into S_GROUP journal + API->>DB: insert identical Source into R_U1 journal + API->>DB: insert pc_subject_source_projections relation + API->>DB: upsert Profile pending for R_U1 + API->>DB: COMMIT + API-->>App: 201 Source + committed subject projection +``` + +图中使用 HTTP Source API 展示调用,但双写不是 HTTP handler 的专有逻辑。Runtime API、Python SDK、MCP、Connector +和其他业务采集适配器只要携带 `subject_key`,都必须进入同一个 `SubjectSourceRoutingService` application service。 +该服务统一执行 Root Resolve、双 Scope 锁、Source 双写、投影关系和 Pending upsert;任何入口不得自行实现其中一部分, +也不得绕过它直接写一条带主体归属的 Origin Source。 + +首期明确扩展的业务入口请求为 `CreateSourceRequest`、`CaptureContentSourceRequest` 和 +`SubmitSourceObservationRequest`。三者共享 `subject_key/root_contributor` 路由字段和同一 application service; +Connector 最终提交 observation 时也不得绕过该服务。 + +Artifact 写入为 provenance 生成的内部 `lineage_only` 系统 Source,以及 Artifact Family 自己维护的内部 domain +Source,都不属于上述业务入口,不接受 `subject_key`,不进入主体投影服务。它们保留在目标 Scope,由对应领域服务 +直接写入。 + +双写必须满足: + +- 原 Source、Root Source、投影关系与 Root 的 Profile pending 在同一数据库事务提交;任一步失败则整体回滚; +- 同时锁定两个 Source journal 时,按 `scope_id` 排序加锁,避免并发死锁; +- 同一 Source 内部重试复用相同 `source_type + source_id`,相同 payload 视为幂等成功,不同 payload 返回冲突;Source ID 必须在生成时保证部署内唯一; +- `subject_key` 与 Root 的一一映射由数据库唯一约束和事务共同保证; +- Source 是不可变事实记录,写错 `subject_key` 后不能原地改归属,只能追加纠正 Source,并由后续画像 Revision 修正。 + +## Profile Artifact + +### Identity and singleton + +Subject-keyed user Profile 固定为: + +```text +(root_scope_id, family="profile", artifact_id="profile:user") +``` + +同一个 Root 首次写入使用 Profile 专用 Create;已有 `profile:user` 时再次 Create 返回 `409 Conflict`,后续只能使用 +Profile 专用 Replace。 +HTTP Replace 必须原样回传当前 Head 的不透明 `ETag` 作为 `If-Match`;内部 Profile RecordService 使用同一 Head CAS,不能另设 +一套以请求体 Revision 代替 HTTP 条件写的并发契约。 + +不带 `subject_key` 的普通 Scope 可以显式启用 Scope-local Profile: + +```text +(scope_id, family="profile", artifact_id="profile:local") +``` + +共享或多人 Scope 默认不启用 Scope-local Profile,避免把 U1、U2、U3 混成同一画像。 + +### Profile content + +Profile Revision 是一份完整 Markdown 当前快照。首期不定义 Claim category、Claim 主键、结构化 Claim 列表或逐 Claim 风险等级。 + +为保持现有 Artifact Repository 的“family content 是 Pydantic Model”约束,Profile 使用只有一个正文载荷的模型: + +```python +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +class ProfileContent(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema: Literal["powercontext.profile.v1"] = "powercontext.profile.v1" + media_type: Literal["text/markdown"] = "text/markdown" + content: Annotated[str, Field(min_length=1)] + + @field_validator("content") + @classmethod + def validate_markdown(cls, value: str) -> str: + normalized = normalize_profile_markdown(value) + if len(normalized.encode("utf-8")) > 262_144: + raise ValueError("profile Markdown exceeds 256 KiB") + return normalized +``` + +逻辑内容示例: + +```json +{ + "schema": "powercontext.profile.v1", + "media_type": "text/markdown", + "content": "# 用户画像\n\n用户偏好中文简洁回答。国内酒店通常选择大床房,常见预算约为 500~700 元。\n" +} +``` + +其中 `content` 完全由 LLM 生成或由授权用户编辑,格式为 Markdown: + +```markdown +# 用户画像 + +用户偏好中文简洁回答。国内酒店通常选择大床房,常见预算约为 500~700 元。 +``` + +规范化规则固定为 UTF-8、Unicode NFC、LF 换行、无 BOM、文件末尾一个换行。服务端校验非空、大小和 Markdown 文档边界;不把标题层级解释成数据库分类。 + +### Physical BLOB encoding + +现有 `pc_artifacts.content` 已是 `BLOB`,OceanBase/MySQL 变体为 `MEDIUMBLOB`,因此表结构无需变化。首期沿用当前 Artifact codec:将 `ProfileContent` 序列化为 Pydantic JSON UTF-8 bytes 写入 BLOB。也就是说,BLOB 中是包含 Markdown 字符串的模型字节,不是新的 Claim 列,也不是绕过 Artifact Repository 写入裸文本。 + +```text +pc_artifacts.content + = UTF8_BYTES('{"schema":"powercontext.profile.v1",' + '"media_type":"text/markdown",' + '"content":"# 用户画像\\n...\\n"}') +``` + +Profile 专用 API 将其解码并以字符串返回;通用 Artifact API 仍返回 `content` object,所以不需要改变现有 `ArtifactRevision.content: object` 的响应形状。 + +### Revision lineage and generation metadata + +每次自动生成、人工创建、人工替换、审核通过和回退都创建新的不可变 Revision: + +- 自动生成或审核通过的 Revision 在 `pc_artifact_lineage_sources` 中引用本次实际消费的 Root-local 业务 Source, + 不引用被窗口过滤掉的 `lineage_only` Source; +- 人工 Create、Replace 和 Rollback 由 Profile 专用 API 解析固定 identity,再调用内部 Artifact RecordService; + RecordService 保留 [RFC 1437](1437_source_artifact_rest_api.md) 的 provenance 语义,为该次写入命令生成 + `lineage_only` 系统 Source,并将它放在新 Revision 直接 Source lineage 的 ordinal 0; +- `pc_artifact_lineage_artifacts` 在更新时引用上一版 Profile 的精确 Revision; +- `pc_profile_revision_metadata` 保存生成方式、Source Window、生成器版本和回退来源; +- 不在 Markdown 中混入运行时游标或内部任务状态。 + +人工写入生成的系统 Source 仍是可审计 provenance,但 Profile Processor 必须过滤它,不能让一次画像修改再次成为 +下一次画像生成的证据。 + +### Update rules + +自动更新的模型输入是: + +```text +current Profile Markdown ++ Root Source window (cursor, source_through] +-> full next Profile Markdown | NOOP +``` + +合并规则: + +1. 只有 Root Source journal 中出现尚未消费的业务 Source 才允许自动调用 LLM;模型、Prompt、代码版本变化以及只有 + `lineage_only` Source 到达都不触发 rebuild。 +2. Worker 先过滤所有 `lineage_only` Source,再按精确 Source address 与 content digest 去重。窗口只有过滤项时不调用 + LLM、不创建 Revision,但仍以 CAS 推进 Cursor,避免永久重复扫描。 +3. LLM 读取当前完整 Markdown 和新 Source,只保留稳定、跨会话有价值的用户信息。 +4. 完全重复的内容合并;新且明确的用户表达覆盖冲突的旧表述;证据不足时保留原表述,不做敏感推断。 +5. `pc_profile_revision_metadata.generation_mode` 只描述整篇 Revision 如何成为 Head。冲突处理可以把 + `manual_create`、`manual_replace`、`review_approved` 的当前 Head 作为一个整体排在 `automatic` Head 之前,但不能 + 把这种优先级继承到某个段落,也不能声称一篇包含旧自动内容的人工 Revision 已逐段获得人工确认。新 Source 明确 + 记录用户纠正时,下一版仍按完整文档重新生成或人工编辑。 +6. LLM 必须返回完整 Markdown 或 `NOOP`,不能直接操作数据库字段。 +7. 服务端规范化并计算 digest;与当前 Head 相同则不创建空 Revision,只推进 Cursor。 +8. 校验失败、模型失败或 CAS 冲突不推进 Cursor;CAS 冲突时重读 Head 后重新合并。 + +移除 Claim 结构后的取舍是:首期只提供 Revision 级 lineage,不提供 Claim 级查询、Claim 级风险判断或 Claim 级引用。需要这些能力时,应通过后续可重建索引实现,而不是重新把 Claim 分类写入事实表。 + +## Background automatic generation + +### Schedule configuration + +默认每天部署时区的 `02:00` 发起一个 Profile 自动处理波次: + +```python +from typing import Annotated +from zoneinfo import ZoneInfo + +from pydantic import BaseModel, Field + +class ProfileGenerationSchedule(BaseModel): + enabled: bool = True + cron: str = "0 2 * * *" + timezone: str = "Asia/Shanghai" + source_window_limit: Annotated[int, Field(ge=1, le=1000)] = 200 + max_concurrency: Annotated[int, Field(ge=1, le=128)] = 8 + worker_timeout_seconds: Annotated[int, Field(ge=30, le=3600)] = 900 + retry_max_delay_seconds: Annotated[int, Field(ge=30, le=86_400)] = 1800 + + def tzinfo(self) -> ZoneInfo: + return ZoneInfo(self.timezone) +``` + +`02:00` 是默认低峰时间点。部署可以修改 Cron 和 IANA timezone;大规模部署可以配置调度抖动,但默认不抖动。实现必须使用带时区的 CronTrigger,不能用“每 86,400 秒”的 IntervalTrigger,否则服务重启和夏令时会造成时间漂移。 + +### Scheduled call flow + +```mermaid +sequenceDiagram + participant Cron as Profile Cron Scheduler + participant Sup as Artifact Processing Supervisor + participant DB as Metadata + Artifact DB + participant Worker as Profile Worker + participant LLM as LLM + + Cron->>Sup: daily wave at 02:00 + Sup->>DB: acquire/renew global lease + Sup->>DB: page pending(binding=profile-source-window) + DB-->>Sup: dirty Profile scopes and source_through + Sup->>Worker: assign(scope, after, through, generation) + Worker->>DB: read Cursor + current Profile + fixed Source window + Worker->>LLM: current Markdown + new Sources + LLM-->>Worker: complete Markdown or NOOP + Worker->>Worker: normalize, validate, digest + alt automatic and changed + Worker->>DB: CAS Create/Replace Revision + metadata + Cursor + else review_required and changed + Worker->>DB: create full-Markdown Candidate; wait for decision + else NOOP + Worker->>DB: CAS advance Cursor only + end + Worker-->>Sup: success / review_pending / failure +``` + +详细流程: + +1. 统一的 `SubjectSourceRoutingService` 已在业务 Source 写入事务中将 Root journal 高水位 upsert 到 + `pc_artifact_processing_pending`,但不立即调用 LLM。普通 Scope 显式启用 Scope-local Profile 时,其自身 journal + 高水位也会登记为独立 target;共享 Scope 默认不启用。 +2. 每天 `02:00`,持有 Supervisor lease 的实例启动本日波次;持久化 scheduler 使用 `coalesce=true`,错过执行时间后恢复时补执行一次。 +3. Supervisor 分页读取 `binding_name="profile-source-window"` 的 dirty targets,并按 `max_concurrency` 公平调度。 +4. Worker 冻结本轮 `source_through`,读取 `pc_source_cursors` 的 `after`,按默认最多 200 条 Source 的 Window 分批 + 读取,并在调用模型前排除 `lineage_only`。新 Source 在推理期间到达时位置大于 `through`,留给下一波。 +5. `after >= through` 或固定 Window 过滤后为空时跳过 LLM;后者仍推进 Cursor。达到 Pending 高水位后清理 Pending。 +6. Worker 在事务外读取当前 Profile、固定 Source Window 并调用 LLM,避免长事务占锁。 +7. Worker 校验完整 Markdown。自动生效时,用 Head CAS、Cursor CAS 和 Supervisor fencing 在一个短事务中提交 Revision、Lineage、Revision Metadata 和 Cursor。 +8. 无语义变化时不创建 Revision,只 CAS 推进 Cursor。 +9. `review_required` 时,在一个事务中创建完整 Profile Candidate、持久化其 Source Window,并占用 Policy 的单一 + `pending_candidate_id`;有未决 Candidate 时,定时与 Manual Generate 都不重复生成。批准后创建 Revision 并推进到 + Candidate 的 `source_through`。拒绝必须显式选择 `reject_and_consume` 或 `reject_and_retry`:前者推进 Cursor,避免 + 次日重复提出同一内容;后者不推进 Cursor 并保留 Pending,使同一窗口可以在后续波次重新生成。 +10. 单个用户处理失败不阻塞其他用户;失败不推进 Cursor,不删除 Pending,并按指数退避重试,最大间隔默认 30 分钟。 + +### Why a durable dirty set instead of a Job history table + +Profile 复用 Topic Memory RFC 定义的通用 `pc_artifact_processing_pending`、`pc_artifact_processing_leases` 和 `pc_source_cursors`。Pending 表达“哪个 `(binding_name, scope_id)` 仍有未消费 Source”,不是无限增长的任务历史。 + +首期不增加 `pc_profile_generation_jobs`。处理状态由 Pending、Cursor、当前 journal head 和最近 Profile Revision Metadata 组合得到;运行日志和指标用于观测每次尝试。若 Topic Memory 的通用处理表在 Profile 实现前尚未落地,则它们作为本 RFC 的新增通用表一并实现,而不能被描述成已有表。 + +### Manual generation + +`POST /v1/profile/generate` 不同步等待 LLM。它读取当前 Source journal head、递增 Pending 的 `flush_generation` 并唤醒 +Supervisor。该 operation 只有一个成功 HTTP 状态 `200 OK`,body 的 `status` 为 `accepted`、`idle` 或 +`review_pending`;无新 Source 时返回 `idle`,已有未决 Candidate 时返回 `review_pending`,两种情况都不会 rebuild +当前 Profile。 + +## Review, edit and rollback + +Claim category 和风险等级移除后,审核粒度是整篇 Markdown Revision: + +```python +from typing import Literal + +from pydantic import BaseModel, ConfigDict + +class ProfilePolicy(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + generation_enabled: bool = True + activation_mode: Literal["automatic", "review_required"] = "automatic" + version: int +``` + +- `automatic`:默认值,合法的新 Markdown 直接 Create/Replace 并成为 Head; +- `review_required`:生成结果写入现有 Artifact Candidate 表,批准后才成为新 Revision; +- 政策由服务端配置或授权用户通过 Policy API 按目标 Scope 修改,不由 LLM 判断; +- 不再存在“某一 Claim 风险等级自动、另一等级 Review”的配置,因为首期没有 Claim 级结构。 + +拒绝自动 Candidate 时,审核请求必须显式提交 `disposition`: + +- `reject_and_consume`:记录拒绝、推进 Cursor 到 Candidate 的 `source_through`、更新 Pending 并清空 Policy 指针; +- `reject_and_retry`:记录拒绝、保持 Cursor 不变、保留或重新 upsert Pending,并清空 Policy 指针。 + +人工修改必须提交完整 Markdown、原因和当前 Head 的 `If-Match`,并创建新 Revision。回退不是把 Head 指针倒拨,而是 +读取目标旧 Revision 的 Markdown,将其复制为当前 Head 的下一个 Revision;Revision Metadata 记录 +`restored_from_revision`,HTTP 请求同样使用 `If-Match` 保护当前 Head。 + +Candidate、人工修改和回退都使用 Artifact Head CAS。审核期间 Head 已发生变化时,批准返回冲突并要求重新生成或重新修订 Candidate,不能把基于旧 Head 的内容静默覆盖到新 Head。 + +## Subject context aggregation + +`subject_key` 不只用于找到 Profile,也定义一个可供不同 Artifact Family 复用的稳定查询入口: + +```mermaid +flowchart LR + K["subject_key"] --> Resolve["resolve root_scope_id"] + Resolve --> Select["root + true descendants"] + Select --> Auth["authorize every Scope and Artifact"] + Auth --> Profile["exact Profile Head"] + Auth --> Recall["family-specific recall"] + Recall --> Dedup["exact + semantic dedup"] + Profile --> Compose["conflict-aware composition"] + Dedup --> Compose + Compose --> Budget["rank + family quota + max_bytes"] +``` + +范围选择遵循以下规则: + +1. 服务端先通过 `pc_subject_roots` 得到唯一 `root_scope_id`。 +2. 候选范围是 Root 与其真实 descendants;Parent 只用于组织,仍需逐 Scope、逐 Artifact 授权。 +3. 共享群聊 Scope 不属于任何用户 Root 子树,不能因用户参与群聊而被隐式加入。 +4. Profile 使用固定地址精确读取,不参与普通向量召回;Memory、Topic Memory、Skill、Experience 等使用各自 family 的召回器。 +5. 相同 `(scope_id, family, artifact_id, revision)` 只保留一次;同一 Head 与其精确 Revision 不重复注入。跨 Scope + 返回值必须使用包含 `scope_id` 的 `ArtifactAddress`,不能只返回同 Scope 才完整的 `ArtifactRef`。 +6. family 内部先按稳定身份和内容摘要去重,再做语义去重;不同 family 的程序性知识不能只因文本相似就合并。 +7. Markdown Profile 与其他制品表达冲突时,只能按当前 Head 的整篇 `generation_mode`、时间和直接证据排序;不得把 + Revision 级人工模式解释成段落级信任。仍无法判断时同时返回冲突摘要与双方精确 `ArtifactAddress`,不修改任何源 + Artifact。 +8. 最终结果使用 family quota 和请求的 `max_bytes` 限制;服务端按 UTF-8 实际字节数计量,被截断的内容保留可继续 + 读取的完整地址。 + +Memory Entry 等 family-owned subresource 也必须返回包含 `scope_id` 的完整地址;主体聚合结果中不得出现依赖隐含当前 +Scope 才能解引用的裸 `ArtifactRef`、Entry ref 或其他 subresource ref。 + +现有 Prepare Context 只处理调用方显式 Scope 范围,不会自动遍历 Subject Root。本 RFC 的 Subject Context API 负责服务端解析范围,再复用各 family 的既有召回能力。 + +首期自动生成的用户级制品只有 Profile。未来其他 Artifact Family 若复用本设计,应从 Root-local Source journal 消费证据,并把产物写到 Root 或其真实子 Scope;共享 Scope 中已经存在的 Artifact 不会仅因 Source 被复制而自动跨 Scope 生效。 + +# Reference-level explanation + +## Database metadata design + +### Relationship diagram + +```mermaid +erDiagram + PC_SCOPES ||--o| PC_SUBJECT_ROOTS : "root_scope_id" + PC_SCOPES ||--o{ PC_SOURCES : owns + PC_SUBJECT_ROOTS ||--o{ PC_SUBJECT_SOURCE_PROJECTIONS : routes + PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "origin Source" + PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "Root Source" + PC_SCOPES ||--o{ PC_ARTIFACTS : owns + PC_ARTIFACTS ||--o| PC_PROFILE_REVISION_METADATA : "Profile subset" + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : cites + PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : evidence + PC_SCOPES ||--o| PC_PROFILE_POLICIES : configures + PC_ARTIFACT_CANDIDATE_HEADS ||--o| PC_PROFILE_CANDIDATE_METADATA : tracks_window + PC_SCOPES ||--o{ PC_SOURCE_CURSORS : consumes + PC_SCOPES ||--o{ PC_ARTIFACT_PROCESSING_PENDING : marks_dirty +``` + +`pc_artifact_processing_leases` 通过 Supervisor 的 `holder_id + supervisor_generation` 在运行时 fencing Worker 提交;它与 Pending 没有数据库外键,因而不在 ER 实线关系中。 + +### New table: `pc_subject_roots` + +Artifact Family 无关的主体到 Root Scope 映射: + +| 字段 | 类型 | 约束 | 含义 | +| --- | --- | --- | --- | +| `subject_key` | `VARCHAR(256)` binary collation | PK | 调用方业务 `user_id`,精确匹配 | +| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, UNIQUE, FK -> `pc_scopes.scope_id` | PowerContext 生成的用户 Root | +| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | 映射创建时间 | + +额外定义 `UNIQUE(subject_key, root_scope_id)`,供投影表建立复合外键。映射一经创建不可重绑;账号合并与迁移另行设计。 + +### New table: `pc_subject_source_projections` + +记录业务 Scope Source 与 Root Source 的精确一一投影: + +| 字段 | 类型 | 约束 | +| --- | --- | --- | +| `origin_scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_sources.scope_id` | +| `origin_source_type` | `VARCHAR(128)` binary collation | PK part, FK part | +| `origin_source_id` | `VARCHAR(256)` binary collation | PK part, FK part | +| `subject_key` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | +| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | +| `projected_source_type` | `VARCHAR(128)` binary collation | NOT NULL, FK part -> `pc_sources` | +| `projected_source_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_sources` | +| `content_digest` | `VARCHAR(71)` binary collation | NOT NULL, `sha256:` | +| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | + +约束: + +```text +PRIMARY KEY (origin_scope_id, origin_source_type, origin_source_id) +UNIQUE (root_scope_id, projected_source_type, projected_source_id) +FOREIGN KEY (origin_scope_id, origin_source_type, origin_source_id) + REFERENCES pc_sources(scope_id, source_type, source_id) +FOREIGN KEY (root_scope_id, projected_source_type, projected_source_id) + REFERENCES pc_sources(scope_id, source_type, source_id) +FOREIGN KEY (subject_key, root_scope_id) + REFERENCES pc_subject_roots(subject_key, root_scope_id) +CHECK (origin_scope_id <> root_scope_id) +``` + +首期 `projected_source_type/id` 与原 Source 相同;单独保留字段是为了让关系两端地址完整,并允许未来定义不同的内部 Source adapter。 + +### New table: `pc_profile_policies` + +同时支持 Subject Root Profile 和显式启用的 Scope-local Profile: + +| 字段 | 类型 | 约束 | 默认值 | +| --- | --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK, FK -> `pc_scopes.scope_id` | - | +| `generation_enabled` | `BOOLEAN` | NOT NULL | `TRUE` for Subject Root | +| `activation_mode` | `VARCHAR(32)` binary collation | CHECK `automatic/review_required` | `automatic` | +| `pending_candidate_id` | `VARCHAR(128)` binary collation | nullable, FK part -> `pc_artifact_candidate_heads` | `NULL` | +| `version` | `BIGINT` | NOT NULL, CHECK > 0 | `1` | +| `updated_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | current time | + +创建 Subject Root 时同时创建默认 Policy。普通 Scope 没有 Policy 表示未启用 Scope-local Profile;调用方显式配置后才加入每日扫描。 + +`pending_candidate_id` 与同一行的 `scope_id` 组成外键,指向 `pc_artifact_candidate_heads(scope_id, candidate_id)`。Worker 只能在该字段为 `NULL` 时创建自动 Profile Candidate,并在同一事务中设置它;Approve/Reject 在完成 Cursor/Pending 处理后清空它。这个单值指针保证每个 Profile Scope 同时最多一个未决自动 Candidate,包括 Manual Generate 并发路径。 + +### New table: `pc_profile_revision_metadata` + +Markdown 是纯画像内容,运行元数据单独关联到 Artifact Revision: + +| 字段 | 类型 | 约束 | +| --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifacts` | +| `family` | `VARCHAR(128)` binary collation | PK part, FK part, CHECK `family='profile'` | +| `artifact_id` | `VARCHAR(128)` binary collation | PK part, FK part | +| `revision` | `INTEGER` | PK part, FK part | +| `generation_mode` | `VARCHAR(32)` binary collation | `automatic/manual_create/manual_replace/review_approved/rollback` | +| `generator_id` | `VARCHAR(128)` binary collation | NULL for manual operations | +| `generator_version` | `VARCHAR(128)` binary collation | NULL for manual operations | +| `source_after` | `BIGINT` | nullable, CHECK >= 0 | +| `source_through` | `BIGINT` | nullable, CHECK >= `source_after` | +| `restored_from_revision` | `INTEGER` | nullable, CHECK > 0;与同一 `scope_id/family/artifact_id` 组成复合 FK | +| `operation_reason` | `TEXT` | nullable | +| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | + +约束: + +```text +PRIMARY KEY (scope_id, family, artifact_id, revision) +FOREIGN KEY (scope_id, family, artifact_id, revision) + REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) +FOREIGN KEY (scope_id, family, artifact_id, restored_from_revision) + REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) +CHECK (family = 'profile') +CHECK (generation_mode IN + ('automatic', 'manual_create', 'manual_replace', 'review_approved', 'rollback')) +CHECK ((source_after IS NULL) = (source_through IS NULL)) +CHECK (source_after IS NULL OR (source_after >= 0 AND source_through >= source_after)) +CHECK ( + (generation_mode IN ('automatic', 'review_approved') AND source_after IS NOT NULL) + OR + (generation_mode IN ('manual_create', 'manual_replace', 'rollback') AND source_after IS NULL) +) +CHECK ( + (generation_mode = 'rollback' AND restored_from_revision IS NOT NULL) + OR + (generation_mode <> 'rollback' AND restored_from_revision IS NULL) +) +``` + +### New table: `pc_profile_candidate_metadata` + +现有 Candidate 表不保存生成窗口,不能在拒绝时可靠知道 Cursor 应推进到哪里。Profile 自动 Candidate 因此增加一条窄化的处理元数据记录: + +| 字段 | 类型 | 约束 | +| --- | --- | --- | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifact_candidate_heads` | +| `candidate_id` | `VARCHAR(128)` binary collation | PK part, FK part | +| `binding_name` | `VARCHAR(128)` binary collation | NOT NULL, CHECK `binding_name='profile-source-window'` | +| `source_after` | `BIGINT` | NOT NULL, CHECK >= 0 | +| `source_through` | `BIGINT` | NOT NULL, CHECK >= `source_after` | +| `claimed_flush_generation` | `BIGINT` | NOT NULL, CHECK >= 0 | +| `rejection_disposition` | `VARCHAR(32)` binary collation | nullable;`reject_and_consume/reject_and_retry` | +| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | + +```text +PRIMARY KEY (scope_id, candidate_id) +FOREIGN KEY (scope_id, candidate_id) + REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) +CHECK (binding_name = 'profile-source-window') +CHECK (rejection_disposition IS NULL OR rejection_disposition IN + ('reject_and_consume', 'reject_and_retry')) +``` + +Candidate Create 同时写 Candidate、该元数据和 `pc_profile_policies.pending_candidate_id`,但不推进 Cursor。Approve 在同一 +事务中提交 Profile Revision、Revision Metadata、Candidate 状态、Cursor/Pending 和 Policy 指针。Reject 不创建 Artifact: +`reject_and_consume` 在同一事务中推进到 `source_through` 并更新 Pending;`reject_and_retry` 保持 Cursor 不变并保留或重新 +upsert Pending。两者都记录 `rejection_disposition`、拒绝原因并清空 Policy 指针。若期间 Head 已变化,操作冲突并保留 +Candidate,不推进 Cursor。 + +### New generic tables shared with Topic Memory + +如果 Topic Memory 尚未先行创建,下列两张表由本 RFC 一并增加。 + +`pc_artifact_processing_pending`: + +| 字段 | 类型 | 约束 | +| --- | --- | --- | +| `binding_name` | `VARCHAR(128)` binary collation | PK part | +| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_scopes.scope_id` | +| `source_through` | `BIGINT` | NOT NULL, CHECK >= 1 | +| `flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK >= 0 | +| `handled_flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK between 0 and `flush_generation` | + +Profile 使用 `binding_name="profile-source-window"`。 + +`pc_artifact_processing_leases`: + +| 字段 | 类型 | 约束 | +| --- | --- | --- | +| `supervisor_group` | `VARCHAR(128)` binary collation | PK;首期固定 `global` | +| `holder_id` | `VARCHAR(128)` binary collation | NOT NULL | +| `supervisor_generation` | `BIGINT` | NOT NULL, CHECK > 0 | +| `lease_expires_at` | `DateTime(timezone=True)`,按 UTC 归一化 | nullable for single-process SQLite | + +两张表是通用 Artifact processing substrate,不属于 Profile 内容模型。 + +### Existing tables: no physical schema changes + +本 RFC 不修改以下已有表的列、主键或外键: + +| 现有表 | 本 RFC 的用法 | DDL 变更 | +| --- | --- | --- | +| `pc_scopes` | 保存业务 Scope 和用户 Root;Root 的 `parent_scope_id=NULL` | 无 | +| `pc_scope_bindings` | 本方案不用于 Subject Root 映射 | 无 | +| `pc_scope_context_references` | Source Create 不自动写入 | 无 | +| `pc_sources` | 原 Scope 与 Root 各保存一条相同 Source | 无 | +| `pc_source_journal_heads` | 两个 Scope 各自维护 journal 高水位 | 无 | +| `pc_source_cursors` | 保存 `profile-source-window` 的消费位置 | 无 | +| `pc_artifacts` | 保存不可变 Profile Revision;`content` 已是 BLOB/MEDIUMBLOB | 无 | +| `pc_artifact_heads` | 保存 `profile:user` 或 `profile:local` 当前 Head | 无 | +| `pc_artifact_lineage_sources` | 自动 Profile 引用同 Scope 的可消费 Root Source;人工操作保留同 Scope `lineage_only` 系统 Source | 无 | +| `pc_artifact_lineage_artifacts` | 新 Profile Revision 引用上一 Revision | 无 | +| `pc_artifact_candidate_versions` | `review_required` 时保存完整 ProfileContent proposal | 无 | +| `pc_artifact_candidate_heads` | 保存 Profile Candidate 当前审核状态 | 无 | +| `pc_artifact_publications` | 本 RFC 的 Source 复制不使用 Artifact Publication | 无 | +| `powercontext_scheduler_jobs` | APScheduler sidecar 增加一个 Profile Cron job row | 表结构无变化 | + +虽然数据库 DDL 不变,Artifact 与 Candidate 的代码/OpenAPI family 枚举需要增加 `profile`,见接口变更。 + +### Example rows for one U1 message + +```text +pc_subject_roots + (U1, R_U1) + +pc_sources + (S_GROUP, content, source_01, payload=P, journal_position=101) + (R_U1, content, source_01, payload=P, journal_position=42) + +pc_subject_source_projections + (S_GROUP, content, source_01, U1, R_U1, content, source_01, sha256:...) + +pc_artifact_processing_pending + (profile-source-window, R_U1, source_through=42, ...) +``` + +U2/U3 的 Root、journal、Cursor 和 Pending 均不变化。 + +## API design + +### Python request and response types + +以下类型展示首期公开契约的关键字段;已有模型未展示的字段保持不变: + +```python +from __future__ import annotations + +from typing import Annotated, Any, Generic, Literal, Mapping, TypeVar + +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +SubjectKey = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] +ETag = Annotated[str, Field(min_length=1)] + + +class PrincipalRef(BaseModel): + type: Literal["user", "service"] + id: Annotated[str, Field(min_length=1, max_length=256)] + description: str | None = None + + +class SubjectRoutingFields(BaseModel): + subject_key: SubjectKey | None = None + root_contributor: PrincipalRef | None = None + + +class CreateSourceRequest(SubjectRoutingFields): + # Existing fields remain unchanged. + source_type: Literal["content"] = "content" + content: Any + + +class CaptureContentSourceRequest(SubjectRoutingFields): + # Existing fields remain unchanged. + scope_id: str + source_id: str + content: str + metadata: dict[str, Any] | None = None + + +class SubmitSourceObservationRequest(SubjectRoutingFields): + # Existing SourceObservation schema remains unchanged. + scope_id: str + observation: Any + + +class SourceAddress(BaseModel): + scope_id: str + source_type: str + source_id: str + + +class SubjectProjectionReceipt(BaseModel): + subject_key: SubjectKey + root_scope_id: str + origin_source: SourceAddress + root_source: SourceAddress + status: Literal["committed", "already_in_root"] + + +# DELTA ONLY: this is not a replacement definition for SourceRecord. +# SourceRecord keeps every existing field, including receipt_identity. +class SourceRecordDelta(BaseModel): + subject_projection: SubjectProjectionReceipt | None = None + + +class ArtifactRef(BaseModel): + family: str + artifact_id: str + revision: int + + +class ArtifactAddress(BaseModel): + scope_id: str + artifact: ArtifactRef + + +class MemoryEntryAddress(BaseModel): + memory: ArtifactAddress + entry_id: str + entry_version_id: str + + +class ProfileTarget(BaseModel): + subject_key: SubjectKey | None = None + scope_id: str | None = None + + @model_validator(mode="after") + def exactly_one_target(self): + if (self.subject_key is None) == (self.scope_id is None): + raise ValueError("provide exactly one of subject_key or scope_id") + return self + + +class ResolvedProfileTarget(BaseModel): + scope_id: str + artifact_id: Literal["profile:user", "profile:local"] + # Both are populated for a subject-keyed Profile and null for Scope-local. + subject_key: SubjectKey | None = None + root_scope_id: str | None = None + + +class ResolveSubjectRequest(BaseModel): + subject_key: SubjectKey + create_if_absent: bool = True + origin_scope_id: str | None = None + root_contributor: PrincipalRef | None = None + + @model_validator(mode="after") + def require_origin_for_create(self): + if self.create_if_absent and self.origin_scope_id is None: + raise ValueError("origin_scope_id is required when create_if_absent=true") + return self + + +class ResolveSubjectResponse(BaseModel): + subject_key: SubjectKey + root_scope_id: str + created: bool + + +class ProfileGenerationMetadata(BaseModel): + mode: Literal[ + "automatic", + "manual_create", + "manual_replace", + "review_approved", + "rollback", + ] + source_after: int | None = None + source_through: int | None = None + restored_from_revision: int | None = None + created_at: str + + +class ProfileRecord(BaseModel): + target: ResolvedProfileTarget + artifact: ArtifactAddress + media_type: Literal["text/markdown"] = "text/markdown" + content: str + content_digest: str + generation: ProfileGenerationMetadata + + +class ProfileResponse(BaseModel): + """Python SDK wrapper; the wire body is ProfileRecord and ETag is a header.""" + + record: ProfileRecord + etag: ETag + + +class CreateProfileRequest(BaseModel): + target: ProfileTarget + content: str + reason: str + + +class GetProfileRequest(BaseModel): + target: ProfileTarget + + +class ListProfileChangesRequest(BaseModel): + target: ProfileTarget + limit: Annotated[int, Field(ge=1, le=100)] = 50 + cursor: str | None = None + + +class ProfileChange(BaseModel): + artifact: ArtifactAddress + generation: ProfileGenerationMetadata + content_digest: str + + +class ProfileChangesPage(BaseModel): + target: ResolvedProfileTarget + items: tuple[ProfileChange, ...] + next_cursor: str | None = None + + +class DiffProfileRequest(BaseModel): + target: ProfileTarget + from_revision: Annotated[int, Field(ge=1)] + to_revision: Annotated[int, Field(ge=1)] + + +class ProfileDiffHunk(BaseModel): + old_start: int + old_lines: int + new_start: int + new_lines: int + lines: tuple[str, ...] + + +class ProfileDiff(BaseModel): + from_artifact: ArtifactAddress + to_artifact: ArtifactAddress + hunks: tuple[ProfileDiffHunk, ...] + + +class ReplaceProfileRequest(BaseModel): + # If-Match is an HTTP header, not a body field. + target: ProfileTarget + content: str + reason: str + + +class RollbackProfileRequest(BaseModel): + # If-Match is an HTTP header, not a body field. + target: ProfileTarget + restore_revision: Annotated[int, Field(ge=1)] + reason: str + + +class GenerateProfileRequest(BaseModel): + target: ProfileTarget + + +class ProfileGenerationResponse(BaseModel): + target: ResolvedProfileTarget + status: Literal["accepted", "idle", "review_pending"] + binding_name: Literal["profile-source-window"] + source_through: int | None = None + flush_generation: int | None = None + + +class GetProfileProcessingRequest(BaseModel): + target: ProfileTarget + + +class ProfileProcessingStatus(BaseModel): + target: ResolvedProfileTarget + journal_head: int + cursor_after: int + pending_through: int | None = None + pending_flush_generation: int | None = None + pending_candidate_id: str | None = None + last_result: Literal["success", "noop", "review_pending", "failure"] | None = None + + +class GetProfilePolicyRequest(BaseModel): + target: ProfileTarget + + +class ProfilePolicyRecord(BaseModel): + target: ResolvedProfileTarget + generation_enabled: bool + activation_mode: Literal["automatic", "review_required"] + version: int + + +class UpdateProfilePolicyRequest(BaseModel): + target: ProfileTarget + generation_enabled: bool + activation_mode: Literal["automatic", "review_required"] + expected_version: Annotated[int, Field(ge=1)] + + +ContextAddress = ArtifactAddress | MemoryEntryAddress + + +class PrepareSubjectContextRequest(BaseModel): + subject_key: SubjectKey + query: Annotated[str, Field(min_length=1)] + families: tuple[Literal["profile", "memory", "topic-memory", "skill", "experience"], ...] + max_bytes: Annotated[int, Field(ge=1, le=4_194_304)] + + +class SubjectContextItem(BaseModel): + address: ContextAddress + content: str + selected_bytes: int + + +class SubjectContextConflict(BaseModel): + summary: str + left: ContextAddress + right: ContextAddress + + +class PreparedSubjectContext(BaseModel): + subject_key: SubjectKey + root_scope_id: str + scope_ids: tuple[str, ...] + items: tuple[SubjectContextItem, ...] + conflicts: tuple[SubjectContextConflict, ...] + used_bytes: int + max_bytes: int + truncated: bool + + +T = TypeVar("T") + + +class HttpResult(BaseModel, Generic[T]): + body: T + headers: Mapping[str, str] + + +def with_profile_metadata(result: HttpResult[ProfileRecord]) -> ProfileResponse: + """Shared SDK helper used by Profile Create, Get, Replace, and Rollback.""" + + etag = result.headers.get("ETag") + if etag is None: + raise RuntimeError("Profile response omitted required ETag") + return ProfileResponse(record=result.body, etag=etag) +``` + +`ProfileTarget(subject_key=...)` 解析到 `root_scope_id + profile:user`。`ProfileTarget(scope_id=...)` +先检查该 Scope 是否登记在 `pc_subject_roots`:若是用户 Root,同样规范化为 `profile:user`;只有普通 Scope +才解析为 `profile:local`。因此不能用不同 selector 在同一用户 Root 创建两个 Profile Head。 + +`ProfileResponse` 是 Python SDK 的 metadata-aware wrapper,不是新的 HTTP body envelope。Profile Create、Get、 +Replace 和 Rollback 的 wire body 都是 `ProfileRecord`,SDK 通过共享的 `with_profile_metadata` helper 同时读取 +response body 与 `ETag` header,构造 `ProfileResponse(record=..., etag=...)`。Scope-local Profile 的 +`subject_key` 和 `root_scope_id` 都为 `None`。 + +上面的 `SourceRecordDelta` 只展示本 RFC 增加的字段。最终 `SourceRecord` 必须保留现有全部字段,包括 +`receipt_identity`,再增加可选 `subject_projection`;不得用该代码片段覆盖现有 schema。 + +### Existing API changes + +| 已有接口/Schema | 变更 | 兼容性 | +| --- | --- | --- | +| 所有业务 Source 写入 application service | `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 增加可选 `subject_key` 和 `root_contributor`;传入 key 时统一经 `SubjectSourceRoutingService` | 不传时行为不变;HTTP、Runtime、MCP 和 Connector 共用 | +| `POST /v1/scopes/{scope_id}/sources` | HTTP adapter 将扩展后的 `CreateSourceRequest` 交给上述统一服务 | 不传 key 时行为不变;加法式变更 | +| `SourceRecord` | 增加可选 `subject_projection`,返回 Root 与 Root Source 地址 | 旧客户端可忽略 | +| Root Scope 上的 Source Create | 必须携带与 Root 映射一致的 `subject_key`;内部投影除外 | 普通 Scope 行为不变;新增 Root 边界校验 | +| `PUT /v1/scopes/{scope_id}` | 当目标是已登记的用户 Root 时,禁止把 `parent_scope_id` 改为非空 | 请求结构不变;新增 Root 不变量冲突 | +| `BaseArtifactFamily` | 枚举增加 `profile`,用于通用 Artifact 读取地址和响应 | 加法式变更 | +| `CreateArtifactRequest`、`ReplaceArtifactRequest` | 首期不增加 Profile 分支;通用 Artifact Create/Replace 不接受 `profile` 写入 | 现有写入 union 不变;Profile 写入只能走专用 API | +| 通用 Artifact Get head、Get revision、List | 接受 `family=profile`,内容仍是 `ProfileContent` object | 路径和响应外形不变 | +| `CandidateFamily` | 枚举增加 `profile` | 加法式变更 | +| `ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` | union 增加 `ProfileContent` | 加法式变更 | +| `/v1/artifact-candidates/list|get|approve|reject|revise` | 支持完整 Markdown Profile Candidate;Profile Reject 强制 `disposition=reject_and_consume/reject_and_retry`;Approve/Reject 联动 Cursor、Pending、窗口元数据和 Policy 指针 | 路径不变,Profile 分支增加原子副作用 | +| Profile Create/Get/Replace/Rollback response | wire body 为 `ProfileRecord`,全部返回 `ETag` header;Python SDK 返回 `ProfileResponse` | 新增 metadata-aware helper,不改变通用 Client 返回类型 | +| `GET /v1/capabilities` | `artifact_families` 包含 `profile`,并增加 `profile_generation` 能力位 | 加法式变更 | + +除上表列出的 Root Parent 保护与可选 Source 投影信息外,Scope、Source exact identity、Artifact identity、ETag、Revision 和 Candidate 状态语义不变。首期仍不增加 Source Update;新的事实或纠正通过 Create 新 Source 表达。 + +当前 Source Create 与 Source exact Get 共用 `SourceRecord`,所以选择在 `SourceRecord` 增加可选字段时,两者都会得到这一加法式字段。读取 Origin Source 时可以返回投影关系;读取 Root Source 时可以返回其 Origin。若实现只希望 Create 返回 receipt,则必须新增 `CreateSourceResponse` 并把 `201` 响应从 `SourceRecord` 改为该类型,不能只修改服务端返回值而不修改 OpenAPI。 + +Candidate 数据库表虽然 family-neutral,现有 Review Service 仍只处理 Experience/Skill。支持 Profile 时, +`ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` 和内部 `ReviewedProposal` 都要加入 +`ProfileContent`。ReviewService 增加 Profile 分支:解析 Candidate 的固定目标后调用内部 Profile RecordService,提交到 +`profile:user` 或 `profile:local` 并执行 Head CAS、Cursor/Pending 和 Policy 指针事务;不得经通用 Artifact Create/Replace +分配随机 Artifact ID。只扩展 `CandidateFamily` 枚举不够。 + +已有非 HTTP 配置与 Python 组装也有加法式变化: + +| 位置 | 变更 | +| --- | --- | +| Runtime configuration | 增加 Profile Cron、IANA timezone、Window limit、并发与超时配置;现有 Memory/Experience interval 配置不变 | +| Scheduler assembly | 新增 `configure_profile_generation_job` 和带独立 timezone 的 CronTrigger;复用 `powercontext_scheduler_jobs`,不以 86,400 秒 Interval 代替每日时间点 | +| Artifact registry / read codecs | 注册 `ProfileContent`,供通用 exact Get、revision Get 和 List 解码;不注册公开 generic write 分支 | +| Profile RecordService | Profile 专用 API、Processor 和 ReviewService 解析固定 identity 后,复用内部 Artifact RecordService 的 Create/Replace/Head CAS | +| System provenance Source target | 允许 `family="profile"`;人工 Create/Replace/Rollback 保留 `lineage_only` Source,自动 Profile Window 必须过滤 | +| Review Service | `ReviewedProposal` 增加 `ProfileContent`,并将 Profile Approve/Reject 与 RecordService、Cursor/Pending 原子联动 | + +### New APIs + +PowerContext 已有 operation-style POST 接口。本 RFC 使用请求体承载 `subject_key`,避免把业务用户 ID 固定暴露在 URL path 和访问日志中。 + +| 新接口 | 用途 | 成功结果 | +| --- | --- | --- | +| `POST /v1/subjects/resolve` | 幂等解析或创建 `subject_key -> root_scope_id` | 固定 `200`;body 用 `created` 区分 | +| `POST /v1/profile/create` | 人工创建首个完整 Markdown Profile | `201` + `ETag`;已存在为 `409` | +| `POST /v1/profile/get` | 按 `ProfileTarget` 获取当前 Head | `200` + `ETag` | +| `POST /v1/profile/changes` | 列出 Revision 与生成元数据 | `200` | +| `POST /v1/profile/diff` | 比较两个 Markdown Revision | `200` unified/structured line diff | +| `POST /v1/profile/replace` | 人工提交完整 Markdown,必须携带当前 Head 的 `If-Match` | `200` new Revision + `ETag` | +| `POST /v1/profile/rollback` | 复制旧内容为新的 Head Revision,必须携带当前 Head 的 `If-Match` | `200` new Revision + `ETag` | +| `POST /v1/profile/generate` | 请求立即处理现有新 Source,不等待 LLM | 固定 `200`;body `status=accepted/idle/review_pending` | +| `POST /v1/profile/processing/get` | 读取 journal head、Cursor、Pending 和最近结果 | `200` | +| `POST /v1/profile/policy/get` | 读取自动生效/Review Policy | `200` | +| `POST /v1/profile/policy/update` | 使用 expected policy version 修改 Policy | `200` | +| `POST /v1/subjects/context/prepare` | 解析 Root 并聚合 Root 及真实 descendants 中被授权的 Artifact | `200` | + +Profile Create、Get、Replace、Rollback 的成功响应都在 header 返回当前 Head 的不透明 `ETag`;wire body 固定为 +`ProfileRecord`。Python SDK 使用 metadata-aware helper 返回 `ProfileResponse(record, etag)`。 + +Profile 审核的 list/get/approve/reject/revise 复用现有 Artifact Candidate 接口,不另建第二套审核状态机。Profile Reject +request 在现有原因之外必须携带 `disposition`,以明确同一 Source Window 是消费还是重试。 + +```python +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class RejectArtifactCandidateRequest(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + scope_id: str + candidate_id: str + expected_version: Annotated[int, Field(ge=1)] + reason: Annotated[str, Field(min_length=1, max_length=2000)] + disposition: Literal["reject_and_consume", "reject_and_retry"] | None = None +``` + +`disposition` 对 Experience/Skill 保持可选且必须为 `None`;服务端解析 Candidate 后,仅对 `family=profile` 强制非空。 + +例如,审核者确认该窗口不应改变画像时提交: + +```json +{ + "scope_id": "R_U1", + "candidate_id": "candidate_01", + "expected_version": 3, + "reason": "这段内容只是一次性请求,不应成为长期画像", + "disposition": "reject_and_consume" +} +``` + +### Resolve Subject Root + +```http +POST /v1/subjects/resolve +Content-Type: application/json +``` + +```json +{ + "subject_key": "U1", + "create_if_absent": true, + "origin_scope_id": "S_GROUP", + "root_contributor": {"type": "user", "id": "principal-u1"} +} +``` + +```json +{ + "subject_key": "U1", + "root_scope_id": "R_U1", + "created": true +} +``` + +Root 创建成功后,映射不可重绑。`create_if_absent=false` 且不存在时返回 `404`。 +无论本次创建还是命中已有映射,成功状态都固定为 `200 OK`,由 response 的 `created` 布尔值表达结果。 + +`create_if_absent=false` 是只读解析,要求对已有 Root 的 `scope.read`。`create_if_absent=true` 是可创建的路由准备: +Root 不存在时执行 Origin `scope.contribute`、`server.admin`/可信 provisioner、Root/mapping/policy/Binding 同事务闭环; +Root 已存在时要求调用 Principal 同时拥有 Origin 与 Root 的 `scope.contribute`。`root_contributor` 省略时默认调用 +Principal;其值不会从 `subject_key` 推导。 + +### Create Source with subject_key + +```http +POST /v1/scopes/S_GROUP/sources +Content-Type: application/json +``` + +```json +{ + "source_type": "content", + "content": { + "role": "user", + "text": "请优先给我简洁结论" + }, + "subject_key": "U1" +} +``` + +```json +{ + "scope_id": "S_GROUP", + "source_type": "content", + "source_id": "source_01", + "content": { + "role": "user", + "text": "请优先给我简洁结论" + }, + "position": 101, + "content_digest": "sha256:...", + "subject_projection": { + "subject_key": "U1", + "root_scope_id": "R_U1", + "origin_source": { + "scope_id": "S_GROUP", + "source_type": "content", + "source_id": "source_01" + }, + "root_source": { + "scope_id": "R_U1", + "source_type": "content", + "source_id": "source_01" + }, + "status": "committed" + } +} +``` + +`201` 表示两条 Source 与投影关系都已提交;它不表示 Profile 已生成。`subject_projection` 始终用 `origin_source` 和 `root_source` 明确方向,读取关系任一端时也返回同一对地址。 + +幂等保证只覆盖同一次服务端命令及其数据库事务重试:服务端复用已经生成的 `source_id`,不会在 Root 重复插入。现有 HTTP Create Source 没有 `Idempotency-Key`;客户端在提交成功但响应丢失后重新发送 HTTP 请求,仍会创建一个新的 Source 及其 Root 副本。通用 HTTP 创建幂等应由独立 RFC 解决,本设计不隐含扩大其语义。 + +### Get Profile + +```http +POST /v1/profile/get +Content-Type: application/json +``` + +```json +{ + "target": {"subject_key": "U1"} +} +``` + +```http +HTTP/1.1 200 OK +ETag: "profile:R_U1:profile:user:12:sha256-abc" +Content-Type: application/json +``` + +```json +{ + "target": { + "scope_id": "R_U1", + "artifact_id": "profile:user", + "subject_key": "U1", + "root_scope_id": "R_U1" + }, + "artifact": { + "scope_id": "R_U1", + "artifact": { + "family": "profile", + "artifact_id": "profile:user", + "revision": 12 + } + }, + "media_type": "text/markdown", + "content": "# 用户画像\n\n用户偏好中文简洁回答。\n", + "content_digest": "sha256:...", + "generation": { + "mode": "automatic", + "source_after": 37, + "source_through": 42, + "created_at": "2026-09-07T02:04:18+08:00" + } +} +``` + +Profile 专用响应将内部 `ProfileContent.content` 展平为 Markdown 字符串。通用 Artifact Get 仍返回完整 `ProfileContent` object。 + +### Create, replace and rollback + +首次人工创建: + +```python +created = await client.profile.create( + target=ProfileTarget(subject_key=app_user.user_id), + content="# 用户画像\n\n用户偏好中文回答。\n", + reason="user confirmed initial profile", +) +``` + +替换必须原样回传 Get/Create 返回的不透明 ETag;Python Client 以 `if_match` 参数映射到 HTTP `If-Match` header: + +```python +updated = await client.profile.replace( + target=ProfileTarget(subject_key=app_user.user_id), + content="# 用户画像\n\n用户偏好中文简洁回答。\n", + if_match=created.etag, + reason="user edited profile", +) +``` + +回退创建新 Revision: + +```python +restored = await client.profile.rollback( + target=ProfileTarget(subject_key=app_user.user_id), + restore_revision=3, + if_match=updated.etag, + reason="restore user-confirmed version", +) +``` + +Profile Replace 和 Rollback 缺少 `If-Match` 返回 `428 Precondition Required`;与当前 Head ETag 不一致返回 +`412 Precondition Failed`。ETag 必须保持不透明,不能由客户端根据 Revision 自行拼接。 + +首期通用 Artifact Create/Replace 不接受 `family=profile`。以上专用 API 与 Profile Processor 在解析 +`profile:user/profile:local` 后直接调用内部 RecordService;通用 Artifact exact Get、Revision Get 和 List 仍可读取 +Profile。 + +### Generate now + +```python +receipt = await client.profile.generate( + target=ProfileTarget(subject_key=app_user.user_id), +) +``` + +```json +{ + "target": { + "scope_id": "R_U1", + "artifact_id": "profile:user", + "subject_key": "U1", + "root_scope_id": "R_U1" + }, + "status": "accepted", + "binding_name": "profile-source-window", + "source_through": 42, + "flush_generation": 8 +} +``` + +该接口只要求立即开始处理已经存在的新 Source。成功 HTTP 状态始终是 `200 OK`:已唤醒处理返回 +`{"status":"accepted"}`,没有新 Source 返回 `{"status":"idle"}`,已有未决 Candidate 返回 +`{"status":"review_pending"}`。 + +### Subject context aggregation API + +```http +POST /v1/subjects/context/prepare +Content-Type: application/json +``` + +```json +{ + "subject_key": "U1", + "query": "推荐适合用户的酒店", + "families": ["profile", "memory", "topic-memory", "skill", "experience"], + "max_bytes": 262144 +} +``` + +```json +{ + "subject_key": "U1", + "root_scope_id": "R_U1", + "scope_ids": ["R_U1", "S_U1_PROJECT"], + "items": [ + { + "address": { + "scope_id": "R_U1", + "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} + }, + "content": "# 用户画像\n\n用户偏好中文简洁回答。\n", + "selected_bytes": 58 + }, + { + "address": { + "memory": { + "scope_id": "S_U1_PROJECT", + "artifact": {"family": "memory", "artifact_id": "memory", "revision": 7} + }, + "entry_id": "hotel-preference", + "entry_version_id": "mev_01" + }, + "content": "国内酒店偏好大床房。", + "selected_bytes": 33 + } + ], + "conflicts": [ + { + "summary": "预算信息存在时间冲突", + "left": { + "scope_id": "R_U1", + "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} + }, + "right": { + "scope_id": "S_U1_PROJECT", + "artifact": {"family": "topic-memory", "artifact_id": "travel", "revision": 4} + } + } + ], + "used_bytes": 91, + "max_bytes": 262144, + "truncated": false +} +``` + +这是新增的 `SubjectContextAdapter` 及其 HTTP/Python adapter,不表示现有 Prepare Context 已支持 Subject Root 遍历。 +该 adapter 解析 `R_U1`,逐 Scope 授权后选择 Root 与真实 descendants,再调用各 family 现有的精确读取或召回入口, +完成去重、冲突标注、排序和按 `max_bytes` 装配。共享群聊 `S_GROUP` 不会因为 U1 是参与者而被纳入;首期也不会自动 +复制其已有 Artifact。所有 Artifact 返回 `ArtifactAddress`;Memory Entry 等 subresource 通过包含 `ArtifactAddress` +的 family-owned address 返回。 + +未来其他 Artifact Family 若复用本设计,应为 Root Source 注册自己的处理 binding,并把用户级 Artifact 生成到 `R_U1` 或其真实子 Scope。这样它们自然进入同一主体查询范围,而不需要给通用 Artifact 表增加 `subject_key`。 + +## Access control and privacy + +权限实现复用 [RFC 1396](1396_handoff_access_control.md) 的现有 `scope.*` 与 `artifact.*` action,不新增 +`subject.*` 或 `profile.*` action vocabulary: + +| Profile/Subject operation | 既有 action | +| --- | --- | +| 解析已有 Subject Root | 返回映射前要求对 Root 拥有 `scope.read`;授权不足固定返回 `403` | +| 创建 Subject Root | 调用 Principal 对 Origin 要求 `scope.contribute`,并要求其拥有 `server.admin` 或由可信 provisioning service principal 承担该 action | +| subject-keyed 业务 Source 写入 | Root 已存在时,对 Origin Scope 和 Root Scope 都要求 `scope.contribute` | +| Profile Get、Changes、Diff | 对逻辑 Profile 要求 `artifact.read`;通过 Scope 列表发现时还要求 `scope.read` | +| 人工创建首个 Profile、请求 Generate | 对目标 Scope 要求 `scope.contribute`;创建成功后按既有 Artifact 流程建立 owner | +| Profile Replace、Rollback | 对逻辑 Profile 要求 system-managed owner relation 和 `artifact.write` | +| Profile Candidate 审核 | 对目标 Scope 要求 `scope.review` | +| Profile Policy Get/Update | Get 要求 `scope.read`,Update 要求 `scope.admin` | +| Subject Context Prepare | 对纳入范围的每个 Scope 要求 `scope.read`,对精确资源授权路径要求 `artifact.read` | + +Parent、Root 映射和 `subject_key` 都不授予权限,也不能把业务 `user_id` 转换为 Principal。Root 首次创建时, +`root_contributor` 省略则取调用 Principal,显式提供时必须是认证系统已解析的 `user` 或 `service` PrincipalRef。在同一 +协调事务中创建 Root、映射、Policy 和该 Principal 的 `scope.contributor` Binding 后,内部路由才可以执行首次 Root +写入。已有 Root 不修改 Binding,并要求调用 Principal 同时通过 Origin 与 Root 的 `scope.contribute`。 + +Profile 必须在 RFC 1396 的 Artifact Family Access Profile registry 中显式注册: + +| Field | Profile registration | +| --- | --- | +| enabled | `true` | +| share_unit | `artifact`,即固定逻辑 `profile:user` 或 `profile:local` | +| shareable_states | `{committed}` | +| base_action | `artifact.read` | +| grantable_roles | `{artifact.viewer}` | +| selector | forbidden;不接受 family-owned subresource selector | +| transitivity | `none`;读取 Profile 不授予 lineage Source 或其他 Artifact 读取权 | +| mutation_semantics | direct owner 通过 `artifact.write` 修改 | + +该注册不增加 Profile 专用 action。后台 Processor 必须携带配置的 service/system Principal;空 Principal 不得执行生成。 + +隐私要求: + +- 日志、指标和错误默认不输出原始 `subject_key` 或 Source/Markdown 原文; +- 数据库直接保存业务 `user_id` 作为 `subject_key`,读取、备份和审计按用户标识保护策略处理; +- Root Source 是原文副本,需要与原 Source 使用一致的加密、保留和删除策略; +- 不在 Root Scope 的 title/summary 中写用户 ID; +- 聚合查询逐 Scope、逐 Artifact 授权,不泄露未授权 Scope 的存在或数量; +- 审核、编辑和回退记录操作者、时间、原因和目标 Revision。 + +## Error semantics + +| 场景 | 建议结果 | +| --- | --- | +| `subject_key` 为空或超过 256 字符 | `422 invalid_subject_key` | +| `subject_key` 不存在且禁止创建 Root | `404 subject_root_not_found` | +| Root 不存在,调用 Principal 缺少 Origin `scope.contribute` 或所需 `server.admin` | `403 Forbidden` | +| `root_contributor.type` 不是 `user/service` | `422 invalid_root_contributor` | +| Authorization Provider 无法事务性建立 Binding,且没有可用可信 provisioner | `503 relationship_management_unavailable` | +| 两个 key 试图绑定同一个 Root | `409 subject_root_binding_conflict` | +| 当前 Scope 是另一个用户的 Root | `409 subject_key_mismatch` | +| 公开请求无 key 直接写用户 Root | `422 subject_key_required` | +| Origin Source 已投影到另一个 key | `409 source_subject_conflict` | +| 原 Source 与 Root Source 相同身份但 payload 不同 | `409 source_projection_content_conflict` | +| 双写中任一步失败 | 整体回滚,不留下单边 Source | +| Subject Resolve 创建或命中已有 Root | 固定 `200 OK`,以 `created` 区分 | +| 没有新 Source 时 Generate | `200 idle` | +| 已有未决自动 Profile Candidate | `200 review_pending`,不重复生成 | +| 已唤醒 Profile 处理 | `200 accepted` | +| 后台 LLM 或校验失败 | 保留旧 Head,不推进 Cursor,重试 | +| Head 或 Cursor CAS 冲突 | 重读最新状态并重新处理 | +| Profile Create 已有 Head | `409 profile_already_exists` | +| 通用 Artifact Create/Replace 请求写入 `family=profile` | `422 profile_requires_dedicated_api` | +| Replace/Rollback 缺少 `If-Match` | `428 Precondition Required` | +| Replace/Rollback 的 ETag 与当前 Head 不一致 | `412 Precondition Failed` | +| Review 时 Head 已变化 | `409 profile_revision_conflict`,保留 Candidate 且不推进 Cursor | +| Profile Reject 缺少 `disposition`,或非 Profile Reject 携带该字段 | `422 invalid_rejection_disposition` | +| Rollback 目标 Revision 不存在 | `404 profile_revision_not_found` | +| 已认证但无权访问 Root、子 Scope 或 Profile | 固定 `403 Forbidden` | + +## Configuration + +```yaml +profile: + enabled: true + artifact_id: "profile:user" + local_artifact_id: "profile:local" + max_content_bytes: 262144 + processing_binding: "profile-source-window" + schedule: + cron: "0 2 * * *" + timezone: "Asia/Shanghai" + source_window_limit: 200 + max_concurrency: 8 + worker_timeout_seconds: 900 + retry_max_delay_seconds: 1800 +``` + +Schedule 是部署级配置。`generation_enabled` 和 `activation_mode` 是 Scope 级 Policy。首期不提供每个用户单独配置 Cron,以避免为大量用户创建独立 scheduler job;一个每日波次公平处理所有 dirty targets。 + +## OpenAPI impact + +`openapi/powercontext.yaml` 是契约事实源,需要完成以下修改并重新生成代码: + +1. `BaseArtifactFamily` 增加 `profile`,供通用 Artifact Get head、Get revision 和 List 使用; + `CreateArtifactRequest`、`ReplaceArtifactRequest` 的写入 union 保持不变,不增加 Profile 分支。 +2. 新增 `ProfileContent`、Profile 专用 request/response/page/diff/processing/policy schemas; + `ArtifactRevision.content` 继续为 object,不改为裸字符串。 +3. `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 都增加可选 + `subject_key` 与 `root_contributor`;`SourceRecord` 在保留 `receipt_identity` 等已有字段的基础上增加可选 + `subject_projection`。 +4. `CandidateFamily` 增加 `profile`;`ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` 和 + transport/internal `ReviewedProposal` union 增加 `ProfileContent`。 +5. `RejectArtifactCandidateRequest` 保留 `scope_id/candidate_id/expected_version/reason`,新增可选 + `disposition`;仅 Profile Candidate 要求该值非空。 +6. Profile Create、Get、Replace、Rollback 的成功响应都声明 `ETag` header;Replace/Rollback 声明必填 + `If-Match`,缺失或失配沿用 `428/412`。 +7. 新增 Subject resolve/context prepare 和 Profile create/get/changes/diff/replace/rollback/generate/processing/policy + operations;每个 operation 只声明一个成功 HTTP 状态。其中 Resolve 固定 `200` 并返回 `created`,Generate 固定 + `200` 并返回 `status=accepted/idle/review_pending`。 +8. Subject Context schema 使用 `max_bytes`,Artifact 结果使用 `ArtifactAddress`,Memory Entry 等 subresource 地址 + 必须包含 Scope。 +9. Capabilities 暴露可读 `profile` family、`profile_generation` 和 Subject Context adapter 能力。 +10. 生成文件继续通过 `make api-generate` 产生,不能手工修改 `src/powercontext/http/_generated/`。 + +## Implementation plan + +1. 增加 Profile family read codec、`ProfileContent`、固定 Artifact identity、Markdown 规范化和内部 Profile RecordService; + 通用 Artifact Create/Replace union 保持不变。 +2. 增加 `pc_subject_roots`,实现 Root Resolve、唯一约束、Root Parent 保护,以及 Root/mapping/policy/ + `scope.contributor` Binding 的首次创建授权事务。 +3. 增加共享的 `SubjectSourceRoutingService`,让 `CreateSourceRequest`、`CaptureContentSourceRequest` 和 + `SubmitSourceObservationRequest` 携带 `subject_key` 时统一完成双 Scope 锁、同事务 Source 双写、投影关系和 + Pending upsert。 +4. 落地或复用通用 Pending、Cursor、Lease 和 Artifact Processing Supervisor。 +5. 增加带时区的 Profile CronTrigger,默认每天 `02:00 Asia/Shanghai`。 +6. 实现 Profile Worker:固定 Window、read-before-write、LLM Markdown、NOOP、Head/Cursor CAS。 +7. 增加 Revision Metadata、Candidate Window Metadata、Policy 单一 pending 指针、`ProfileContent` proposal union 和 + 两种 Reject disposition。 +8. 实现 Profile convenience API、全部响应类型、metadata-aware Python SDK、`ETag`/`If-Match`、历史、Diff、人工 + 替换和回退。 +9. 注册 Profile ArtifactFamilyAccessProfile,并实现使用 `max_bytes`、`ArtifactAddress` 和 scoped subresource address + 的新增 Subject Context adapter。 +10. 补充首次 Resolve 授权、双写原子性、群聊隔离、调度恢复、`lineage_only` 过滤、单成功状态、条件写、Review + disposition 和回退测试。 + +## Acceptance criteria + +### Scope and identity + +- U1、U2、U3 与一个群聊只产生 `R_U1/R_U2/R_U3/S_GROUP` 四个 Scope; +- 群聊 Scope 不被自动设置为任何用户 Root 的 child 或 context reference; +- 同一 `subject_key` 并发 Resolve 只产生一个 Root; +- 不同 `subject_key` 不能映射到同一个 Root; +- Root 的 Parent 始终为 `NULL`; +- Root 首次创建只有在 Origin `scope.contribute` 和 `server.admin`/可信 provisioner 均通过后,才在同一事务创建 + Root、mapping、policy 和明确 `root_contributor` 的 `scope.contributor` Binding; +- Root 已存在时,subject-keyed 写入同时检查 Origin 与 Root 的 `scope.contribute`,且不从 `subject_key` 推导 Principal; +- 通过 `subject_key=U1` 或 `scope_id=R_U1` 访问 Profile 都规范化到同一个 `profile:user`,不能创建 `profile:local`; +- Profile 内容与身份模型只使用 `subject_key`、`root_scope_id` 和固定 Profile Artifact 地址,不增加第二套用户标识或画像类型字段。 + +### Source routing + +- 不带 `subject_key` 时,各业务 Source 入口保持现有持久化行为; +- `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 都通过同一 + `SubjectSourceRoutingService`; +- 带 `subject_key` 时,总共写入 Origin 与对应 Root 两条 Source; +- 两条 Source 的 payload 相同,journal position 在各自 Scope 独立分配; +- 任一步失败均不留下单边写入; +- U1 Source 不改变 U2/U3 Root 的 journal、Pending 或 Cursor; +- 同一次服务端命令的事务重试不产生重复 Root Source;新的 HTTP Create 请求仍按现有语义创建新 Source; +- 多用户批量内容不能作为单条 subject-keyed Source 写入。 + +### Profile content and revision + +- Profile 内容只有完整 Markdown,不存在 Claim category、Claim 表或逐 Claim 风险等级; +- Markdown 通过 `ProfileContent` 编码到现有 BLOB,已有 Artifact 表无需 DDL 变更; +- 一个 Root 只有一个 `profile:user` Head,`artifact_id` 是唯一身份的一部分; +- Create 已存在时冲突,Replace 使用 CAS; +- 通用 Artifact Create/Replace 不接受 Profile;通用 exact Get、Revision Get 和 List 可以读取 Profile; +- Profile Create、Get、Replace 和 Rollback 均返回 `ETag`,后两者用 `If-Match` 并验证 `428/412`; +- Scope-local `ProfileRecord` 的 `subject_key/root_scope_id` 为 null; +- 自动生成、人工编辑、审核通过和回退都创建不可变 Revision; +- 无语义变化不创建空 Revision。 + +### Automatic generation + +- 默认每天 `02:00 Asia/Shanghai` 启动,Cron 和时区可配置; +- 业务 Source 提交不等待 LLM; +- Scheduler 错过时间后可恢复一个合并波次; +- Worker 固定 `(after, through]` Window; +- Worker 排除 `lineage_only` 系统 Source,过滤后为空的窗口不调用 LLM 但仍可推进 Cursor; +- 同一个 Profile 串行,不同 Profile 在并发上限内并行; +- 失败不推进 Cursor,且不影响其他用户; +- 无新 Source 时定时或手工 Generate 均不 rebuild。 +- Resolve 成功固定为 HTTP `200` 并返回 `created`;Generate 成功固定为 `200` 并返回 + `accepted/idle/review_pending`。 + +### Review and correction + +- 默认整篇 Profile 自动生效; +- Policy 可切换为整篇 `review_required`; +- Candidate 审核复用现有 Candidate 状态机; +- 每个 Profile Scope 同时最多一个未决自动 Candidate;其 Source Window 可在重启后恢复; +- Reject 必须显式选择 `reject_and_consume` 或 `reject_and_retry`,并分别验证推进或保留 Cursor; +- 人工 Replace 和 Rollback 必须使用当前 Head 的不透明 `ETag` 作为 `If-Match`; +- Rollback 创建新 Revision,不删除历史或倒拨 Head。 +- `ArtifactCandidate.proposal`、Revise proposal 和 `ReviewedProposal` 都接受 `ProfileContent`,ReviewService 使用固定 + Profile identity 和内部 RecordService。 + +### Database and API inventory + +- 所有新增表均有主键、唯一约束、外键和幂等语义; +- 现有表变更矩阵明确为无物理 DDL 变化; +- OpenAPI 枚举、union、Source schema 和全部新 operation 均有契约测试; +- Revision Metadata 的 rollback 复合外键、mode/null CHECK,以及 Candidate 固定 binding CHECK 均有约束测试; +- Profile ArtifactFamilyAccessProfile、固定 `403` 和 Root provisioning 授权均有 conformance test; +- Python SDK 示例覆盖 Resolve、三类 Source 入口、Profile 全部 API 和 metadata-aware `ProfileResponse`; +- Subject Context 使用 `max_bytes`,跨 Scope Artifact/Memory Entry 只返回完整 scoped address。 + +## Decision summary + +1. 新增 `profile` Artifact Family,首期只支持用户画像。 +2. `subject_key` 的值直接使用调用方业务 `user_id`,首期不支持其他主体类型。 +3. 一个 `subject_key` 一一对应一个 `root_scope_id`;Root 是普通 Scope,Parent 固定为 `NULL`。 +4. 群聊 U1、U2、U3 加共享群聊共四个 Scope;共享 Scope 不属于任一用户 Root 子树。 +5. subject-keyed Source 总共保存两份:业务 Scope 原始 Source 与对应用户 Root Source;两者同事务提交。 +6. `subject_key` 不加入现有 Source 或 Artifact 表,由新增映射与投影表表达关系。 +7. 用户 Root 中固定使用 `(root_scope_id, profile, profile:user)`;普通 Scope 可显式启用 `profile:local`。 +8. Profile 内容是完整 Markdown,通过 `ProfileContent` 的 `content` 字段编码进现有 BLOB;不设计 Claim category、逐 Claim 风险或 Claim 表。 +9. 默认每天 `02:00 Asia/Shanghai` 后台生成,Cron 与时区可配置;手工 Generate 只处理已有新 Source。 +10. 自动更新只由新 Source Window 触发;无新 Source 不 rebuild,无语义变化不创建 Revision。 +11. 默认整篇 Revision 自动生效,可按 Profile Scope 配置整篇 `review_required`。 +12. 人工创建、替换、审核通过和回退均创建不可变 Revision;Create/Get/Replace/Rollback 返回 `ETag`,Replace/Rollback + 使用 `If-Match`。 +13. 新增 `pc_subject_roots`、`pc_subject_source_projections`、`pc_profile_policies`、`pc_profile_revision_metadata`、`pc_profile_candidate_metadata`;若通用 processing substrate 尚未落地,再新增 `pc_artifact_processing_pending` 和 `pc_artifact_processing_leases`。 +14. `pc_scopes`、`pc_sources`、`pc_artifacts`、Head、Lineage、Cursor 和 Candidate 等现有表均无物理 DDL 变更。 +15. 三类通用业务 Source 请求、Candidate proposal union 和 Capabilities 做加法式扩展;通用 Artifact 写入 union + 不增加 Profile。所有携带 `subject_key` 的业务 Source 入口共用主体路由服务;新增 Subject 与 Profile convenience APIs。 +16. 未来其他 Artifact Family 可以复用 Subject Root 与 Root Source,但共享 Scope 内已有 Artifact 不会自动跨 Scope 生效。 + +# Drawbacks + +- 每条 subject-keyed Source 保存两份,增加存储、备份、保留和删除成本; +- Source 双写将一个原本单 Scope 的事务扩大为双 Scope 事务,需要一致锁顺序和更严格的并发测试; +- 现有 HTTP Source Create 没有客户端幂等键,响应丢失后的请求级重试仍可能形成重复事实及对应 Root 副本; +- `subject_key` 的正确性依赖调用方,PowerContext 不负责账号合并或纠正错误身份; +- 每天生成意味着画像存在最长约一天的正常延迟,需要即时结果时调用 Generate; +- 单一 Markdown 简化了存储与阅读,但首期失去 Claim 级查询、风险分级和精细 provenance; +- 共享 Scope 的已有 Artifact 不会自动成为用户制品;其他 family 需要显式消费 Root Source 后再生成到 Root; +- Root Source 原文副本扩大隐私和遗忘处理面。 + +# Rationale and alternatives + +## Why Subject Root is not the group Scope parent + +Scope 只有一个 Parent,而群聊可以有多个用户。把共享 Scope 挂给任何一个用户都会错误表达组织归属;尝试挂给多个用户则无法由现有模型表达。因此本 RFC 用 Source 投影表达主体关系,Parent 只保留真实组织关系。 + +## Why subject_key is family-neutral + +`subject_key` 首期直接等于业务 `user_id`,不引入 opaque key 或第二套身份。使用 `subject` 命名,是为了让未来 Memory、Topic Memory、Experience 等 family 可以复用同一 Root 寻址与 Root-local Source,而无需各自定义用户键。 + +## Why a ProfileContent wrapper instead of raw BLOB bytes + +当前 Artifact Repository 要求 family content 是 Pydantic Model,通用 `ArtifactRevision.content` 也是 object。使用 `ProfileContent` 把 Markdown 编码进现有 BLOB,可以不修改共享表和通用响应形状。直接写裸 Markdown bytes 会扩大到 Artifact Repository codec、运行时记录和 OpenAPI 的联合响应类型,首期没有必要。 + +## Why a daily Cron plus manual Generate + +每天低峰批处理能合并高频 Source,降低 LLM 调用量和并发压力;手工 Generate 为需要即时画像的业务提供明确出口。默认时间是策略而不是 Source/Artifact 语义,部署可调整。 + +## Why no Claim categories + +首期的主要消费者需要一份可直接注入上下文、可由人编辑的画像文档。将内容细分为固定 Claim category 会扩大抽取、Schema、迁移和审核复杂度。完整 Markdown 更适合先验证用户价值;以后如需结构化检索,可以从 Artifact Revision 建立可重建索引,而不改变事实源与制品身份。 + +# Prior art + +PowerContext 已有设计为本 RFC 提供了可复用的基础: + +- [RFC 0019](0019_local_source_memory_runtime.md) 定义 Source journal、消费 Cursor 与本地 Runtime 事务边界; +- [RFC 0050](0050_artifact_candidate_review_inbox.md) 定义不可变 Candidate 与审核状态机; +- [Topic Memory RFC](0000_topic_memory.md) 定义通用 Artifact processing pending、lease、Supervisor 与固定 Source Window; +- [RFC 1345](1345_scope_organization_and_agent_integration.md) 定义 Scope 的组织、隔离和共享语义; +- [RFC 1437](1437_source_artifact_rest_api.md) 定义 Source 和 Artifact 的公开身份、Create、Replace 与 Revision API。 + +本 RFC 复用这些机制,不为 Profile 建立第二套 Source、Artifact、Candidate 或后台任务身份空间。 + +[TencentDB Agent Memory 的官方 README](https://github.com/Tencent/TencentDB-Agent-Memory/blob/main/README.md) +描述了分层长期记忆与 Persona;[OpenViking Session 官方文档](https://github.com/volcengine/OpenViking/blob/main/docs/en/concepts/08-session.md#memory-extraction) +描述了异步 Memory Extraction、用户记忆空间和 `profile.md`。这些具体设计为后台分层处理、checkpoint、用户 Root +与读取已有画像后更新的工程取舍提供参考。 + +本 RFC 只借鉴异步、游标和读取旧画像后增量生成的工程思路,不沿用它们的身份模型。PowerContext 的 `subject_key <-> root_scope_id`、共享 Scope 双写和权限边界由本文独立定义。 + +# Unresolved questions + +首期功能与身份模型已经确定。RFC 合并前仍须明确 Root Source 与 Origin Source 的最小一致删除语义:删除或遗忘任一端时, +实现必须通过 `pc_subject_source_projections` 找到另一端并在同一授权操作中处理,不能让 Profile 后续继续消费已被要求 +遗忘的副本。物理删除、逻辑墓碑、已生成 Revision 的保留与审计规则需要与项目统一的数据删除协议对齐。 + +下列问题不阻塞本 RFC 合并,需在实际需求明确后独立设计: + +- 匿名用户转正式用户、账号别名、账号合并与 `subject_key` 迁移; +- HTTP Source Create 的跨请求 `Idempotency-Key`; +- 从 Profile Revision 派生 Claim 级查询、引用或风险分析索引; +- Profile 以外的 Artifact Family 如何选择并消费 Subject Root Source。 + +# Future possibilities + +后续 Artifact Family 可以注册自己的 Root-local Source processing binding,在不修改 `pc_sources` 或 +`pc_artifacts` 通用身份的前提下,把用户级 Memory、Topic Memory、Experience 或 Skill 派生到 Subject Root +及其真实子 Scope。是否启用这些派生能力应由各 Family 的独立设计决定。 + +Profile Markdown 可以产生可重建的结构化检索索引,用于段落级召回、冲突提示或证据定位。该索引应始终以不可变 +Profile Revision 和精确 Source lineage 为输入,不成为新的事实源,也不改变 Profile 的单一 Markdown 内容契约。 + +Subject Context 聚合可以继续演进 family quota、冲突解释、渐进式展开和可观察性,但必须维持逐 Scope、逐 Artifact +授权以及“共享业务 Scope 不因用户参与而自动进入 Root 子树”的边界。 + +在通用 Source 创建幂等、主体迁移和数据遗忘协议分别稳定后,Subject Root 路由可以复用这些能力,进一步降低 +网络重试、账号生命周期与原文双写带来的运营成本。 From 9a1fe421a5a92ef1221a0bac32a4d3bc6d8e7e99 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Mon, 7 Sep 2026 14:52:50 +0800 Subject: [PATCH 2/4] docs(rfc): number profile artifact RFC 1485 --- .../rfcs/{0000_profile_artifact.md => 1485_profile_artifact.md} | 2 +- .../rfcs/{0000_profile_artifact.md => 1485_profile_artifact.md} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/en/rfcs/{0000_profile_artifact.md => 1485_profile_artifact.md} (99%) rename docs/zh/rfcs/{0000_profile_artifact.md => 1485_profile_artifact.md} (99%) diff --git a/docs/en/rfcs/0000_profile_artifact.md b/docs/en/rfcs/1485_profile_artifact.md similarity index 99% rename from docs/en/rfcs/0000_profile_artifact.md rename to docs/en/rfcs/1485_profile_artifact.md index ba50e0012d..82c187a942 100644 --- a/docs/en/rfcs/0000_profile_artifact.md +++ b/docs/en/rfcs/1485_profile_artifact.md @@ -1,6 +1,6 @@ - Proposal Name: `profile_artifact` - Start Date: 2026-09-07 -- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) - Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), [RFC 1345](1345_scope_organization_and_agent_integration.md), diff --git a/docs/zh/rfcs/0000_profile_artifact.md b/docs/zh/rfcs/1485_profile_artifact.md similarity index 99% rename from docs/zh/rfcs/0000_profile_artifact.md rename to docs/zh/rfcs/1485_profile_artifact.md index c6cd28e6fb..a1126be6b8 100644 --- a/docs/zh/rfcs/0000_profile_artifact.md +++ b/docs/zh/rfcs/1485_profile_artifact.md @@ -1,6 +1,6 @@ - Proposal Name: `profile_artifact` - Start Date: 2026-09-07 -- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) - Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), [RFC 1345](1345_scope_organization_and_agent_integration.md), From 38b9dc917831cecff52715606e81548fd98748ee Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Mon, 7 Sep 2026 19:20:44 +0800 Subject: [PATCH 3/4] docs(rfc): simplify profile storage and subject writes --- docs/en/rfcs/1485_profile_artifact.md | 2533 +++++++------------------ docs/zh/rfcs/1485_profile_artifact.md | 2142 ++++++--------------- 2 files changed, 1241 insertions(+), 3434 deletions(-) diff --git a/docs/en/rfcs/1485_profile_artifact.md b/docs/en/rfcs/1485_profile_artifact.md index 82c187a942..ad0e766280 100644 --- a/docs/en/rfcs/1485_profile_artifact.md +++ b/docs/en/rfcs/1485_profile_artifact.md @@ -1,2054 +1,863 @@ - Proposal Name: `profile_artifact` - Start Date: 2026-09-07 - RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) -- Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), - [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), - [RFC 1345](1345_scope_organization_and_agent_integration.md), - [RFC 1396](1396_handoff_access_control.md), and [RFC 1437](1437_source_artifact_rest_api.md) +- Related RFCs: [Scope organization](1345_scope_organization_and_agent_integration.md), + [Access control](1396_handoff_access_control.md), [Source and Artifact REST API](1437_source_artifact_rest_api.md), + [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](0000_topic_memory.md) # Summary -This RFC adds the `profile` Artifact Family to PowerContext. The first release defines only one fixed user Profile; it -does not expose a profile-type field, other Profile types, or a Profile Schema Registry. +This RFC adds the `profile` Artifact Family: a complete Markdown profile derived from the Sources in one Scope. +User profiles are the principal use case; a multi-user conversation Scope can also have an overall profile. +Profile reuses existing Artifact, Head, Lineage, Candidate, and Source Cursor tables. It adds only +`pc_profile_policies`, without changing columns, indexes, or constraints on existing tables. -A Profile is a rebuildable, Source-derived complete snapshot, not a source of truth. A user Profile has a fixed address: - -```text -Head identity: -(root_scope_id, family="profile", artifact_id="profile:user") - -Exact revision identity: -(root_scope_id, family="profile", artifact_id="profile:user", revision) -``` - -`subject_key` is the business `user_id` supplied directly by the caller when creating a Source. PowerContext does not -generate another user identifier or interpret, concatenate, or normalize this value. The name `subject_key` allows the -`subject_key -> root_scope_id` subject-addressing and Source-projection mechanism to be reused by other Artifact Families -in the future; the first release still fixes the subject to a user. - -Scope organization uses one design: - -- each `subject_key` maps one-to-one to a user Root Scope; -- a shared business Scope is not attached beneath any user's Root; -- a Source with a `subject_key` is written in one transaction to both the business Scope and that user's Root Scope, for - exactly two persisted Source records; -- the Profile Processor consumes only the Source journal in a Root Scope, so one user never triggers another user's - Profile processing; -- an ordinary Scope without a `subject_key` may still explicitly enable a Scope-local Profile. - -Profile content is not split into Claim categories, Claim rows, or risk levels. The LLM produces complete Markdown, -stored as `ProfileContent.content` in the existing `pc_artifacts.content` BLOB. Automatic generation runs daily at -`02:00` by default in the deployment's configured IANA time zone, which defaults to `Asia/Shanghai`; callers may change -the Cron expression and time zone or request immediate generation. +Subject addressing uses a caller-provided `subject_key`, mapped to an ordinary Scope through existing +`pc_scope_bindings`. A new subject Source endpoint stores one Source in the business Scope and another in the bound +subject Scope in one transaction. Existing single-Scope Source endpoints remain single writes. Enabled Scopes with +new evidence are processed daily at `02:00 Asia/Shanghai` by default, with configurable scheduling, manual Flush, +Candidate review, manual editing, and restoration through Replace. Subject bindings provide routing without changing +Scope storage, organization, or authorization semantics. # Motivation -User-facing Agents need to apply one long-lived Profile across sessions, tasks, and business Scopes. Generating a -Profile only inside each original business Scope creates multiple Profiles for the same user. Adding a generic -`user_id` column to every Source and Artifact would instead conflate storage ownership, content subject, content author, -and authorization principal. - -Multi-party conversations make this distinction clearer. One group-chat Scope can contain messages from U1, U2, and -U3, but `pc_scopes.parent_scope_id` has only one value: the group Scope cannot simultaneously be a child of all three -user Roots. The correct design preserves the group Scope's original organization, copies each user's own Sources -precisely into that user's Root, and generates the user Profile in the Root. - -This design keeps general-purpose Source, Scope, and Artifact as the fact and artifact infrastructure, while adding a -narrow convenience layer for subject routing. The integrating application remains responsible for deciding how -business users, conversations, and Sources correspond. PowerContext provides stable Root resolution, reliable -dual-Scope Source writes, background Profile generation, and Revision maintenance. - -## Goals - -1. Add the `profile` Artifact Family while reusing the existing internal Artifact record, Head, Revision, Lineage, and - CAS semantics. The first release does not add Profile to the generic Artifact Create/Replace request unions. -2. Support only a fixed user Profile in the first release; do not design profile-type extension, Claim categories, or a - per-Claim risk model. -3. Use the caller's business `user_id` as `subject_key` and establish an immutable one-to-one - `subject_key <-> root_scope_id` mapping. -4. Support Sources from different users in a shared Scope, while ensuring that a new Source from one user advances only - that user's Root journal. -5. Persist a Source with a `subject_key` exactly twice: once in the original business Scope and once in the corresponding - user Root. -6. Generate Profiles in the background at `02:00` daily by default, with configurable Cron and time zone, without making - the business Source write path wait for an LLM. -7. Store complete Markdown Profiles in the existing `pc_artifacts.content` BLOB, without adding a Claim table or Profile - content columns. -8. Activate revisions automatically by default, while allowing an entire Revision to enter Review according to its - Profile Scope policy. -9. Support manual creation, replacement, review, history inspection, diffing, and non-destructive rollback. -10. Specify every new table and API, all uses of existing tables, and all changes to existing APIs. -11. Allow future Artifact Families to reuse Subject Root and Root-local Sources, without implementing other subject - types or other artifact derivation in the first release. - -## Non-goals - -The first release explicitly excludes: - -- other Profile types such as `team`, `agent`, `customer`, or `driver`; -- custom Profile types, subject types, Profile Schema registration, or arbitrary Claim Schemas; -- user registration, authentication, account aliases, anonymous-to-registered conversion, account merging, or user-ID - generation; -- guessing from natural language which user owns a Source; -- binding one Source to multiple `subject_key` values; -- adding a generic `subject_key` column to `pc_sources` or `pc_artifacts`; -- accepting `family="profile"` through the generic Artifact Create or Replace endpoints in the first release; -- automatically attaching a shared business Scope beneath a user Root, or treating Scope Parent as authorization; -- automatically copying existing Memory, Skill, Experience, Topic Memory, or other Artifacts from a shared Scope; -- automatically rebuilding a Profile because the model, prompt, or implementation version changed when no new Source - exists; -- a general deletion, withdrawal, and forgetting protocol for every Source and Artifact Family; however, the minimum - consistent-cleanup semantics for the Origin/Root duplicate must be decided before this RFC merges; -- implementing the complete subject-derived lifecycle for Artifact Families other than Profile. - -# Guide-level explanation - -## Terminology and invariants +A user can participate in multiple conversations and share a group-chat Scope with other users. Applications need +the complete discussion in that Scope while accumulating a user's relevant messages in a long-lived independent +Scope. Both Scopes can use the Artifact capabilities already supported by PowerContext. -| Term | Meaning | -| --- | --- | -| `subject_key` | The business `user_id` supplied directly by the caller; it denotes only a user subject in the first release | -| `root_scope_id` | An ordinary `pc_scopes.scope_id` that PowerContext creates for a `subject_key`, serving as the stable storage anchor for that user's long-lived artifacts | -| Business Scope | A Scope organized by a conversation, group chat, project, or application; it may contain Sources from multiple users | -| Root Source | The same Source copied from a business Scope into a user Root; its content is identical to the origin Source | -| Scope-local Profile | A local Profile generated directly from the Sources of an ordinary Scope without using `subject_key` | -| Profile Head | The current Profile Revision at the fixed `artifact_id` within a Scope | +Applications determine user identities, content attribution, and when to manage bindings. PowerContext provides Scope +Bindings, a reliable dual-write convenience endpoint, and Scope-based profile generation. Applications need neither +make group chats children of user Scopes nor add `user_id` database columns to every Source and Artifact. -The following invariants must hold: +## Goals and non-goals -```text -one subject_key -> exactly one root_scope_id -one root_scope_id -> at most one subject_key +- At most one Profile Head per Scope, with fixed `family="profile"` and `artifact_id="profile"`; every Revision is a full snapshot. +- Profile is a derived artifact, not a source of truth. Automatic evolution requires new Sources; no rebuild API is added. +- Retain `subject_key`; `subject_type` defaults to and only supports `user` initially, with no subject-type or profile-schema registry. +- A subject Scope is ordinary. Automatic creation uses `parent_scope_id=NULL`; no special Root type or Parent restriction on existing Scopes is introduced. +- Add only one Profile policy table. Generation and review metadata are encoded in existing BLOBs; no Subject, projection, job, or Revision Metadata tables are added. +- Prefer existing Source, Artifact, Scope Binding, authorization, and Candidate APIs; add no subject-specific Artifact CRUD or aggregation API. +- User authentication, reverse one-to-one subject constraints, rebinding migrations, account merging, automatic cross-Scope grants, and global Source deletion cascades are outside scope. +- Source ingestion does not guarantee automatic generation of every Artifact Family. Each Family retains its existing activation, generation, and lifecycle rules. -one subject-keyed Source -> one origin Source + one Root Source -one origin Source -> at most one subject_key - -one user Root -> at most one Profile Head -``` - -`subject_key` answers "which user subject's data should this Source enter?" It is not equivalent to: - -- who is currently signed in; -- who owns the underlying resource; -- which users are mentioned in the content; -- who is authorized to read the Root; -- the general unique key of a Source or Artifact. +# Guide-level explanation -The caller must ensure that `subject_key` is unique, stable, and never reused within one PowerContext deployment and -database. PowerContext performs a case-sensitive, byte-exact comparison of the complete string. Callers should use an -internal user ID, not a directly identifying value such as a name, phone number, email address, or government ID. +## Ordinary scopes and subject bindings -## Scope organization +`subject_key` is the caller's business user ID, such as `U1`. PowerContext stores it unchanged and compares it exactly; +it neither generates a replacement user ID nor normalizes the value. Callers must avoid collisions between distinct +business users within the deployment's subject identity domain. The identity string is not an authentication credential. -### Group chat example: exactly four Scopes +| API field or internal convention | Scope Binding field | Example | +| --- | --- | --- | +| Server constant | `integration` | `subject` | +| `subject_type`, default and only supported value `user` | `kind` | `user` | +| `subject_key` | `external_id` | `U1` | +| Resolved ordinary Scope | `scope_id` | `S_U1` | -When group chat G1 contains users U1, U2, and U3, there are exactly four Scopes: +`subject_scope_id` is an optional Scope ID in the subject write request and the actual Scope ID in its response, +not a new Scope type or database column. Add optional `allow_default` to existing Scope Binding Resolve, defaulting +to true to preserve existing fallback behavior. Subject queries pass false and exactly one binding key; a miss returns +404. Then use the returned `scope_id` with existing Artifact and domain APIs. Internal dual-write resolution always +reads the exact key and never falls back to the default Scope. ```mermaid flowchart LR - K1["subject_key = U1"] --> R1["root_scope_id = R_U1"] - K2["subject_key = U2"] --> R2["root_scope_id = R_U2"] - K3["subject_key = U3"] --> R3["root_scope_id = R_U3"] - G["business scope_id = S_GROUP
U1 + U2 + U3 group chat"] - - G -. "U1 Source copy" .-> R1 - G -. "U2 Source copy" .-> R2 - G -. "U3 Source copy" .-> R3 + K1["subject/user/U1"] --> S1["S_U1: ordinary Scope"] + K2["subject/user/U2"] --> S2["S_U2: ordinary Scope"] + K3["subject/user/U3"] --> S3["S_U3: ordinary Scope"] + G["S_GROUP: group-chat Scope"] + S1 --> P1["Profile, Memory, other enabled artifacts"] + S2 --> P2["Profile, Memory, other enabled artifacts"] + S3 --> P3["Profile, Memory, other enabled artifacts"] + G --> PG["Group Profile, Topic Memory, other enabled artifacts"] ``` -| Scope | Purpose | `parent_scope_id` | -| --- | --- | --- | -| `R_U1` | U1's Root Sources, Profile, and future user-level artifacts | `NULL` | -| `R_U2` | U2's Root Sources, Profile, and future user-level artifacts | `NULL` | -| `R_U3` | U3's Root Sources, Profile, and future user-level artifacts | `NULL` | -| `S_GROUP` | Stores the complete original group-chat record | Preserves the business-defined parent; does not point to `R_U1/R_U2/R_U3` | +The example has four Scopes. Binding arrows are neither Parent nor Context Reference relationships. A subject Scope +does not contain all artifacts from the group chat. Querying `S_U1` follows existing authorization and query scope. +Applications explicitly compose requests when they need other Scopes. This RFC adds neither cross-Family conflict +resolution nor automatic traversal of shared group chats. Existing PrepareContext still uses the current Scope and +direct Context References; this RFC does not automatically expand its supported Families. -The dashed lines represent Source projections, not `parent_scope_id` or `pc_scope_context_references`. This RFC does not -automatically write a Scope Parent or Context Reference because a user participates in a group chat. +## Single-scope writes and subject writes -### What a Root Scope records +Existing `POST /v1/scopes/{scope_id}/sources` writes only to the addressed Scope and still does not accept +`subject_key`. Subject writes use a separate endpoint: -A Root Scope is itself an ordinary `pc_scopes` row. This RFC adds no `profile_root_scope` table and does not place user -information in `pc_scopes.title` or `summary`: +```http +POST /v1/scopes/S_GROUP/subject-sources +Content-Type: application/json -```text -pc_scopes - scope_id = R_U1 - title = "Subject Root" - summary = "User subject data root" - parent_scope_id= NULL - version = 1 +{ + "subject_type": "user", + "subject_key": "U1", + "subject_scope_id": "S_U1", + "source_type": "content", + "content": {"speaker": "U1", "text": "I prefer concise answers in Chinese"} +} ``` -The mapping between `subject_key=U1` and `R_U1` is stored in the new `pc_subject_roots` table. Actual content is stored -in: - -- `pc_sources`: Sources projected for U1 from different business Scopes; -- `pc_artifacts` / `pc_artifact_heads`: U1's Profile Revisions and Head; -- the Lineage, Cursor, Pending, Policy, and Profile Revision metadata tables. - -The Root Scope is a storage and aggregation anchor, not a user-account record. It does not perform authentication or -automatically grant access. - -### Parent rules - -1. A user Root's `parent_scope_id` is always `NULL`. -2. A Scope registered as a Root cannot later receive a Parent through Scope Update. -3. A shared business Scope preserves its own business organization and is not automatically reparented to any user - Root. -4. When the business genuinely has a single-user child Scope, it may explicitly create that Scope as a descendant of a - Root; this is not a Source Create side effect. -5. Context aggregation by `subject_key` selects the Root and its true descendants by default; a shared group-chat Scope - is not in any user's subtree. +The business Scope `S_GROUP` must exist. Resolve or establish the subject binding as follows: -### Source is stored exactly twice +| Existing binding | Optional `subject_scope_id` | Result | +| --- | --- | --- | +| Present | Omitted or matches | Reuse the binding | +| Present | Does not match | `409 subject_scope_conflict`; write no Sources | +| Absent | Supplied | Validate the existing Scope and permissions, then establish the binding | +| Absent | Omitted | Create an ordinary Scope under the authorization rules and establish the binding | -After one Source from U1 is written in the group chat, the database contains exactly two Sources with identical content: +Each request generates one `source_id` and uses it in both Scopes. Since the complete Source identity includes +`scope_id`, equal Source IDs do not conflict. The new endpoint returns `201` and two existing `SourceRecord` values. +Their `content`, `content_digest`, `source_type`, and `source_id` match; their `scope_id` values differ. Positions are +allocated independently and may happen to be equal. Both records are Sources with no primary/replica role. -```text -(S_GROUP, source_type="content", source_id="source_01") # origin -(R_U1, source_type="content", source_id="source_01") # Root copy +```json +{ + "subject_type": "user", + "subject_key": "U1", + "subject_scope_id": "S_U1", + "sources": [ + {"scope_id": "S_GROUP", "source_type": "content", "source_id": "src_01", + "content": {"speaker": "U1", "text": "I prefer concise answers in Chinese"}, "position": 101, "content_digest": "sha256:"}, + {"scope_id": "S_U1", "source_type": "content", "source_id": "src_01", + "content": {"speaker": "U1", "text": "I prefer concise answers in Chinese"}, "position": 42, "content_digest": "sha256:"} + ] +} ``` -Source identity includes `scope_id`, so both records may reuse the same `source_type + source_id`. The new path first -generates a deployment-unique Source ID and then reuses the same `ContentSource` in both Scopes. Their `payload` values -are therefore identical, but their `journal_position` values are assigned independently by the `S_GROUP` and `R_U1` -Source journals. A new relationship table records the exact address and content digest on each side. +`` is a placeholder for the SHA-256 of canonical JSON content. Response order is business Scope, then subject +Scope. Equal target Scopes produce `422 distinct_scopes_required`; use the existing endpoint for a single write. +The new endpoint follows base Create retry semantics: no Idempotency-Key, and a new HTTP request generates a new +Source ID. Internal transaction retries for one request reuse its generated ID. -U1's Source is not written to `R_U2` or `R_U3`; a U1 write therefore advances only the `S_GROUP` and `R_U1` journals. - -There is one exception: if the caller creates a Source with `subject_key=U1` directly in `R_U1`, the origin Scope is -already the target Root, so only one Source is stored and no self-copy is created. - -A user Root is a protected subject storage boundary. A public Source Create request that writes directly into a Root -must include the `subject_key` matching that Root's mapping. A missing or mismatched key is rejected, preventing -unattributed Sources from contaminating the global Profile. - -### Multi-user Source boundary - -Each Source Create request may carry at most one `subject_key`. In a group chat, the integrating application should -split Sources by speaker or independently attributable message: +Per-message ingestion can use the following proposed Client method. Scope provisioning, binding management, and +Policy configuration happen before message ingestion: ```python -await client.sources.create( - scope_id="S_GROUP", - content={"role": "user", "text": "Please give me the concise conclusion first"}, - subject_key="U1", -) - -await client.sources.create( - scope_id="S_GROUP", - content={"role": "user", "text": "I prefer a detailed analysis"}, - subject_key="U2", -) +messages = [ + {"user_id": "U1", "text": "I prefer concise answers in Chinese"}, + {"user_id": "U2", "text": "Give the conclusion first, followed by detailed analysis"}, +] +for message in messages: + await client.create_subject_source( + "S_GROUP", + CreateSubjectSourceRequest( + subject_key=message["user_id"], + content={"speaker": message["user_id"], "text": message["text"]}, + ), + ) +``` + +Do not also call group-chat Source Create for the same message, which would store it twice in that Scope. +Applications split multi-user conversations and supply speaker attribution rather than asking the LLM to infer routing. +Messages such as "agreed" require the relevant context; otherwise profile generation must abstain from inference. + +## Binding management semantics + +Subject writes only resolve or establish a binding. Existing management APIs retain rebind and unbind operations and +allow multiple subjects to bind to one Scope. Neither operation moves or deletes any Source or Artifact. Automatic +creation after unbinding can create a new Scope. Multiple users bound to one Scope accumulate mixed data and an +overall profile; that Scope is not an exclusive data space for one user. + +A request uses the binding it actually reads and fixes its target after resolution. Concurrent management changes do +not redirect that request; the response reports its actual target. No binding version, reverse uniqueness check, +immutability constraint, or migration protocol is added. Matching Source IDs are not a global cross-Scope projection +index. Discovering every copy from one Source or deleting copies through a cascade is not promised. + +## Profile meaning and lifecycle + +A Profile captures stable characteristics supported by evidence in its Scope. User Scopes produce user profiles; +group-chat Scopes can describe participant characteristics and shared preferences. Mixed evidence should say +"U1 prefers concise answers; U2 needs detailed analysis", without combining those preferences into one person. + +```text +Head: (scope_id, family="profile", artifact_id="profile") +Revision: (scope_id, family="profile", artifact_id="profile", revision) ``` -A batch Source containing messages from multiple users must be split first; PowerContext does not ask an LLM to guess -which user owns the entire content. A Source without `subject_key` is stored only in the current Scope and enters no -user Root. If that ordinary Scope has explicitly enabled a Scope-local Profile through `pc_profile_policies`, the same -Source transaction also upserts the current Scope's `profile-source-window` Pending row so the daily Scheduler can -discover it. +Each Scope independently maintains one Profile. Identical content in two Scopes participates in their enabled +generation flows separately. Outputs may differ because their other evidence and previous profiles differ. +Updates use the previous profile and new evidence, deterministically remove exact duplicates, merge semantic +duplicates, and favor the latest valid evidence for explicit conflicts. Preserve still-valid information and avoid +turning a temporary instruction into a lasting preference. There are no Claim categories or per-Claim risk levels. -### Root creation and authorization +Automatically created subject Scopes receive an enabled, automatic Profile Policy. Reusing an existing Scope does +not silently change its Policy. Ordinary group-chat Scopes and disabled user Scopes can explicitly enable generation +through the Policy API. Other Families' configurations are unaffected. -`subject_key` never derives a Principal. The calling Principal comes only from authentication middleware or a trusted -internal bridge. Optional `root_contributor` is an explicit existing `PrincipalRef`; when omitted it defaults to the -calling Principal, and its type can only be `user` or `service`. +Background generation processes new Sources daily at `02:00 Asia/Shanghai` by default. With `review_required`, it +creates a Candidate and leaves the committed profile unchanged. Users may revise and approve the Candidate, or +reject it and consume that window. Manual Create/Replace retains existing explicit-commit behavior and is not blocked +by the automatic-generation review policy. -When a Root does not exist, automatic creation must close the complete authorization loop: +# Reference-level explanation -1. The calling Principal must have `scope.contribute` on the Origin Scope. -2. The same calling Principal must also have `server.admin`. A deployment may instead configure a trusted provisioning - service Principal to exercise `server.admin` internally, but that does not replace the calling Principal's - `scope.contribute` on the Origin. -3. In one coordinated transaction, create the `pc_scopes` Root, `pc_subject_roots` mapping, and default - `pc_profile_policies`, and use the Access Control `RelationshipWriter` to create a `scope.contributor` Binding for the - explicit `root_contributor`. -4. Only after the Binding succeeds does the routing service's internal branch write the first Root Source, projection - relationship, and Pending row. A failure at any step commits neither the Origin Source, the Root, nor a one-sided - authorization relationship. +## Scope binding and atomic source transaction -If an external Authorization Provider's `RelationshipWriter` cannot participate in this coordinated transaction, -automatic creation must return `503 relationship_management_unavailable`. The deployment must first use a trusted -provisioning flow to create the Root, mapping, Policy, and Binding, and only then submit the business Source. It must not -write the Origin first and fill in authorization asynchronously. +Internal `ensure_binding` uses the existing `(integration, kind, external_id)` unique key and inserts only when absent; +it never uses an overwriting upsert. On a concurrent insertion conflict, roll back the entire attempt, reread the +binding, and apply the resolution rules. Never commit an unreferenced new Scope before retrying. Existing management +`set_binding/clear_binding` behavior remains unchanged and does not have to adopt ensure semantics. -An existing Root does not require `server.admin`, but the calling Principal must have `scope.contribute` on both the -Origin and Root Scopes. A request's `root_contributor` cannot modify an existing Binding and cannot impersonate the -calling Principal. +All database operations in a subject write share one connection and transaction: -### Atomic write flow +1. Validate the request and business Scope permissions, normalize content, and generate one Source ID. +2. Read the binding; if absent, validate the supplied Scope or create an ordinary Scope, then insert the binding. +3. Authorize the actual subject Scope and reject equal target Scopes. New Scope authorization is specified below. +4. Acquire journal write locks in sorted `scope_id` order and store the same Source value twice, allocating each position independently. +5. Commit Scope, binding, any new Policy, both Sources, and journal heads together; roll back everything on failure. ```mermaid sequenceDiagram participant App as Application - participant API as Source API - participant PEP as Access Control - participant DB as PowerContext DB - - App->>API: Create Source(scope=S_GROUP, subject_key=U1) - API->>PEP: require scope.contribute on Origin - alt Root absent - API->>PEP: require server.admin or trusted provisioner - else Root exists - API->>PEP: require scope.contribute on Root - end - API->>DB: BEGIN - API->>DB: resolve or atomically provision U1 -> R_U1 - API->>DB: if new, bind explicit root_contributor - API->>DB: insert origin Source into S_GROUP journal - API->>DB: insert identical Source into R_U1 journal - API->>DB: insert pc_subject_source_projections relation - API->>DB: upsert Profile pending for R_U1 - API->>DB: COMMIT - API-->>App: 201 Source + committed subject projection -``` - -The diagram uses the HTTP Source API to illustrate the call, but the dual write is not private logic in the HTTP -handler. The Runtime API, Python SDK, MCP, Connectors, and other business-ingestion adapters must all enter the same -`SubjectSourceRoutingService` application service whenever they carry a `subject_key`. That service consistently -performs Root Resolve, dual-Scope locking, the dual Source write, projection recording, and Pending upsert. No entry -point may implement only part of this flow or bypass it by directly writing an Origin Source with subject attribution. - -The business entry request types explicitly extended in the first release are `CreateSourceRequest`, -`CaptureContentSourceRequest`, and `SubmitSourceObservationRequest`. All three share the -`subject_key/root_contributor` routing fields and the same application service. A Connector submitting an observation -must not bypass this service. - -Internal `lineage_only` system Sources generated as Artifact-write provenance, and internal domain Sources maintained by -an Artifact Family, are not business entry Sources. They do not accept `subject_key` or enter the subject-projection -service. They remain in the target Scope and are written directly by the corresponding domain service. - -The dual write must satisfy the following requirements: - -- the origin Source, Root Source, projection relationship, and Root Profile Pending row commit in the same database - transaction; any failure rolls back the whole transaction; -- when locking two Source journals, locks are acquired in `scope_id` order to avoid concurrent deadlocks; -- an internal retry of one Source operation reuses the same `source_type + source_id`; an identical payload is an - idempotent success, while a different payload returns a conflict; the Source ID must be deployment-unique when it is - generated; -- database uniqueness constraints and the transaction jointly enforce the one-to-one mapping between `subject_key` and - Root; -- a Source is an immutable fact record. An incorrect `subject_key` cannot be reassigned in place; the caller appends a - corrective Source and a later Profile Revision incorporates the correction. - -## Profile Artifact - -### Identity and singleton - -A subject-keyed user Profile is fixed at: - -```text -(root_scope_id, family="profile", artifact_id="profile:user") -``` - -The first write in a Root uses the Profile Create convenience endpoint. A subsequent Profile Create when `profile:user` -already exists returns `409 Conflict`; later writes must use Profile Replace. Profile Replace must echo the current -Head's opaque `ETag` unchanged in `If-Match`. Profile APIs first resolve `ProfileTarget` to the scoped fixed address and -then reuse the internal `RecordService` persistence and Head CAS primitives. They do not derive an ID through a generic -family writer and do not introduce a second concurrency contract in which a Revision in the request body replaces the -HTTP precondition. - -The generic Artifact Create and Replace endpoints do not accept `profile` in the first release. Exact generic Artifact -Get, List, and Get Revision do accept `family="profile"`, because they read an already resolved Artifact identity rather -than choosing which Profile singleton to write. - -An ordinary Scope without a `subject_key` may explicitly enable a Scope-local Profile: - -```text -(scope_id, family="profile", artifact_id="profile:local") -``` - -A shared or multi-user Scope does not enable a Scope-local Profile by default, preventing U1, U2, and U3 from being -combined into one Profile. - -### Profile content - -A Profile Revision is a complete current Markdown snapshot. The first release defines no Claim categories, Claim keys, -structured Claim list, or per-Claim risk levels. - -To preserve the existing Artifact Repository constraint that family content is a Pydantic Model, Profile uses a model -with a single body payload: + participant API as Subject Source API + participant DB as Existing tables + Policy + App->>API: business scope + subject_key + optional subject_scope_id + content + API->>DB: Begin transaction; read/ensure binding + API->>DB: Authorize actual scopes; lock journals in scope order + API->>DB: Insert (S_GROUP, content, src_01) + API->>DB: Insert (S_U1, content, src_01) + API->>DB: Commit both Sources and journal heads + API-->>App: 201, actual scope IDs and two SourceRecords + Note over API,DB: No LLM invocation on the Source write path +``` + +Binding transaction retries are not API idempotency. Existing Source repository rules still reject the same identity +with different payloads. Subject dual writes initially support only the `content` Source accepted by the base API. +Existing capture, observation, Connector, and MCP single-write entry points do not implicitly duplicate writes; +integrations needing dual writes call the new application service/Client method. Internal `lineage_only` Sources +never use the subject write endpoint. + +## Authorization and confidentiality + +Reuse existing actions: require `scope.contribute` separately on the business and subject Scopes; use existing +`scope.read/artifact.read` for reads. When establishing an absent binding, also require the management permission +required by the existing Binding management endpoint, namely `server.admin`. Automatic Scope creation also follows existing Scope +Create's `server.admin`. In the same transaction, the existing RelationshipWriter creates a `scope.contributor` role +binding for the authenticated calling Principal on that newly created Scope. This bootstrap applies only to new +Scopes; `server.admin` is not permission to contribute to arbitrary existing Scopes. It is behavior of the new +convenience endpoint, not a change to existing Scope Create. Authorization-disabled deployments retain their existing mode. + +The current authorization repository opens its own transactions. Implementation needs an internal write path that +accepts an existing connection, so new-Scope authorization, audit, and relationship revisions commit in the subject +write transaction. Do not invoke a public management API that commits permissions independently. Public permission +management semantics remain unchanged. + +A subject key never derives a Principal or replaces permission checks. Policy updates require `scope.admin`, Flush +requires `scope.contribute`, and Candidate operations use existing Review permissions. Background processing runs as +a trusted Runtime service identity and processes only Scopes permitted by the deployment. + +Register `profile` in existing Artifact Access Profiles: enabled=true, share_unit=artifact, +shareable_states={committed}, base_action=artifact.read, grantable_roles={artifact.viewer}, selector=forbidden, +mutation_semantics={artifact.write}. Candidates are not exposed as committed Artifacts. Logs omit raw subject_key, +Source content, and profile content by default. + +## Profile content and server-owned metadata + +Markdown is stored in `ProfileContent.content`; generation metadata is encoded alongside it in the existing +`pc_artifacts.content` BLOB. Use the current codec's Pydantic JSON UTF-8 bytes, without describing that codec as +RFC 8785. Public `content_digest` still follows the base API's canonical JSON rules. The LLM generates only Markdown; +the server constructs generation metadata. Models and clients cannot forge review status, timestamps, or Source windows. ```python from typing import Annotated, Literal +from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator -from pydantic import BaseModel, ConfigDict, Field, field_validator - -class ProfileContent(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - schema: Literal["powercontext.profile.v1"] = "powercontext.profile.v1" - media_type: Literal["text/markdown"] = "text/markdown" - content: Annotated[str, Field(min_length=1)] - - @field_validator("content") - @classmethod - def validate_markdown(cls, value: str) -> str: - normalized = normalize_profile_markdown(value) - if len(normalized.encode("utf-8")) > 262_144: - raise ValueError("profile Markdown exceeds 256 KiB") - return normalized -``` +Identifier = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] -Logical content example: +class SourceWindow(BaseModel): + after: int = Field(ge=0) + through: int = Field(ge=0) -```json -{ - "schema": "powercontext.profile.v1", - "media_type": "text/markdown", - "content": "# User Profile\n\nThe user prefers concise answers in Chinese. For hotels in China, the user usually selects a king room with a typical budget of CNY 500-700.\n" -} -``` - -The `content` is generated entirely by an LLM or edited by an authorized user, and its format is Markdown: - -```markdown -# User Profile - -The user prefers concise answers in Chinese. For hotels in China, the user usually selects a king room with a typical -budget of CNY 500-700. -``` + @model_validator(mode="after") + def ordered(self): + if self.through < self.after: + raise ValueError("through must be >= after") + return self -Normalization is fixed to UTF-8, Unicode NFC, LF newlines, no BOM, and exactly one trailing newline. The server validates -that the document is non-empty, within the size limit, and has valid Markdown document boundaries. It does not interpret -heading levels as database categories. +class ProfileGeneration(BaseModel): + mode: Literal["automatic", "manual_create", "manual_replace", "review_approved", "rollback"] + created_at: str # Server-generated UTC RFC 3339 timestamp. + generator_id: str | None = None + generator_version: str | None = None + source_window: SourceWindow | None = None + restored_from_revision: int | None = Field(default=None, ge=1) -### Physical BLOB encoding +class ProfileWriteContent(BaseModel): + model_config = ConfigDict(extra="forbid") + content: str = Field(min_length=1) + restored_from_revision: int | None = Field(default=None, ge=1) -The existing `pc_artifacts.content` is already a `BLOB`, or `MEDIUMBLOB` in the OceanBase/MySQL variant, so no schema -change is required. The first release keeps the current Artifact codec: it serializes `ProfileContent` as Pydantic JSON -UTF-8 bytes into the BLOB. In other words, the BLOB contains model bytes whose string field is Markdown. It is not a new -Claim column, nor raw text written around the Artifact Repository. +class ProfileContent(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_: Literal["powercontext.profile.v1"] = Field(default="powercontext.profile.v1", alias="schema") + media_type: Literal["text/markdown"] = "text/markdown" + content: str + generation: ProfileGeneration -```text -pc_artifacts.content - = UTF8_BYTES('{"schema":"powercontext.profile.v1",' - '"media_type":"text/markdown",' - '"content":"# User Profile\\n...\\n"}') +class ProfileCandidateProposal(BaseModel): + schema_: Literal["powercontext.profile-candidate.v1"] = Field(default="powercontext.profile-candidate.v1", alias="schema") + content: str + source_window: SourceWindow + generator_id: str + generator_version: str + created_at: str ``` -Profile-specific APIs decode this value and return a string. The general Artifact API continues to return a `content` -object, so the existing `ArtifactRevision.content: object` response shape does not change. - -### Revision lineage and generation metadata - -Every automatic generation, manual creation, manual replacement, approval, and rollback creates a new immutable -Revision: +These models show the core types. Commit validation also requires nonblank Markdown, NFC/LF normalization, BOM +removal, exactly one trailing newline, and a 256 KiB UTF-8 Markdown limit. Timestamps must parse and normalize to UTC. +Automatic/review-approved generation requires a valid window and generator information; manual operations cannot +forge windows. Only rollback has restored_from_revision, referencing an existing Revision of the same +Scope/Family/Artifact. Candidate window and generator fields are server-owned. Revise uses a separate Markdown input +schema rather than accepting the writable persistence model. -- an automatically generated or approved Revision references the Root-local business Sources actually consumed in - this run through `pc_artifact_lineage_sources`; it does not reference `lineage_only` Sources filtered out of the - window; -- manual Profile Create, Replace, and Rollback resolve the fixed scoped identity and reuse the internal Artifact - `RecordService` and CAS transaction primitives described by [RFC 1437](1437_source_artifact_rest_api.md). They - preserve the `lineage_only` system Source generated by the write command and place it at ordinal 0 in the new - Revision's direct Source lineage; -- `pc_artifact_lineage_artifacts` references the exact previous Profile Revision on update; -- `pc_profile_revision_metadata` stores the generation mode, Source Window, generator version, and rollback source; -- runtime cursors and internal task state are not mixed into the Markdown. +Only Markdown is compared to detect no-change generation. Different timestamps or generator fields alone do not +create an automatic Revision. Base manual Replace retains its existing behavior of creating a Revision on every +successful call. Human confirmation is a whole-Revision generation signal; it does not establish paragraph-level +confirmation. Later explicit Source evidence may still update the corresponding content. -The system Source produced by a manual write remains auditable provenance, but the Profile Processor must filter it out. -A Profile edit must not become evidence for the next Profile generation. +## Daily scheduling and source consumption -### Update rules +Reuse the APScheduler sidecar table and add a Cron job. Add no durable pending, lease, or business job tables. +Page enabled Scopes in `pc_profile_policies` and compare `pc_source_journal_heads.position` with the +`profile-source-window` Cursor in `pc_source_cursors`. A missing Cursor means sequence=0. -The model input for an automatic update is: - -```text -current Profile Markdown -+ Root Source window (cursor, source_through] --> full next Profile Markdown | NOOP -``` - -Merge rules: - -1. An automatic LLM call is allowed only when the Root Source journal contains unconsumed business Sources. Changes to - the model, prompt, or code version, and the arrival of only `lineage_only` Sources, do not trigger a rebuild. -2. Before invoking the LLM, the Worker filters every `lineage_only` Source and deduplicates by exact Source address and - content digest. If a window contains only filtered items, it does not invoke the LLM or create a Revision, but still - advances the Cursor with CAS so the same items are not scanned forever. -3. The LLM reads the current complete Markdown and the new Sources and preserves only stable, cross-session user - information with durable value. -4. Exact duplicates are merged. A new, explicit user statement supersedes a conflicting older statement. When evidence - is insufficient, the old statement remains and no sensitive inference is made. -5. Trust applies only to a complete Profile Revision. When the current Head's `generation_mode` is `manual_create`, - `manual_replace`, `review_approved`, or `rollback`, the whole current document takes precedence over an unconfirmed - generated replacement unless a new Source explicitly records a user correction. The first release does not infer - that individual paragraphs within a Markdown document have different trust levels. -6. The LLM must return complete Markdown or `NOOP`; it cannot operate on database fields directly. -7. The server normalizes the result and calculates a digest. If it matches the current Head, no empty Revision is - created; only the Cursor advances. -8. A validation failure, model failure, or CAS conflict does not advance the Cursor. On a CAS conflict, the Worker - rereads the Head and performs the merge again. - -Removing the Claim structure means that the first release provides Revision-level lineage only, not Claim-level -queries, risk classification, or citations. Those capabilities should later be implemented as rebuildable indexes -rather than by writing Claim classifications back into the fact tables. - -## Background automatic generation - -### Schedule configuration - -By default, one automatic Profile processing wave begins every day at `02:00` in the deployment time zone: - -```python -from typing import Annotated -from zoneinfo import ZoneInfo - -from pydantic import BaseModel, Field - -class ProfileGenerationSchedule(BaseModel): - enabled: bool = True - cron: str = "0 2 * * *" - timezone: str = "Asia/Shanghai" - source_window_limit: Annotated[int, Field(ge=1, le=1000)] = 200 - max_concurrency: Annotated[int, Field(ge=1, le=128)] = 8 - worker_timeout_seconds: Annotated[int, Field(ge=30, le=3600)] = 900 - retry_max_delay_seconds: Annotated[int, Field(ge=30, le=86_400)] = 1800 - - def tzinfo(self) -> ZoneInfo: - return ZoneInfo(self.timezone) +```yaml +profile: + schedule: + cron: "0 2 * * *" + timezone: "Asia/Shanghai" + misfire_grace_seconds: 86400 + max_concurrency: 4 + max_sources_per_window: 32 ``` -`02:00` is the default off-peak time. A deployment may change the Cron expression and IANA time zone. A large -deployment may configure scheduling jitter, but the default has no jitter. The implementation must use a time-zone-aware -CronTrigger rather than an IntervalTrigger that runs every 86,400 seconds, because service restarts and daylight-saving -time would otherwise cause drift. - -### Scheduled call flow +Cron and IANA timezone are configurable; invalid values fail startup. Configure coalescing and per-process +max_instances=1. Run a recovery scan at startup so unconsumed Sources are found even after long downtime or an +expired misfire grace period. Each run uses a fixed high watermark and bounded windows. Process windows sequentially +within a Scope and Scopes concurrently. Limit each Scope to 100 windows per scan; leave remaining work for the next +scan or Flush. Windows contain at most 32 journal entries and must respect the existing Candidate limit of 32 total +Source and Artifact evidence references. When the previous Profile is Artifact evidence, use at most 31 entries. +Never omit evidence actually used in generation from lineage merely to fit the limit. ```mermaid sequenceDiagram - participant Cron as Profile Cron Scheduler - participant Sup as Artifact Processing Supervisor - participant DB as Metadata + Artifact DB - participant Worker as Profile Worker - participant LLM as LLM - - Cron->>Sup: daily wave at 02:00 - Sup->>DB: acquire/renew global lease - Sup->>DB: page pending(binding=profile-source-window) - DB-->>Sup: dirty Profile scopes and source_through - Sup->>Worker: assign(scope, after, through, generation) - Worker->>DB: read Cursor + current Profile + fixed Source window - Worker->>LLM: current Markdown + new Sources - LLM-->>Worker: complete Markdown or NOOP - Worker->>Worker: normalize, validate, digest - alt automatic and changed - Worker->>DB: CAS Create/Replace Revision + metadata + Cursor - else review_required and changed - Worker->>DB: create full-Markdown Candidate; wait for decision - else NOOP - Worker->>DB: CAS advance Cursor only + participant Cron as 02:00 Scheduler / Manual Flush + participant Worker as Profile Processor + participant DB as Policy + Journal + Cursor + Artifact/Candidate + participant LLM as Model + Cron->>Worker: Scan enabled scopes + Worker->>DB: Read policy version, pending pointer, cursor and profile head + alt Candidate pending or no new journal entries + Worker-->>Cron: review_pending / noop + else New source window + Worker->>DB: Read bounded (after, through] window + Worker->>Worker: Filter lineage_only; normalize and deduplicate evidence + Worker->>LLM: Old profile + eligible evidence, if any + LLM-->>Worker: Complete Markdown + Worker->>DB: Begin transaction; lock Policy; recheck version, cursor, head + alt Automatic activation + Worker->>DB: Commit revision + lineage + cursor atomically + else Review required + Worker->>DB: Commit candidate + pending pointer; cursor unchanged + end + Worker-->>Cron: updated / review_pending end - Worker-->>Sup: success / review_pending / failure ``` -Detailed flow: - -1. In the business Source write transaction, the unified `SubjectSourceRoutingService` has already upserted the Root - journal high-water mark into `pc_artifact_processing_pending`, without invoking an LLM. When an ordinary Scope - explicitly enables a Scope-local Profile, its own journal high-water mark is registered as a separate target. A - shared Scope is disabled by default. -2. At `02:00` every day, the instance holding the Supervisor lease starts that day's wave. The persistent scheduler uses - `coalesce=true`, so it runs once after recovering from a missed execution time. -3. The Supervisor pages dirty targets with `binding_name="profile-source-window"` and schedules them fairly up to - `max_concurrency`. -4. A Worker freezes the current `source_through`, reads `after` from `pc_source_cursors`, reads Source Windows in batches - of at most 200 by default, and excludes `lineage_only` items before invoking the model. A Source that arrives during - inference has a position greater than `through` and remains for the next wave. -5. If `after >= through`, or the fixed Window is empty after filtering, the Worker skips the LLM; in the latter case it - still advances the Cursor. Once the Cursor reaches the Pending high-water mark, Pending is cleared. -6. The Worker reads the current Profile and fixed Source Window and invokes the LLM outside a transaction, avoiding - locks held by a long transaction. -7. The Worker validates the complete Markdown. In automatic mode, it commits the Revision, Lineage, Revision Metadata, - and Cursor in one short transaction protected by Head CAS, Cursor CAS, and Supervisor fencing. -8. When there is no semantic change, the Worker creates no Revision and only advances the Cursor with CAS. -9. In `review_required` mode, the Worker creates a full-Profile Candidate, persists its Source Window, and claims the - Policy's single `pending_candidate_id` in one transaction. Scheduled and Manual Generate paths do not create a - duplicate while a Candidate is pending. Approval creates a Revision and advances through the Candidate's - `source_through`. Rejection must explicitly select `reject_and_consume` or `reject_and_retry`: the former advances - the Cursor so the same proposal is not recreated the next day; the latter leaves the Cursor unchanged and retains - Pending so a later wave may regenerate the same window. -10. A failure for one user does not block other users. Failure does not advance the Cursor or remove Pending, and is - retried with exponential backoff capped at 30 minutes by default. - -### Why a durable dirty set instead of a Job history table - -Profile reuses the general `pc_artifact_processing_pending`, `pc_artifact_processing_leases`, and `pc_source_cursors` -defined by the Topic Memory RFC. Pending means that a `(binding_name, scope_id)` pair still has unconsumed Sources; it is -not an ever-growing task history. - -The first release adds no `pc_profile_generation_jobs`. Processing status is derived from Pending, Cursor, the current -journal head, and the latest Profile Revision Metadata. Runtime logs and metrics observe individual attempts. If Topic -Memory's general processing tables have not landed before Profile is implemented, they are added as general tables by -this RFC and must not be described as pre-existing tables. - -### Manual generation - -`POST /v1/profile/generate` does not wait synchronously for an LLM. It reads the current Source journal head, increments -Pending's `flush_generation`, wakes the Supervisor, and always returns HTTP `200`. The response body's `status` is -`accepted`, `idle`, or `review_pending`. With no new Source it returns `idle` and does not rebuild the current Profile; -with an existing automatic Candidate it returns `review_pending` without creating another Candidate. - -## Review, edit and rollback - -Because Claim categories and risk levels have been removed, the review unit is the entire Markdown Revision: - -```python -from typing import Literal - -from pydantic import BaseModel, ConfigDict - -class ProfilePolicy(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - generation_enabled: bool = True - activation_mode: Literal["automatic", "review_required"] = "automatic" - version: int -``` +A window containing only `lineage_only` entries invokes no LLM and creates no Artifact; advance to the complete +through boundary. Eligible evidence that produces unchanged Markdown also advances only the Cursor. Generation +depends only on this Scope's Sources; writing to S_U1 never advances S_U2's Cursor. The previous Profile is merge +context, not a reason to repeatedly consume all its historical Sources as new evidence. -- `automatic`: the default; valid new Markdown is created or replaced and immediately becomes the Head; -- `review_required`: generated content is written to the existing Artifact Candidate tables and becomes a new Revision - only after approval; -- the policy is set by server configuration or changed for a target Scope by an authorized user through the Policy API; - the LLM does not choose it; -- there is no configuration that activates one Claim risk level automatically while requiring Review for another, - because the first release has no Claim-level structure. +Do not hold a database transaction lock during an LLM call. At commit, lock the Policy and compare its snapshotted +version and pending pointer, Cursor generation, and Head. Discard the computation without advancing the Cursor if +any changed. SQLite serializes writes with a write transaction; OceanBase uses row locks and CAS. Every successful +Profile processing commit and Policy pointer change increments Policy version. Base Profile Create/Replace takes +the same Policy lock to serialize commits against workers and review. Concurrent initial Policy creation during a +manual operation also uses the primary key and transaction to resolve races. -When rejecting an automatic Candidate, the review request must explicitly submit a `disposition`: +Multiple processes may call the LLM redundantly, but only one result may commit. APScheduler per-process options are +not distributed locks. Model timeout, invalid output, or transaction failure retains the Cursor, records an error +without content, and retries at the next scheduled scan or manual Flush. Sources and Cursors provide recovery; +persistent job records are unnecessary. Model or Prompt changes alone do not trigger regeneration. -- `reject_and_consume`: record the rejection, advance the Cursor to the Candidate's `source_through`, update Pending, - and clear the Policy pointer; -- `reject_and_retry`: record the rejection, leave the Cursor unchanged, retain or re-upsert Pending, and clear the - Policy pointer. +## Review, manual editing and rollback -A manual edit submits complete Markdown, a reason, and the current Head's `If-Match`, and creates a new Revision. A -rollback does not move the Head pointer backward. It reads the Markdown from the selected old Revision and copies it -into the next Revision after the current Head. Revision Metadata records `restored_from_revision`, and the HTTP request -also uses `If-Match` to protect the current Head. +Commit an automatic Candidate and `pending_candidate_id` atomically. Each Scope has at most one pending automatic +Profile Candidate. Sources may continue to arrive while one is pending, but scheduled and manual Flush calls do not +generate another Candidate. Changing Policy neither approves nor discards an existing Candidate. -Candidate approval, manual editing, and rollback all use Artifact Head CAS. If the Head changes during review, approval -returns a conflict and requires regeneration or Candidate revision; content based on an old Head must not silently -overwrite a new Head. - -Human confirmation applies to the complete Candidate proposal and the resulting complete Head. It is represented by the -Revision's `generation_mode="review_approved"`, not by paragraph annotations. The conflict resolver must not describe a -paragraph as human-confirmed merely because some other part of the same Markdown Revision was edited or reviewed. - -## Subject context aggregation - -`subject_key` is not only a way to find a Profile. It also defines a stable query entry point reusable by different -Artifact Families: +| Operation | Atomic updates | Cursor | +| --- | --- | --- | +| Generate Candidate | Candidate versions/heads, Policy pointer and version | Unchanged | +| Revise Candidate | New Candidate version; edit Markdown, preserve window/target/evidence | Unchanged | +| Approve | Artifact/Head/lineage, Candidate approved/result, clear Policy pointer, Cursor | Advance to Candidate through | +| Reject | Candidate rejected/reason, clear Policy pointer, Cursor | Advance to Candidate through | + +Reuse existing Candidate get/list/revise/approve/reject. Requests retain `scope_id`, `candidate_id`, and +`expected_version`; Reject still requires reason and adds no disposition. The Profile branch validates the Policy +pointer, pending status, and Cursor.sequence=after. Approve additionally requires the current Head to match Candidate +target. For target=NULL, the fixed Profile Head must not exist. + +Manual Replace remains allowed while review is pending. Approve of the stale Candidate returns `409` and preserves +it. Reject need not match the current Head and can still consume the original window. Users may read the Candidate +and manually apply desired content before rejecting it. Revise does not silently retarget the Candidate to a newer +Head. Approve/Reject never partially advance the Cursor. Repeated terminal requests follow existing Candidate +conflict semantics; clients use Get to confirm the outcome. + +Reject consumes only its window and never deletes Sources. Rejected Markdown becomes neither committed content nor +the previous-profile input to future generation. Later evidence may assert the same fact; rejection is not permanent +fact suppression. If the journal grows from 42 to 50 during review, processing resumes after 42 following the decision. +After restart, restore the waiting state from the persisted Policy pointer and Candidate without generating again. + +Manual Create/Replace uses the base Artifact API Family writer and preserves its system `lineage_only` Source, +ordinal=0, ETag/If-Match, and lineage rules. Create uses artifact_id=profile and returns 409 if the Head exists. +Automatic commits use the same Family validation and repository but cite actual evidence rather than inventing a +manual system Source. + +Rollback needs no new API: GET a historical Revision, GET the current Head ETag, then PUT the complete Markdown with +optional `restored_from_revision` in ProfileWriteContent. The server verifies that the historical Revision exists +and its normalized Markdown matches, then creates a new rollback Revision. It neither moves Head back to an older +Revision nor rewinds the Cursor. Omitting the field is an ordinary manual Replace; Create forbids it. Clients compare +two Revisions themselves, with no new diff or history-list endpoint. + +## Persistence inventory and example rows + +BLOB examples below show decoded JSON. Foreign keys and lineage use complete identities. Timestamps and digests +are readable examples; omitted default columns are still written according to existing definitions. Existing tables +have no DDL changes; only Profile BLOB schemas and code branches are extended. ```mermaid -flowchart LR - K["subject_key"] --> Resolve["resolve root_scope_id"] - Resolve --> Select["root + true descendants"] - Select --> Auth["authorize every Scope and Artifact"] - Auth --> Profile["exact Profile Head"] - Auth --> Recall["family-specific recall"] - Recall --> Dedup["exact + semantic dedup"] - Profile --> Compose["conflict-aware composition"] - Dedup --> Compose - Compose --> Budget["rank + family quota + max_bytes"] +erDiagram + PC_SCOPES ||--o{ PC_SCOPE_BINDINGS : scope_id + PC_SCOPES ||--o| PC_PROFILE_POLICIES : scope_id + PC_SCOPES ||--o{ PC_SOURCES : "logical scope membership" + PC_SCOPES ||--o{ PC_SOURCE_CURSORS : "logical scope membership" + PC_ARTIFACTS ||--o| PC_ARTIFACT_HEADS : current_revision + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : revision + PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : local_evidence + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_ARTIFACTS : revision + PC_ARTIFACT_CANDIDATE_VERSIONS ||--o| PC_ARTIFACT_CANDIDATE_HEADS : current_version + PC_ARTIFACT_CANDIDATE_HEADS o|--o| PC_PROFILE_POLICIES : pending_candidate ``` -Scope selection follows these rules: - -1. The server obtains the unique `root_scope_id` from `pc_subject_roots`. -2. Candidate Scopes are the Root and its true descendants. Parent expresses organization only; every Scope and Artifact - still requires authorization. -3. A shared group-chat Scope is not part of any user Root subtree and is not implicitly selected because the user - participates in the chat. -4. Profile is read exactly at its fixed address and does not participate in ordinary vector recall. Memory, Topic - Memory, Skill, Experience, and other families use their own recall providers. -5. Each `(scope_id, family, artifact_id, revision)` is kept once; the same Head and its exact Revision are not injected - twice. Cross-Scope results must use `ArtifactAddress`, which includes `scope_id`; they cannot return an `ArtifactRef` - that is complete only within one Scope. -6. Within a family, content is first deduplicated by stable identity and content digest, then semantically deduplicated. - Procedural knowledge from different families is not merged merely because its text is similar. -7. When a Markdown Profile conflicts with another artifact, ranking can use only the current Head's whole-document - `generation_mode`, time, and direct evidence. Revision-level manual mode must not be interpreted as paragraph-level - trust. If the conflict remains unresolved, the result includes a conflict summary and both exact - `ArtifactAddress` values without modifying any source Artifact. -8. Final composition applies family quotas and the request's `max_bytes`. The server measures actual UTF-8 bytes, and - truncated content preserves a complete address that callers can expand. - -A Memory Entry or another family-owned subresource must likewise return a complete address containing `scope_id`. -Subject aggregation results cannot contain a bare `ArtifactRef`, Entry ref, or other subresource ref that can be -dereferenced only by assuming a current Scope. - -The existing Prepare Context path processes only the Scope range explicitly supplied by the caller and does not -automatically traverse a Subject Root. The Subject Context API in this RFC resolves the range server-side and then -reuses each family's existing recall capability. - -Profile is the only user-level artifact generated automatically in the first release. If another Artifact Family later -reuses this design, it should consume evidence from the Root-local Source journal and write results into the Root or a -true child Scope. Artifacts already present in a shared Scope do not automatically become cross-Scope merely because a -Source was copied. +Logical membership is not a new foreign key: `pc_sources` and `pc_source_cursors` retain existing constraints. +There is no new relationship table or FK between the two cross-Scope Sources. `pc_artifact_lineage_artifacts` still +stores same-Scope upstream Revisions. -# Reference-level explanation - -## Database metadata design - -### Relationship diagram +### Scopes and bindings -```mermaid -erDiagram - PC_SCOPES ||--o| PC_SUBJECT_ROOTS : "root_scope_id" - PC_SCOPES ||--o{ PC_SOURCES : owns - PC_SUBJECT_ROOTS ||--o{ PC_SUBJECT_SOURCE_PROJECTIONS : routes - PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "origin Source" - PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "Root Source" - PC_SCOPES ||--o{ PC_ARTIFACTS : owns - PC_ARTIFACTS ||--o| PC_PROFILE_REVISION_METADATA : "Profile subset" - PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : cites - PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : evidence - PC_SCOPES ||--o| PC_PROFILE_POLICIES : configures - PC_ARTIFACT_CANDIDATE_HEADS ||--o| PC_PROFILE_CANDIDATE_METADATA : tracks_window - PC_SCOPES ||--o{ PC_SOURCE_CURSORS : consumes - PC_SCOPES ||--o{ PC_ARTIFACT_PROCESSING_PENDING : marks_dirty -``` +`pc_scopes` stores ordinary Scopes. The example has four rows without Parents, although the group chat may retain +its existing organizational relationship: -At runtime, `pc_artifact_processing_leases` fences Worker commits with the Supervisor's -`holder_id + supervisor_generation`. It has no database foreign key to Pending and therefore is not shown as a solid ER -relationship. The `root_contributor` authorization binding is persisted in the existing -`pc_access_relationships` table. That table identifies resources through its access-control resource columns and hash, -not a foreign key to `pc_subject_roots`, so the binding is also not drawn as a solid ER edge. +| scope_id | title | summary | parent_scope_id | version | +| --- | --- | --- | --- | --- | +| S_GROUP | Discussion | Group conversation evidence | NULL | 1 | +| S_U1 | User workspace | Long-lived conversation evidence | NULL | 1 | +| S_U2 | User workspace | Long-lived conversation evidence | NULL | 1 | +| S_U3 | User workspace | Long-lived conversation evidence | NULL | 1 | -### New table: `pc_subject_roots` +`pc_scope_bindings` keeps `(integration, kind, external_id)` as its primary key with no new uniqueness on scope_id. -This family-neutral table maps a subject to its Root Scope: - -| Field | Type | Constraint | Meaning | +| integration | kind | external_id | scope_id | | --- | --- | --- | --- | -| `subject_key` | `VARCHAR(256)` binary collation | PK | Caller-provided business `user_id`, matched exactly | -| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, UNIQUE, FK -> `pc_scopes.scope_id` | User Root generated by PowerContext | -| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | Mapping creation time | +| subject | user | U1 | S_U1 | +| subject | user | U2 | S_U2 | +| subject | user | U3 | S_U3 | -An additional `UNIQUE(subject_key, root_scope_id)` supports the composite foreign key from the projection table. Once -created, a mapping cannot be rebound. Account merging and migration require a separate design. +`pc_scope_context_references`, `pc_scope_external_references`, and `pc_scope_settings` receive no rows in this example. +Internal automatic Scope creation does not pretend to use public Scope Create's Idempotency-Key, so +`pc_scope_creation_requests` has no row for this request. If the application precreates a Scope through existing +Scope Create, its records follow that existing flow. -### New table: `pc_subject_source_projections` +### Sources, journal heads and cursors -This table records the exact one-to-one projection between a business-Scope Source and a Root Source: +`pc_sources` retains primary key `(scope_id, source_type, source_id)`. P is the same complete valid ContentSource +payload. Both rows share name/src_01, so their internal envelopes can also match. Source ID is not globally unique. -| Field | Type | Constraint | -| --- | --- | --- | -| `origin_scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_sources.scope_id` | -| `origin_source_type` | `VARCHAR(128)` binary collation | PK part, FK part | -| `origin_source_id` | `VARCHAR(256)` binary collation | PK part, FK part | -| `subject_key` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | -| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | -| `projected_source_type` | `VARCHAR(128)` binary collation | NOT NULL, FK part -> `pc_sources` | -| `projected_source_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_sources` | -| `content_digest` | `VARCHAR(71)` binary collation | NOT NULL, `sha256:` | -| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | - -Constraints: +| scope_id | source_type | source_id | payload | journal_position | +| --- | --- | --- | --- | --- | +| S_GROUP | content | src_01 | P | 101 | +| S_U1 | content | src_01 | P | 42 | -```text -PRIMARY KEY (origin_scope_id, origin_source_type, origin_source_id) -UNIQUE (root_scope_id, projected_source_type, projected_source_id) -FOREIGN KEY (origin_scope_id, origin_source_type, origin_source_id) - REFERENCES pc_sources(scope_id, source_type, source_id) -FOREIGN KEY (root_scope_id, projected_source_type, projected_source_id) - REFERENCES pc_sources(scope_id, source_type, source_id) -FOREIGN KEY (subject_key, root_scope_id) - REFERENCES pc_subject_roots(subject_key, root_scope_id) -CHECK (origin_scope_id <> root_scope_id) -``` +P's business content is `{"speaker":"U1","text":"I prefer concise answers in Chinese"}`, encoded through the existing +adapter with no new internal subject fields. -In the first release, `projected_source_type/id` equal those of the origin Source. Separate fields preserve complete -addresses on both sides and allow a future internal Source adapter to define a different address. +`pc_source_journal_heads`: -### New table: `pc_profile_policies` +| scope_id | position | +| --- | --- | +| S_GROUP | 101 | +| S_U1 | 42 | -This table supports both Subject Root Profiles and explicitly enabled Scope-local Profiles: +`pc_source_cursors`, after Source ingestion and before generation: -| Field | Type | Constraint | Default | +| scope_id | binding_name | cursor BLOB | generation | | --- | --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK, FK -> `pc_scopes.scope_id` | - | -| `generation_enabled` | `BOOLEAN` | NOT NULL | `TRUE` for Subject Root | -| `activation_mode` | `VARCHAR(32)` binary collation | NOT NULL, CHECK `automatic/review_required` | `automatic` | -| `pending_candidate_id` | `VARCHAR(128)` binary collation | nullable, FK part -> `pc_artifact_candidate_heads` | `NULL` | -| `version` | `BIGINT` | NOT NULL, CHECK > 0 | `1` | -| `updated_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | current time | - -Creating a Subject Root also creates its default Policy. The absence of a Policy for an ordinary Scope means that its -Scope-local Profile is disabled; the caller must configure it explicitly before it participates in the daily scan. +| S_GROUP | profile-source-window | {"sequence":100} | 8 | +| S_U1 | profile-source-window | {"sequence":41} | 5 | -Together with the same row's `scope_id`, `pending_candidate_id` forms a foreign key to -`pc_artifact_candidate_heads(scope_id, candidate_id)`. A Worker may create an automatic Profile Candidate only when this -field is `NULL`, and sets it in the same transaction. Approve/Reject clears it after completing Cursor/Pending handling. -This single pointer guarantees at most one pending automatic Candidate for each Profile Scope, including concurrent -Manual Generate paths. +After successful processing, sequences become 101/42 and generations become 9/6 respectively. Memory and other +bindings' Cursors remain unchanged. -### New table: `pc_profile_revision_metadata` +### The only new table: pc_profile_policies -Markdown contains only Profile content; runtime metadata is associated separately with the Artifact Revision: - -| Field | Type | Constraint | +| Field | SQLAlchemy type | Constraint/meaning | | --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifacts` | -| `family` | `VARCHAR(128)` binary collation | PK part, FK part, CHECK `family='profile'` | -| `artifact_id` | `VARCHAR(128)` binary collation | PK part, FK part | -| `revision` | `INTEGER` | PK part, FK part | -| `generation_mode` | `VARCHAR(32)` binary collation | `automatic/manual_create/manual_replace/review_approved/rollback` | -| `generator_id` | `VARCHAR(128)` binary collation | NULL for manual operations | -| `generator_version` | `VARCHAR(128)` binary collation | NULL for manual operations | -| `source_after` | `BIGINT` | nullable, CHECK >= 0 | -| `source_through` | `BIGINT` | nullable, CHECK >= `source_after` | -| `restored_from_revision` | `INTEGER` | nullable, CHECK > 0; composite FK with the same `scope_id/family/artifact_id` | -| `operation_reason` | `TEXT` | nullable | -| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | - -Constraints: +| scope_id | identity_string(256) | PK, FK -> pc_scopes.scope_id, ON DELETE CASCADE | +| generation_enabled | Boolean | NOT NULL; participates in scheduled scans/Flush | +| activation_mode | identity_string(32) | NOT NULL; automatic or review_required | +| pending_candidate_id | identity_string(128) | Nullable; composite FK with scope_id -> pc_artifact_candidate_heads | +| version | BigInteger | NOT NULL, >0; CAS version for configuration and processing state | +| updated_at | DateTime(timezone=True) | NOT NULL, UTC | ```text -PRIMARY KEY (scope_id, family, artifact_id, revision) -FOREIGN KEY (scope_id, family, artifact_id, revision) - REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) -FOREIGN KEY (scope_id, family, artifact_id, restored_from_revision) - REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) -CHECK (family = 'profile') -CHECK (generation_mode IN - ('automatic', 'manual_create', 'manual_replace', 'review_approved', 'rollback')) -CHECK ((source_after IS NULL) = (source_through IS NULL)) -CHECK (source_after IS NULL OR (source_after >= 0 AND source_through >= source_after)) -CHECK ( - (generation_mode IN ('automatic', 'review_approved') AND source_after IS NOT NULL) - OR - (generation_mode IN ('manual_create', 'manual_replace', 'rollback') AND source_after IS NULL) -) -CHECK ( - (generation_mode = 'rollback' AND restored_from_revision IS NOT NULL) - OR - (generation_mode <> 'rollback' AND restored_from_revision IS NULL) -) +PRIMARY KEY (scope_id) +CHECK (activation_mode IN ('automatic', 'review_required')) +CHECK (version > 0) +FOREIGN KEY (scope_id, pending_candidate_id) + REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) ON DELETE RESTRICT ``` -The nullable composite foreign key is inactive for non-rollback rows. These mode checks prevent a manual Revision from -claiming a generated Source Window and prevent an automatic or approved generated Revision from omitting its exact -Window. - -### New table: `pc_profile_candidate_metadata` - -The existing Candidate tables do not store a generation window, so a rejection cannot reliably determine how far to -advance the Cursor. An automatic Profile Candidate therefore receives one narrow processing-metadata row: +| scope_id | generation_enabled | activation_mode | pending_candidate_id | version | updated_at | +| --- | --- | --- | --- | --- | --- | +| S_GROUP | true | automatic | NULL | 3 | 2026-09-07T18:00:00Z | +| S_U1 | true | review_required | cand_01 | 7 | 2026-09-07T18:00:00Z | -| Field | Type | Constraint | -| --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifact_candidate_heads` | -| `candidate_id` | `VARCHAR(128)` binary collation | PK part, FK part | -| `binding_name` | `VARCHAR(128)` binary collation | NOT NULL, CHECK `binding_name='profile-source-window'` | -| `source_after` | `BIGINT` | NOT NULL, CHECK >= 0 | -| `source_through` | `BIGINT` | NOT NULL, CHECK >= `source_after` | -| `claimed_flush_generation` | `BIGINT` | NOT NULL, CHECK >= 0 | -| `rejection_disposition` | `VARCHAR(32)` binary collation | nullable; `reject_and_consume/reject_and_retry` | -| `created_at` | `DateTime(timezone=True)`, normalized to UTC | NOT NULL | - -```text -PRIMARY KEY (scope_id, candidate_id) -FOREIGN KEY (scope_id, candidate_id) - REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) -CHECK (binding_name = 'profile-source-window') -CHECK (source_through >= source_after) -CHECK (rejection_disposition IS NULL OR rejection_disposition IN - ('reject_and_consume', 'reject_and_retry')) -``` +A missing Policy means automatic generation is disabled. Automatically created subject Scopes start with enabled=true, +automatic, version=1. A base manual Profile creation with no Policy creates an enabled=false, automatic Policy for +concurrency coordination without enabling background generation. Policy PUT preserves pending_candidate_id; +clients cannot set or clear it. -Candidate Create writes the Candidate, this metadata, and `pc_profile_policies.pending_candidate_id` together, but does -not advance the Cursor. Approve commits the Profile Revision, Revision Metadata, Candidate status, Cursor/Pending state, -and Policy pointer in one transaction. Reject creates no Artifact: `reject_and_consume` advances through -`source_through` and updates Pending in one transaction, while `reject_and_retry` preserves the Cursor and retains or -re-upserts Pending. Both record `rejection_disposition` and the rejection reason and clear the Policy pointer. If the -Head changed in the meantime, the operation conflicts and preserves the Candidate without advancing the Cursor. +### Artifact content, heads and lineage -### New generic tables shared with Topic Memory +`pc_artifacts` example: -If Topic Memory has not already created the following two tables, this RFC adds them. +| scope_id | family | artifact_id | revision | content BLOB | +| --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 3 | C3 | +| S_U1 | profile | profile | 4 | C4 | +| S_GROUP | profile | profile | 2 | Group profile snapshot | -`pc_artifact_processing_pending`: +C4 is the complete value after approving cand_01. Its Markdown has no Claim rows or categories: -| Field | Type | Constraint | -| --- | --- | --- | -| `binding_name` | `VARCHAR(128)` binary collation | PK part | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_scopes.scope_id` | -| `source_through` | `BIGINT` | NOT NULL, CHECK >= 1 | -| `flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK >= 0 | -| `handled_flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK between 0 and `flush_generation` | +```json +{ + "schema": "powercontext.profile.v1", + "media_type": "text/markdown", + "content": "# User profile\n\n- Prefers concise answers in Chinese.\n", + "generation": { + "mode": "review_approved", + "created_at": "2026-09-08T01:00:00Z", + "generator_id": "profile-source-window", + "generator_version": "1", + "source_window": {"after": 41, "through": 42}, + "restored_from_revision": null + } +} +``` -Profile uses `binding_name="profile-source-window"`. +`pc_artifact_heads` points to Revision 3 before review and 4 afterward. These are post-approval rows: -`pc_artifact_processing_leases`: +| scope_id | family | artifact_id | revision | searchable_text | lifecycle_state | replacement_artifact_id | governance_generation | +| --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | Prefers concise answers in Chinese | active | NULL | 0 | +| S_GROUP | profile | profile | 2 | U1 prefers concise Chinese; U2 needs detailed analysis | active | NULL | 0 | -| Field | Type | Constraint | -| --- | --- | --- | -| `supervisor_group` | `VARCHAR(128)` binary collation | PK; fixed to `global` in the first release | -| `holder_id` | `VARCHAR(128)` binary collation | NOT NULL | -| `supervisor_generation` | `BIGINT` | NOT NULL, CHECK > 0 | -| `lease_expires_at` | `DateTime(timezone=True)`, normalized to UTC | nullable for single-process SQLite | +`pc_artifact_lineage_sources`: -These two tables are general Artifact processing substrate, not part of the Profile content model. +| scope_id | family | artifact_id | revision | ordinal | source_type | source_id | +| --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | 0 | content | src_01 | +| S_GROUP | profile | profile | 2 | 0 | content | src_01 | -### Existing tables: no physical schema changes +`pc_artifact_lineage_artifacts`: -This RFC changes no columns, primary keys, or foreign keys in the following existing tables: +| scope_id | family | artifact_id | revision | ordinal | upstream_family | upstream_artifact_id | upstream_revision | +| --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | 0 | profile | profile | 3 | -| Existing table | Use in this RFC | DDL change | -| --- | --- | --- | -| `pc_scopes` | Stores business Scopes and user Roots; Root has `parent_scope_id=NULL` | None | -| `pc_scope_bindings` | Not used for Subject Root mappings in this design | None | -| `pc_scope_context_references` | Not written automatically by Source Create | None | -| `pc_access_relationships` | Stores the explicit `root_contributor` / `scope.contributor` binding created during authorized Root bootstrap | None | -| `pc_sources` | Stores an identical Source once in the origin Scope and once in the Root | None | -| `pc_source_journal_heads` | Maintains an independent journal high-water mark for each Scope | None | -| `pc_source_cursors` | Stores the consumption position for `profile-source-window` | None | -| `pc_artifacts` | Stores immutable Profile Revisions; `content` is already BLOB/MEDIUMBLOB | None | -| `pc_artifact_heads` | Stores the current Head for `profile:user` or `profile:local` | None | -| `pc_artifact_lineage_sources` | Profile cites only same-Scope Root Sources | None | -| `pc_artifact_lineage_artifacts` | A new Profile Revision cites the previous Revision | None | -| `pc_artifact_candidate_versions` | Stores the complete ProfileContent proposal in `review_required` mode | None | -| `pc_artifact_candidate_heads` | Stores the current review state of a Profile Candidate | None | -| `pc_artifact_publications` | Artifact Publication is not used for Source copies in this RFC | None | -| `powercontext_scheduler_jobs` | The APScheduler sidecar gains one Profile Cron job row | No schema change | - -Although database DDL does not change, the Artifact and Candidate family enums in code and OpenAPI must add `profile`, -as described in the API changes. - -### Example rows for one U1 message +Automatic updates reference the previous Profile used as input. Base manual Replace retains base API lineage rules +and does not reuse another Revision's lineage_only Source as new evidence. Subject Source dual writes add no rows +to `pc_artifact_publications`. -```text -pc_subject_roots - (U1, R_U1) +### Candidates and scheduler -pc_sources - (S_GROUP, content, source_01, payload=P, journal_position=101) - (R_U1, content, source_01, payload=P, journal_position=42) +`pc_artifact_candidate_versions`, before review: -pc_subject_source_projections - (S_GROUP, content, source_01, U1, R_U1, content, source_01, sha256:...) +| scope_id | candidate_id | version | family | proposal BLOB | source_refs BLOB | artifact_refs BLOB | target_family | target_artifact_id | target_revision | reason | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | cand_01 | 1 | profile | Q1 | [{"source_type":"content","source_id":"src_01"}] | [{"family":"profile","artifact_id":"profile","revision":3}] | profile | profile | 3 | New evidence | -pc_artifact_processing_pending - (profile-source-window, R_U1, source_through=42, ...) +```json +{ + "schema": "powercontext.profile-candidate.v1", + "content": "# User profile\n\n- Prefers concise answers in Chinese.\n", + "source_window": {"after": 41, "through": 42}, + "generator_id": "profile-source-window", + "generator_version": "1", + "created_at": "2026-09-07T18:00:00Z" +} ``` -The Roots, journals, Cursors, and Pending rows for U2 and U3 do not change. +The JSON is Q1. Revise inserts version=2, preserving all server processing metadata and target while changing only +content. The three `pc_artifact_candidate_heads` states below are alternatives; only one current Head exists: -## API design +| scope_id | candidate_id | family | version | status | result_family | result_artifact_id | result_revision | decision_reason | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | cand_01 | profile | 1 | pending | NULL | NULL | NULL | NULL | +| S_U1 | cand_01 | profile | 1 | approved | profile | profile | 4 | NULL | +| S_U1 | cand_01 | profile | 1 | rejected | NULL | NULL | NULL | Evidence is too temporary | -### Python request and response types +Both approve and reject clear the Policy pointer and advance the Cursor from 41 to 42; only approve produces C4. +The Candidate version preserves the historical window, making `pc_profile_candidate_metadata` unnecessary. -```python -from __future__ import annotations +`powercontext_scheduler_jobs` reuses APScheduler's id/next_run_time/job_state: -from typing import Annotated, Any, Generic, Literal, Mapping, TypeVar +| id | next_run_time | job_state | +| --- | --- | --- | +| powercontext.profile.source-window.v1 | 1788804000.0 | APScheduler serialized CronTrigger: 02:00 Asia/Shanghai, dispatch_profile_windows | -from pydantic import BaseModel, ConfigDict, Field, model_validator +The timestamp corresponds to `2026-09-08T02:00:00+08:00`. APScheduler serializes job_state; implementations do not +handcraft its BLOB. Authorization relationships use existing Access Control tables and RelationshipWriter. The +following representative fields cover automatic creation and Profile commits; existing services fill remaining +audit, digest, and version fields. Assume the calling Principal is service/app-agent, with no automatic relationship +to business subject U1: -SubjectKey = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] -ETag = Annotated[str, Field(min_length=1)] +| Existing table | Example data (selected columns) | +| --- | --- | +| pc_access_relationships | binding_id=bind_01, subject_type=service, subject_id=app-agent, resource_type=scope, scope_id=S_U1, role=scope.contributor, state=active, version=1 | +| pc_access_relationship_heads | name=authorization, revision=12; incremented by the existing service on relationship changes | +| pc_access_idempotency | actor_id=, operation=binding.create, result_binding_id=bind_01; internal authorization deduplication, not Source HTTP idempotency | +| pc_access_audit | principal_type=service, principal_id=app-agent, scope_id=S_U1, allowed=true; operation/action supplied by existing authorization and audit services | +| pc_access_owners | owner_kind=artifact, scope_id=S_U1, family=profile, artifact_id=profile, owner_type=service, owner_id=app-agent; Candidate owner_kind=candidate, candidate_id=cand_01 follows existing rules | +No authorization table is added. Generation and review retain existing owner establishment/inheritance rules. +Background work uses a configured trusted service Principal, never subject_key as owner_id. The owner example +assumes app-agent performs the commit; it is not derived from U1. -class PrincipalRef(BaseModel): - type: Literal["user", "service"] - id: Annotated[str, Field(min_length=1, max_length=256)] - description: str | None = None +## API surface and Python examples +Only four HTTP operations are added. Their paths and types are implementation targets of this RFC, not claims of +current availability. -class SubjectRoutingFields(BaseModel): - subject_key: SubjectKey | None = None - root_contributor: PrincipalRef | None = None +| operationId | Method and path | Success | Purpose | +| --- | --- | --- | --- | +| create_subject_source | POST /v1/scopes/{scope_id}/subject-sources | 201 | Resolve subject binding and atomically write both Sources | +| get_profile_policy | GET /v1/scopes/{scope_id}/profile-policy | 200 | Read policy and pending pointer | +| put_profile_policy | PUT /v1/scopes/{scope_id}/profile-policy | 200 | Enable/disable generation and configure review | +| flush_profile | POST /v1/profile/flush | 200 | Process one bounded window through the background Processor | +Policy GET returns 404 if absent. PUT uses expected_version: 0 means create only; a positive value must match the +current version. GET requires scope.read and PUT scope.admin. Configuration changes and processing commits share +version, so clients reread after a conflict. Flush returns disabled for a missing Policy or generation_enabled=false without enabling it. +It waits for one window within a deployment-configured timeout. Timeout does not prove the transaction failed; +clients inspect existing Artifact/Candidate and Policy APIs. Retries still use Cursor/CAS checks. -class CreateSourceRequest(SubjectRoutingFields): - # Existing fields remain unchanged. +```python +class CreateSubjectSourceRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + subject_key: Identifier + subject_type: Literal["user"] = "user" + subject_scope_id: Identifier | None = None source_type: Literal["content"] = "content" - content: Any - - -class CaptureContentSourceRequest(SubjectRoutingFields): - # Existing fields remain unchanged. - scope_id: str - source_id: str - content: str - metadata: dict[str, Any] | None = None - - -class SubmitSourceObservationRequest(SubjectRoutingFields): - # The existing SourceObservation schema remains unchanged. - scope_id: str - observation: Any - - -class SourceAddress(BaseModel): - scope_id: str - source_type: str - source_id: str - - -class SubjectProjectionReceipt(BaseModel): - subject_key: SubjectKey - root_scope_id: str - origin_source: SourceAddress - root_source: SourceAddress - status: Literal["committed", "already_in_root"] - - -# DELTA ONLY: this is not a replacement definition for SourceRecord. -# SourceRecord retains every existing field, including receipt_identity. -class SourceRecordDelta(BaseModel): - subject_projection: SubjectProjectionReceipt | None = None - - -class ArtifactRef(BaseModel): - family: str - artifact_id: str - revision: int - - -class ArtifactAddress(BaseModel): - scope_id: str - artifact: ArtifactRef - - -class MemoryEntryAddress(BaseModel): - memory: ArtifactAddress - entry_id: str - entry_version_id: str - - -class ProfileTarget(BaseModel): - subject_key: SubjectKey | None = None - scope_id: str | None = None - - @model_validator(mode="after") - def exactly_one_target(self): - if (self.subject_key is None) == (self.scope_id is None): - raise ValueError("provide exactly one of subject_key or scope_id") - return self - - -class ResolvedProfileTarget(BaseModel): - scope_id: str - artifact_id: Literal["profile:user", "profile:local"] - # Both are populated for a subject-keyed Profile and null for Scope-local. - subject_key: SubjectKey | None = None - root_scope_id: str | None = None - - -class ResolveSubjectRequest(BaseModel): - subject_key: SubjectKey - create_if_absent: bool = True - origin_scope_id: str | None = None - root_contributor: PrincipalRef | None = None - - @model_validator(mode="after") - def require_origin_for_create(self): - if self.create_if_absent and self.origin_scope_id is None: - raise ValueError("origin_scope_id is required when create_if_absent=true") - return self - - -class ResolveSubjectResponse(BaseModel): - subject_key: SubjectKey - root_scope_id: str - created: bool - - -class ProfileGenerationMetadata(BaseModel): - mode: Literal[ - "automatic", - "manual_create", - "manual_replace", - "review_approved", - "rollback", - ] - source_after: int | None = None - source_through: int | None = None - restored_from_revision: int | None = None - created_at: str - - -class ProfileRecord(BaseModel): - target: ResolvedProfileTarget - artifact: ArtifactAddress - media_type: Literal["text/markdown"] = "text/markdown" - content: str - content_digest: str - generation: ProfileGenerationMetadata - - -class ProfileResponse(BaseModel): - """Python SDK wrapper; the wire body is ProfileRecord and ETag is a header.""" + content: JsonValue - record: ProfileRecord - etag: ETag +class CreateSubjectSourceResponse(BaseModel): + subject_type: Literal["user"] + subject_key: Identifier + subject_scope_id: Identifier + sources: list[SourceRecord] # Existing model; exactly two, business then subject. - -class CreateProfileRequest(BaseModel): - target: ProfileTarget - content: str - reason: str - - -class GetProfileRequest(BaseModel): - target: ProfileTarget - - -class ListProfileChangesRequest(BaseModel): - target: ProfileTarget - limit: Annotated[int, Field(ge=1, le=100)] = 50 - cursor: str | None = None - - -class ProfileChange(BaseModel): - artifact: ArtifactAddress - generation: ProfileGenerationMetadata - content_digest: str - - -class ProfileChangesPage(BaseModel): - target: ResolvedProfileTarget - items: tuple[ProfileChange, ...] - next_cursor: str | None = None - - -class DiffProfileRequest(BaseModel): - target: ProfileTarget - from_revision: Annotated[int, Field(ge=1)] - to_revision: Annotated[int, Field(ge=1)] - - -class ProfileDiffHunk(BaseModel): - old_start: int - old_lines: int - new_start: int - new_lines: int - lines: tuple[str, ...] - - -class ProfileDiff(BaseModel): - from_artifact: ArtifactAddress - to_artifact: ArtifactAddress - hunks: tuple[ProfileDiffHunk, ...] - - -class ReplaceProfileRequest(BaseModel): - # If-Match is an HTTP header, not a body field. - target: ProfileTarget - content: str - reason: str - - -class RollbackProfileRequest(BaseModel): - # If-Match is an HTTP header, not a body field. - target: ProfileTarget - restore_revision: Annotated[int, Field(ge=1)] - reason: str - - -class GenerateProfileRequest(BaseModel): - target: ProfileTarget - - -class ProfileGenerationResponse(BaseModel): - target: ResolvedProfileTarget - status: Literal["accepted", "idle", "review_pending"] - binding_name: Literal["profile-source-window"] - source_through: int | None = None - flush_generation: int | None = None - - -class GetProfileProcessingRequest(BaseModel): - target: ProfileTarget - - -class ProfileProcessingStatus(BaseModel): - target: ResolvedProfileTarget - journal_head: int - cursor_after: int - pending_through: int | None = None - pending_flush_generation: int | None = None - pending_candidate_id: str | None = None - last_result: Literal["success", "noop", "review_pending", "failure"] | None = None - - -class GetProfilePolicyRequest(BaseModel): - target: ProfileTarget - - -class ProfilePolicyRecord(BaseModel): - target: ResolvedProfileTarget +class PutProfilePolicyRequest(BaseModel): + model_config = ConfigDict(extra="forbid") generation_enabled: bool - activation_mode: Literal["automatic", "review_required"] - version: int - + activation_mode: Literal["automatic", "review_required"] = "automatic" + expected_version: int = Field(ge=0) -class UpdateProfilePolicyRequest(BaseModel): - target: ProfileTarget +class ProfilePolicyResponse(BaseModel): + scope_id: Identifier generation_enabled: bool activation_mode: Literal["automatic", "review_required"] - expected_version: Annotated[int, Field(ge=1)] - - -ContextAddress = ArtifactAddress | MemoryEntryAddress - - -class PrepareSubjectContextRequest(BaseModel): - subject_key: SubjectKey - query: Annotated[str, Field(min_length=1)] - families: tuple[Literal["profile", "memory", "topic-memory", "skill", "experience"], ...] - max_bytes: Annotated[int, Field(ge=1, le=4_194_304)] - - -class SubjectContextItem(BaseModel): - address: ContextAddress - content: str - selected_bytes: int - - -class SubjectContextConflict(BaseModel): - summary: str - left: ContextAddress - right: ContextAddress - - -class PreparedSubjectContext(BaseModel): - subject_key: SubjectKey - root_scope_id: str - scope_ids: tuple[str, ...] - items: tuple[SubjectContextItem, ...] - conflicts: tuple[SubjectContextConflict, ...] - used_bytes: int - max_bytes: int - truncated: bool - - -T = TypeVar("T") - - -class HttpResult(BaseModel, Generic[T]): - body: T - headers: Mapping[str, str] - - -def with_profile_metadata(result: HttpResult[ProfileRecord]) -> ProfileResponse: - """Shared SDK helper used by Profile Create, Get, Replace, and Rollback.""" - - etag = result.headers.get("ETag") - if etag is None: - raise RuntimeError("Profile response omitted required ETag") - return ProfileResponse(record=result.body, etag=etag) -``` - -`ProfileTarget(subject_key=...)` resolves to `root_scope_id + profile:user`. `ProfileTarget(scope_id=...)` first checks -whether the Scope is registered in `pc_subject_roots`: a user Root also normalizes to `profile:user`, while only an -ordinary Scope resolves to `profile:local`. Different selectors therefore cannot create two Profile Heads in the same -user Root. `ResolvedProfileTarget.subject_key` and `root_scope_id` are nullable precisely for the Scope-local case; its -scoped `ArtifactAddress` remains complete. - -Every Profile Create, Get, Replace, and Rollback HTTP success returns `ProfileRecord` in the response body and the -current opaque value in the HTTP `ETag` header. The generated transport client gains a metadata-aware response helper -that reads that header and returns `ProfileResponse(record=..., etag=...)`; the high-level synchronous and asynchronous -Python Profile clients use this helper rather than discarding response metadata. Replace and Rollback accept -`if_match: str` in Python and send it as `If-Match`, not as a JSON field. - -The `SourceRecordDelta` block above shows only the field added by this RFC. The final `SourceRecord` retains every -existing field, including `receipt_identity`, and adds optional `subject_projection`; the delta must not replace the -existing schema. - -### Existing API changes - -| Existing API/Schema | Change | Compatibility | -| --- | --- | --- | -| All business Source write application services | Add optional `subject_key` and `root_contributor` to `CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest`; when a key is present, uniformly use `SubjectSourceRoutingService` | Behavior is unchanged when omitted; HTTP, Runtime, MCP, and Connectors share the path | -| `POST /v1/scopes/{scope_id}/sources` | The HTTP adapter passes the extended `CreateSourceRequest` to the unified service above | Behavior is unchanged without a key; additive change | -| `POST /v1/sources/content` | The explicit-ID capture adapter passes the extended `CaptureContentSourceRequest` to the same routing service | Behavior is unchanged without a key; additive change | -| `POST /v1/source-observations` | The observation adapter passes the extended `SubmitSourceObservationRequest` to the same service and routes the materialized business Source with its actual `source_type` | Behavior is unchanged without a key; additive change | -| `SourceRecord` | Add optional `subject_projection` containing the Root and Root Source addresses while retaining existing `receipt_identity` | Old clients may ignore the new field | -| Source Create on a Root Scope | Require the `subject_key` matching the Root mapping; internal projections are exempt | Ordinary Scope behavior is unchanged; adds Root-boundary validation | -| `PUT /v1/scopes/{scope_id}` | When the target is a registered user Root, forbid changing `parent_scope_id` to a non-null value | Request shape is unchanged; adds a Root-invariant conflict | -| `BaseArtifactFamily` | Add `profile` for generic Artifact read addresses and responses | Additive change | -| `CreateArtifactRequest` / `ReplaceArtifactRequest` | Do not add a Profile union branch; generic Artifact Create/Replace rejects `family=profile` in v1 | Existing write unions and family-owned ID derivation remain unchanged | -| Generic Artifact Get Head, Get Revision, and List | Accept `family=profile`; content remains a `ProfileContent` object | Paths and response shape are unchanged | -| `CandidateFamily` | Add `profile` to the enum | Additive change | -| `ArtifactCandidate.proposal` / `ReviseArtifactCandidateRequest.proposal` | Add `ProfileContent` to the wire union; add `ProfileContent` to Runtime `ReviewedProposal` | Additive discriminator branch | -| `/v1/artifact-candidates/list|get|approve|reject|revise` | Support a complete-Markdown Profile Candidate; generic Reject gains optional `disposition`, which is mandatory after the server loads a Profile Candidate; Approve/Reject atomically coordinates Cursor, Pending, window metadata, and the Policy pointer | Paths are unchanged; the Profile branch adds atomic side effects | -| `GET /v1/capabilities` | Include `profile` in `artifact_families` and add the `profile_generation` capability | Additive change | - -Except for the Root Parent protection and optional Source projection information in this table, the semantics of Scope, -exact Source identity, Artifact identity, ETag, Revision, and Candidate status do not change. The first release still -adds no Source Update; callers express new facts or corrections by creating another Source. - -`CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest` are three distinct wire -schemas and all gain the same optional `subject_key` and `root_contributor`. Their HTTP adapters and corresponding Runtime, Python Client, -Connector, and MCP call paths dispatch through `SubjectSourceRoutingService`. Internal `lineage_only` provenance -Sources, Artifact-domain Sources, processor-created Sources, and the Root copy created inside the routing service do not -accept `subject_key` and must not recursively re-enter routing. - -Source Create and exact Source Get currently share `SourceRecord`. Therefore, adding an optional field to -`SourceRecord` means that both operations receive the additive field. Reading an Origin Source may return its projection -relationship; reading a Root Source may return its Origin. If an implementation wants only Create to return the receipt, -it must add `CreateSourceResponse` and change the `201` response type from `SourceRecord`; it cannot change only the -server response without updating OpenAPI. The code block above is an explicit `SourceRecord` delta and retains the -existing optional `receipt_identity` field. - -Although the Candidate database tables are family-neutral, current wire `ArtifactCandidate.proposal`, -`ReviseArtifactCandidateRequest.proposal`, Runtime `ReviewedProposal`, and Review Service branches handle only -Experience and Skill. All four must add `ProfileContent`. The Review Service loads the Candidate before validating an -optional Reject `disposition`, requires it for Profile, forbids it for other families, and dispatches approval through -the Profile service to the resolved `profile:user` or `profile:local` identity with the same Head CAS. Extending only -`CandidateFamily` is insufficient. - -Existing non-HTTP configuration and Python assembly also receive additive changes: - -| Location | Change | + pending_candidate_id: str | None + version: int = Field(ge=1) + updated_at: str + +class FlushProfileRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + scope_id: Identifier + +class FlushProfileResponse(BaseModel): + status: Literal["updated", "noop", "review_pending", "disabled", "conflict"] + previous_cursor: int + current_cursor: int + high_watermark: int + processed_source_count: int + artifact: ArtifactRef | None = None # Existing exact ref, scoped by request. + candidate_id: str | None = None +``` + +All new request models reject unknown fields and validate IDs/enums. SourceRecord and ArtifactRef are reused with +their existing optional fields. Flush processed_source_count is the number of eligible Sources in this invocation's +window; review_pending/disabled without a new model call returns 0. A concurrent conflict returns the reread Cursor +and no artifact/candidate_id from the discarded result. Other numeric response fields are nonnegative. + +| Existing endpoint/component | Change | | --- | --- | -| Runtime configuration | Add Profile Cron, IANA time zone, Window limit, concurrency, and timeout settings; existing Memory/Experience interval settings remain unchanged | -| Scheduler assembly | Add `configure_profile_generation_job` and a CronTrigger with its own time zone; reuse `powercontext_scheduler_jobs` instead of substituting a daily 86,400-second Interval | -| Artifact registry / Profile service | Register the `Profile` content codec and a Profile-only adapter that resolves the fixed scoped identity before calling internal `RecordService` and CAS primitives; do not register Profile in generic Create/Replace request unions | -| System provenance Source target | Allow `family="profile"`; manual Create/Replace/Rollback preserves `lineage_only` Sources, while an automatic Profile Window filters them | -| Review Service | Extend `ReviewedProposal` and the wire proposal unions with `ProfileContent`; add Profile approval/rejection branches and coordinate them atomically with Cursor/Pending | -| Subject/Profile HTTP and Python adapters | Add new resolve, Profile lifecycle, processing, policy, and Subject Context adapters; add a metadata-aware Python response helper that preserves HTTP `ETag` | -| Subject Context composition | Add new Profile exact-read, Topic Memory, Skill, and Experience adapters plus cross-family conflict handling and `max_bytes` composition; these are new implementation work, not behavior supplied by existing Prepare Context | - -### New APIs - -PowerContext already uses operation-style POST endpoints. This RFC carries `subject_key` in the request body rather than -exposing the business user ID in the URL path and access logs. - -| New endpoint | Purpose | Success result | -| --- | --- | --- | -| `POST /v1/subjects/resolve` | Idempotently resolve or create `subject_key -> root_scope_id` | `200`; body `created` distinguishes outcomes | -| `POST /v1/profile/create` | Manually create the first complete Markdown Profile | `201` + `ETag`; `409` if it exists | -| `POST /v1/profile/get` | Get the current Head by `ProfileTarget` | `200` + `ETag` | -| `POST /v1/profile/changes` | List Revisions and generation metadata | `200` | -| `POST /v1/profile/diff` | Compare two Markdown Revisions | `200` unified/structured line diff | -| `POST /v1/profile/replace` | Manually submit complete Markdown with the current Head's `If-Match` | `200` new Revision + `ETag` | -| `POST /v1/profile/rollback` | Copy old content into a new Head Revision with the current Head's `If-Match` | `200` new Revision + `ETag` | -| `POST /v1/profile/generate` | Request immediate processing of existing new Sources without waiting for an LLM | `200`; body status `accepted/idle/review_pending` | -| `POST /v1/profile/processing/get` | Read journal head, Cursor, Pending, and latest result | `200` | -| `POST /v1/profile/policy/get` | Read the automatic/Review Policy | `200` | -| `POST /v1/profile/policy/update` | Update the Policy using its expected version | `200` | -| `POST /v1/subjects/context/prepare` | Resolve the Root and aggregate authorized Artifacts in the Root and its true descendants | `200` | - -Every operation has exactly one success status because the current OpenAPI generator requires one 2xx response per -operation. Resolve always uses HTTP `200` and the body carries `created: bool`. Generate always uses HTTP `200` and the -body carries `status: accepted | idle | review_pending`. Profile Create has the single success status `201`; Profile Get, -Changes, Diff, Replace, Rollback, Processing Get, Policy Get/Update, and Subject Context Prepare each have the single -success status `200`. - -Profile review reuses the existing Artifact Candidate list/get/approve/reject/revise endpoints rather than creating a -second review state machine. The existing Reject request retains `scope_id`, `candidate_id`, `expected_version`, and -`reason`, and gains an optional wire field named `disposition`. After loading the Candidate under version CAS, the -server requires `disposition` for `family="profile"` and rejects it for every other family. This keeps one request schema -without weakening the existing concurrency contract. - -```python -from typing import Annotated, Literal, TypeAlias - -from pydantic import BaseModel, ConfigDict, Field - -# Wire proposal unions after this RFC. -CandidateProposal: TypeAlias = ExperienceProposal | SkillProposal | ProfileContent -# ArtifactCandidate.proposal: CandidateProposal -# ReviseArtifactCandidateRequest.proposal: CandidateProposal - - -# Runtime union after transport mapping. -ReviewedProposal: TypeAlias = ExperienceContent | SkillContent | ProfileContent - - -class RejectArtifactCandidateRequest(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - scope_id: str - candidate_id: str - expected_version: Annotated[int, Field(ge=1)] - reason: Annotated[str, Field(min_length=1, max_length=2_000)] - disposition: Literal["reject_and_consume", "reject_and_retry"] | None = None -``` - -`ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, transport mapping, Runtime -`ReviewedProposal`, Candidate repository validation, and `ReviewService` approve/reject/revise dispatch all gain the -Profile branch together. A Profile revision request still submits a complete `ProfileContent`; approval commits that -exact reviewed proposal through the Profile service. - -For example, when a reviewer determines that the window should not change the Profile: - -```json -{ - "scope_id": "R_U1", - "candidate_id": "candidate_profile_01", - "expected_version": 1, - "reason": "This content is a one-time request and should not become part of the long-lived Profile", - "disposition": "reject_and_consume" -} -``` - -### Resolve Subject Root +| Base Source Create/Get, capture, observation | Unchanged request/response and single-write behavior | +| Scope Create/Get/List and Binding Set/Clear | Unchanged contract; the new endpoint uses internal insert-only ensure | +| Scope Binding Resolve | Add allow_default=true; subject queries pass false to prohibit fallback on a miss | +| Artifact Create/Get/Get Revision/List/Replace | Add profile to Family enums, input unions, and Family writer; reuse paths | +| Candidate Get/List/Revise/Approve/Reject | Add Profile proposal and committer; coordinate Profile Policy/Cursor | +| Artifact Access Profile, capabilities/readiness, internal authorization repository | Register/report profile and support transactional permission bootstrap without new actions or public management changes | +| RuntimeConfig and scheduler registration/configuration | Add Profile Cron configuration and scan callback using existing sidecar | +| Python Client and HTTP adapters | Add four operations; support profile through existing Artifact/Candidate methods | +| PrepareContext and other Family generation endpoints | No expanded aggregation scope or automatic-generation guarantees | + +Manual Profile creation retains the base request shape: ```http -POST /v1/subjects/resolve -Content-Type: application/json -``` - -```json -{ - "subject_key": "U1", - "create_if_absent": true, - "origin_scope_id": "S_GROUP", - "root_contributor": {"type": "user", "id": "principal-u1"} -} -``` +POST /v1/scopes/S_U1/artifacts -```json -{ - "subject_key": "U1", - "root_scope_id": "R_U1", - "created": true -} +{"family":"profile","content":{"content":"# User profile\n\n- Prefers concise answers.\n"}} ``` -Once created, a Root mapping cannot be rebound. If `create_if_absent=false` and no mapping exists, the endpoint returns -`404`. Both the existing and newly created cases return HTTP `200`; callers inspect `created`. Creating the mapping -requires `server.admin` or the trusted provisioning service Principal and atomically creates the Root Scope, mapping, -default Policy, and `root_contributor` binding. Merely knowing `subject_key` never identifies the Principal receiving -that binding. +Read and replace through existing paths: -### Create Source with subject_key - -```http -POST /v1/scopes/S_GROUP/sources -Content-Type: application/json +```text +GET /v1/scopes/S_U1/artifacts/profile/profile +GET /v1/scopes/S_U1/artifacts/profile/profile/revisions/3 +GET /v1/scopes/S_U1/artifacts/profile +PUT /v1/scopes/S_U1/artifacts/profile/profile (If-Match required) ``` ```json -{ - "source_type": "content", - "content": { - "role": "user", - "text": "Please give me the concise conclusion first" - }, - "subject_key": "U1" -} +{"content":{"content":"# User profile\n\n- Prefers concise answers.\n","restored_from_revision":3}} ``` -```json -{ - "scope_id": "S_GROUP", - "source_type": "content", - "source_id": "source_01", - "content": { - "role": "user", - "text": "Please give me the concise conclusion first" - }, - "position": 101, - "content_digest": "sha256:...", - "subject_projection": { - "subject_key": "U1", - "root_scope_id": "R_U1", - "origin_source": { - "scope_id": "S_GROUP", - "source_type": "content", - "source_id": "source_01" - }, - "root_source": { - "scope_id": "R_U1", - "source_type": "content", - "source_id": "source_01" - }, - "status": "committed" - } -} -``` - -`201` means both Sources and the projection relationship have committed; it does not mean that a Profile has been -generated. `subject_projection` always uses `origin_source` and `root_source` to make direction explicit and returns the -same address pair when either side of the relationship is read. - -The idempotency guarantee covers only one server-side operation and retries of its database transaction: the server -reuses the Source ID it has already generated and does not insert a duplicate Root Source. The current HTTP Create -Source endpoint has no `Idempotency-Key`. If a client retries the HTTP request after the commit succeeded but its -response was lost, the retry still creates a new Source and a new Root copy. A general HTTP-create idempotency design -belongs in a separate RFC; this design does not implicitly broaden the current semantics. - -### Get Profile +The PUT example restores Revision 3's Markdown. The response remains ArtifactRevision with server-generated +generation and a new ETag. The SDK keeps its existing If-Match mechanism for Replace; it does not assume response +models have an `.etag` attribute. ```http -POST /v1/profile/get -Content-Type: application/json -``` +POST /v1/artifact-candidates/reject -```json -{ - "target": {"subject_key": "U1"} -} +{"scope_id":"S_U1","candidate_id":"cand_01","expected_version":1,"reason":"This is a temporary request"} ``` -```http -HTTP/1.1 200 OK -ETag: "profile:R_U1:profile:user:12:sha256-abc" -Content-Type: application/json -``` - -```json -{ - "target": { - "scope_id": "R_U1", - "artifact_id": "profile:user", - "subject_key": "U1", - "root_scope_id": "R_U1" - }, - "artifact": { - "scope_id": "R_U1", - "artifact": { - "family": "profile", - "artifact_id": "profile:user", - "revision": 12 - } - }, - "media_type": "text/markdown", - "content": "# User Profile\n\nThe user prefers concise answers in Chinese.\n", - "content_digest": "sha256:...", - "generation": { - "mode": "automatic", - "source_after": 37, - "source_through": 42, - "created_at": "2026-09-07T02:04:18+08:00" - } -} -``` - -The Profile-specific response flattens internal `ProfileContent.content` into a Markdown string. General Artifact Get -continues to return the complete `ProfileContent` object. The HTTP body is `ProfileRecord`; the Python Client returns -`ProfileResponse(record=profile_record, etag='"profile:R_U1:profile:user:12:sha256-abc"')` after reading the response -header. For a Scope-local Profile, `target.subject_key` and `target.root_scope_id` are JSON `null`, while `artifact` -remains a complete `ArtifactAddress` for `profile:local`. - -### Create, replace and rollback - -First manual creation: - -```python -created: ProfileResponse = await client.profile.create( - target=ProfileTarget(subject_key=app_user.user_id), - content="# User Profile\n\nThe user prefers answers in Chinese.\n", - reason="user confirmed initial profile", -) -``` - -Replace must echo the opaque ETag from Get/Create unchanged. The Python Client maps `if_match` to the HTTP `If-Match` -header: - -```python -updated: ProfileResponse = await client.profile.replace( - target=ProfileTarget(subject_key=app_user.user_id), - content="# User Profile\n\nThe user prefers concise answers in Chinese.\n", - if_match=created.etag, - reason="user edited profile", -) -``` - -Rollback creates a new Revision: - -```python -restored: ProfileResponse = await client.profile.rollback( - target=ProfileTarget(subject_key=app_user.user_id), - restore_revision=3, - if_match=updated.etag, - reason="restore user-confirmed version", -) -``` - -Profile Replace and Rollback return `428 Precondition Required` when `If-Match` is absent and -`412 Precondition Failed` when it does not match the current Head's ETag. The ETag must remain opaque; a client cannot -construct it from the Revision. Profile Create, Get, Replace, and Rollback all expose the current Head's `ETag`; the -Profile-specific metadata-aware Python helper returns it without requiring callers to use the low-level HTTP response. - -### Generate now - -```python -receipt = await client.profile.generate( - target=ProfileTarget(subject_key=app_user.user_id), -) -``` - -```json -{ - "status": "accepted", - "scope_id": "R_U1", - "binding_name": "profile-source-window", - "source_through": 42, - "flush_generation": 8 -} -``` - -This endpoint only asks processing to begin immediately for new Sources that already exist. With no new Source, it -returns HTTP `200` with `{"status":"idle", ...}`. If an automatic Candidate is already pending, it returns HTTP `200` -with `status="review_pending"` and its `pending_candidate_id`. `accepted` also uses HTTP `200`; none of these states uses -`202`. - -### Subject context aggregation API +No subject Artifact CRUD, Subject Resolve, or Profile history/diff/rollback/context APIs are added. To query by +subject_key, resolve the exact binding, then call ordinary Scope APIs. Resolve retains its existing server.observe requirement: ```http -POST /v1/subjects/context/prepare -Content-Type: application/json -``` - -```json -{ - "subject_key": "U1", - "query": "Recommend a hotel suitable for the user", - "families": ["profile", "memory", "topic-memory", "skill", "experience"], - "max_bytes": 262144 -} -``` - -```json -{ - "subject_key": "U1", - "root_scope_id": "R_U1", - "scope_ids": ["R_U1", "S_U1_PROJECT"], - "items": [ - { - "address": { - "scope_id": "R_U1", - "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} - }, - "content": "# User Profile\n\nThe user prefers concise answers in Chinese.\n", - "selected_bytes": 67 - }, - { - "address": { - "memory": { - "scope_id": "S_U1_PROJECT", - "artifact": {"family": "memory", "artifact_id": "memory", "revision": 7} - }, - "entry_id": "hotel-preference", - "entry_version_id": "mev_01" - }, - "content": "For hotels in China, the user prefers a king room.", - "selected_bytes": 53 - } - ], - "conflicts": [ - { - "summary": "Budget information conflicts across time", - "left": { - "scope_id": "R_U1", - "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} - }, - "right": { - "scope_id": "S_U1_PROJECT", - "artifact": {"family": "topic-memory", "artifact_id": "travel", "revision": 4} - } - } - ], - "used_bytes": 120, - "max_bytes": 262144, - "truncated": false -} -``` - -The server resolves `R_U1`, selects the Root and true descendants after authorizing each Scope, then performs -family-specific recall, exact deduplication, semantic deduplication, conflict annotation, ranking, and `max_bytes` -composition. This is a new `SubjectContextAdapter` plus new HTTP/Python adapters; it does not mean the existing Prepare -Context path already traverses Subject Roots. Every Artifact is exposed through the cross-Scope `ArtifactAddress`, -which is its globally complete address; a Memory Entry or another subresource uses a family-owned address containing -an `ArtifactAddress`. The shared group chat `S_GROUP` is not included merely because U1 participates, and existing -Artifacts in that Scope are not automatically copied in the first release. - -If a future Artifact Family reuses this design, it should register its own processing binding for Root Sources and -generate user-level Artifacts into `R_U1` or a true child Scope. They then naturally enter the same subject query range -without adding `subject_key` to the general Artifact table. - -## Access control and privacy - -The implementation reuses the existing `scope.*` and `artifact.*` actions from -[RFC 1396](1396_handoff_access_control.md). It adds no `subject.*` or `profile.*` action vocabulary: +POST /v1/scope-bindings/resolve -```python -ARTIFACT_FAMILY_PROFILES["profile"] = ArtifactFamilyAccessProfile( - family="profile", - enabled=True, - share_unit="artifact", - shareable_states=frozenset({"committed"}), - base_action=AccessAction.ARTIFACT_READ, - additional_actions=frozenset(), - grantable_roles=frozenset({AccessRole.ARTIFACT_VIEWER}), - selector="forbidden", - transitivity="none", - mutation_semantics=frozenset({AccessAction.ARTIFACT_WRITE}), -) +{"binding_keys":[{"integration":"subject","kind":"user","external_id":"U1"}],"allow_default":false} ``` -Thus the exact access contract is: enabled family, whole-Artifact share unit, only `committed` state shareable, -`artifact.read` base action, `artifact.viewer` grantable role, no selector, no transitivity, and `artifact.write` mutation -semantics. A pending Candidate is not a committed Profile Artifact and remains governed by `scope.review`. +## Errors, compatibility and implementation -| Profile/Subject operation | Existing action | -| --- | --- | -| Resolve an existing Subject Root | Require `scope.read` on the Root before returning the mapping; insufficient authorization always returns `403` | -| Create a Subject Root | Require Origin `scope.contribute` plus either caller `server.admin` or invocation of the configured trusted provisioning service Principal; atomically create Root, mapping, Policy, and the explicit `root_contributor` / `scope.contributor` binding | -| Write a subject-keyed business Source | Always require Origin `scope.contribute`; for an existing Root, also require Root `scope.contribute`; first creation uses the bootstrap rule above | -| Profile Get, Changes, Diff | Require `artifact.read` on the logical Profile; discovery through a Scope list also requires `scope.read` | -| Manually create the first Profile or request Generate | Require `scope.contribute` on the target Scope; establish the owner through the existing Artifact flow after creation | -| Profile Replace, Rollback | Require a system-managed owner relation and `artifact.write` on the logical Profile | -| Review a Profile Candidate | Require `scope.review` on the target Scope | -| Profile Policy Get/Update | Get requires `scope.read`; Update requires `scope.admin` | -| Subject Context Prepare | Require `scope.read` on every included Scope and `artifact.read` for exact-resource authorization paths | - -Parent, Root mappings, and `subject_key` do not grant authorization. This RFC never derives a Principal from the business -`user_id`. During first-time bootstrap, the authenticated initiating Principal is recorded as the subject of the -explicit `root_contributor` binding with the existing `scope.contributor` role; a trusted provisioning service may -instead install the business Principal supplied through its authorized provisioning context. Root, mapping, default -Policy, and binding commit atomically. For an existing Root, the PEP must allow `scope.contribute` on both Origin and -Root before the dual write. Any denial or bootstrap failure prevents all Source and metadata writes. - -Profile must be registered in RFC 1396's Artifact Family Access Profile registry exactly as shown above. This adds no -Profile-specific action. A background Processor must run with its configured service/system Principal; an empty -Principal cannot execute generation. - -Privacy requirements: - -- logs, metrics, and errors do not include the raw `subject_key`, Source content, or Markdown by default; -- the database stores the business `user_id` directly as `subject_key`; reads, backups, and audits protect it according - to policies for user identifiers; -- a Root Source is a copy of original content and must use the same encryption, retention, and deletion policies as the - origin Source; -- a Root Scope title or summary does not contain a user ID; -- aggregation authorizes every Scope and Artifact and does not disclose the existence or count of unauthorized Scopes; -- review, edit, and rollback record the actor, time, reason, and target Revision. - -## Error semantics - -| Scenario | Recommended result | +| Condition | Result | | --- | --- | -| `subject_key` is empty or longer than 256 characters | `422 invalid_subject_key` | -| `subject_key` does not exist and Root creation is forbidden | `404 subject_root_not_found` | -| Root is absent and the calling Principal lacks Origin `scope.contribute` or required `server.admin` | `403 Forbidden` | -| `root_contributor.type` is not `user/service` | `422 invalid_root_contributor` | -| The Authorization Provider cannot create a Binding transactionally and no trusted provisioner is available | `503 relationship_management_unavailable` | -| Two keys attempt to bind the same Root | `409 subject_root_binding_conflict` | -| The current Scope is another user's Root | `409 subject_key_mismatch` | -| A public request writes a user Root without a key | `422 subject_key_required` | -| An Origin Source has already been projected to another key | `409 source_subject_conflict` | -| Origin and Root Sources have the same identity but different payloads | `409 source_projection_content_conflict` | -| Any step of the dual write fails | Roll back the whole transaction; leave no one-sided Source | -| Subject Resolve creates or finds a Root | Always `200 OK`; distinguish with `created` | -| Generate is called with no new Source | `200 idle` | -| An automatic Profile Candidate is already pending | `200 review_pending`; do not generate a duplicate | -| Profile processing has been awakened | `200 accepted` | -| Background LLM or validation fails | Preserve the old Head, do not advance the Cursor, and retry | -| Head or Cursor CAS conflicts | Reread the latest state and process again | -| Profile Create finds an existing Head | `409 profile_already_exists` | -| Replace/Rollback omits `If-Match` | `428 Precondition Required` | -| Replace/Rollback ETag does not match the current Head | `412 Precondition Failed` | -| The Head changed during Review | `409 profile_revision_conflict`; preserve the Candidate and do not advance the Cursor | -| Rollback target Revision does not exist | `404 profile_revision_not_found` | -| Root or child Scope is unauthorized | `403 forbidden` | - -## Configuration - -```yaml -profile: - enabled: true - artifact_id: "profile:user" - local_artifact_id: "profile:local" - max_content_bytes: 262144 - processing_binding: "profile-source-window" - schedule: - cron: "0 2 * * *" - timezone: "Asia/Shanghai" - source_window_limit: 200 - max_concurrency: 8 - worker_timeout_seconds: 900 - retry_max_delay_seconds: 1800 -``` - -Schedule is deployment-level configuration. `generation_enabled` and `activation_mode` are Scope-level Policy. The -first release does not expose an individual Cron schedule for each user, avoiding a separate scheduler job for every -user; one daily wave processes all dirty targets fairly. - -## OpenAPI impact - -`openapi/powercontext.yaml` is the source of truth for the contract. Implementation must make the following changes and -regenerate code: - -1. Accept `profile` in exact generic Artifact Get, Get Revision, List, Artifact response, and capability schemas while - keeping the generic `CreateArtifactRequest` and `ReplaceArtifactRequest` unions unchanged; their endpoints reject - Profile writes in v1. -2. Add `profile` to `CandidateFamily` and register the exact `ArtifactFamilyAccessProfile` defined above. -3. Add optional `subject_key` and `root_contributor` to `CreateSourceRequest`, `CaptureContentSourceRequest`, and - `SubmitSourceObservationRequest`. -4. Add optional `subject_projection` to `SourceRecord` without removing existing `receipt_identity`. -5. Keep `ArtifactRevision.content` as an object rather than changing it to a raw string. -6. Add `ProfileContent` to `ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, transport mapping, - and Runtime `ReviewedProposal`; add optional `disposition` to the existing Reject request and require it for Profile - after Candidate lookup. -7. Expose the readable `profile` family, `profile_generation`, and the Subject Context adapter capability through - Capabilities. -8. Define `ETag` response headers for Profile Create/Get/Replace/Rollback and an `If-Match` request header for - Replace/Rollback; preserve `428/412` for missing or mismatched preconditions. -9. Give every new operation exactly one 2xx response: Resolve and Generate both use `200`, with `created` or `status` in - the body. -10. Add Subject resolve/context prepare and Profile create/get/changes/diff/replace/rollback/generate/processing/policy - operations, including pagination, `ArtifactAddress`, conflict, and `max_bytes` schemas. -11. Generate metadata-aware Python transport helpers for Profile Create/Get/Replace/Rollback so their high-level sync - and async methods return `ProfileResponse(record, etag)`. -12. Continue generating checked-in sources through `make api-generate`; do not edit - `src/powercontext/http/_generated/` manually. - -## Implementation plan - -1. Add the Profile family, `ProfileContent` codec, fixed-identity Profile service, and Markdown normalization; exact - generic reads support Profile, while generic Artifact Create/Replace does not. -2. Add `pc_subject_roots`, implementing Root Resolve, uniqueness constraints, Root Parent protection, and atomic - authorization bootstrap with the explicit `root_contributor` binding. -3. Add the shared `SubjectSourceRoutingService` and route `CreateSourceRequest`, `CaptureContentSourceRequest`, and - `SubmitSourceObservationRequest` through it so every business Source entry point carrying a `subject_key` performs - dual-Scope locking, the dual Source write, projection recording, and Pending upsert in one transaction. Exclude - internal lineage/domain Sources from routing. -4. Implement or reuse general Pending, Cursor, Lease, and Artifact Processing Supervisor support. -5. Add a time-zone-aware Profile CronTrigger, defaulting to `02:00 Asia/Shanghai` daily. -6. Implement the Profile Worker: fixed Window, read-before-write, LLM Markdown, NOOP, and Head/Cursor CAS. -7. Add Revision Metadata, Candidate Window Metadata, the single pending pointer in Policy, complete-Markdown Candidate - unions, and Profile-aware Review Service branches. -8. Implement Profile convenience HTTP adapters, metadata-aware Python sync/async clients, history, Diff, manual - replacement, rollback, and ETag propagation. -9. Implement the authorized aggregation endpoint and new family composition adapters over the Subject Root range, - returning cross-Scope `ArtifactAddress` values under the request's `max_bytes` budget. -10. Add tests for concurrent first Resolve, authorization bootstrap, dual-write atomicity, group-chat isolation, - scheduler recovery, one-success-status OpenAPI generation, ETag preservation, Candidate Reject dispositions, - failure retry, Review, and rollback. +| Invalid subject_type, blank key, invalid Markdown, or unknown input fields | 422 | +| Existing binding differs from explicit subject_scope_id | 409 subject_scope_conflict | +| Both actual Scopes are equal | 422 distinct_scopes_required | +| Explicit Scope does not exist | 404; never silently create a caller-specified ID | +| Missing required Scope/management permission | 403, no partial write | +| Profile Create when already present | 409 | +| Replace missing/mismatched If-Match | 428 / 412 | +| Policy/Candidate version or review Cursor conflict | 409, no Cursor advance | +| Approve target Head changed | 409, preserve Candidate | +| Model/storage temporarily unavailable | 503, preserve recoverable state | + +Responses retain Request-ID and the existing error envelope and avoid exposing unauthorized Scope content or binding +details. Profile requires coordinated OpenAPI union, output schema, Candidate proposal, and Family registrations. +Server-owned fields remain separate from client input; a GET generation object is not writable input. + +Implementation order: + +1. Add Profile content/write/proposal models and Family writer, reusing singleton IDs, Artifact repository, lineage, and authorization. +2. Create only the Policy table; define versioned BLOB schemas and server validation for generation metadata and Candidate processing context. +3. Implement insert-only ensure and transactional dual-write application service, including concurrent first creation, permissions, and full rollback. +4. Implement the Source-window Processor, Policy/Cursor/Head coordination, Candidate lifecycle, and daily Cron. +5. Add four OpenAPI operations and extend existing Family/Candidate branches; run `make api-generate` without hand-editing generated files. +6. Add bilingual usage documentation and SQLite/OceanBase behavior tests; run `make contract-test`, `make test`, `make check`, and `make docs-test`. ## Acceptance criteria -### Scope and identity - -- U1, U2, U3, and one group chat produce exactly four Scopes: `R_U1/R_U2/R_U3/S_GROUP`. -- The group-chat Scope is not automatically set as any user Root's child or context reference. -- Concurrent Resolve operations for one `subject_key` produce only one Root. -- First Resolve requires Origin `scope.contribute` plus `server.admin` or the trusted provisioning service Principal and - atomically creates Root, mapping, Policy, and the explicit `root_contributor` / `scope.contributor` binding. -- `subject_key` never derives or authenticates a Principal; an existing Root requires `scope.contribute` on both Origin - and Root. -- Different `subject_key` values cannot map to the same Root. -- A Root's Parent is always `NULL`. -- Accessing the Profile through `subject_key=U1` or `scope_id=R_U1` normalizes to the same `profile:user`; callers cannot - create `profile:local` in the Root. -- Profile content and identity use only `subject_key`, `root_scope_id`, and the fixed Profile Artifact address; they add - no second user identifier or Profile-type field. - -### Source routing - -- Without `subject_key`, every business Source entry point preserves its existing persistence behavior. -- `CreateSourceRequest`, `CaptureContentSourceRequest`, and `SubmitSourceObservationRequest` all accept the optional key - and use the same routing service; internal lineage/domain Sources do not accept it. -- With `subject_key`, exactly two Sources are written: one Origin and one corresponding Root Source. -- Both Sources have identical payloads, while each Scope assigns its journal position independently. -- A failure at any step leaves no one-sided write. -- A U1 Source does not change the journal, Pending, or Cursor for the U2/U3 Roots. -- A database-transaction retry of the same server operation does not create a duplicate Root Source; a new HTTP Create - request still creates a new Source under existing semantics. -- Multi-user batch content cannot be written as one subject-keyed Source. - -### Profile content and revision - -- Profile content consists only of complete Markdown; no Claim category, Claim table, or per-Claim risk level exists. -- `ProfileContent` encodes Markdown into the existing BLOB; the existing Artifact tables require no DDL change. -- A Root has only one `profile:user` Head, and `artifact_id` is part of its unique identity. -- Create conflicts when a Head exists; Replace uses CAS. -- Profile Create/Get/Replace/Rollback expose HTTP `ETag`; Python returns `ProfileResponse(record, etag)` and preserves - the opaque header for `If-Match`. -- Generic Artifact Create/Replace does not accept Profile in v1; exact generic Get/List/Get Revision does. -- Automatic generation, manual editing, approval, and rollback all create immutable Revisions. -- No semantic change creates no empty Revision. - -### Automatic generation - -- Processing starts at `02:00 Asia/Shanghai` daily by default, with configurable Cron and time zone. -- Committing a business Source does not wait for an LLM. -- The Scheduler recovers one coalesced wave after a missed time. -- A Worker freezes an `(after, through]` Window. -- A Worker excludes `lineage_only` system Sources; a window empty after filtering skips the LLM but may still advance - the Cursor. -- The same Profile is processed serially; different Profiles run in parallel within the configured concurrency limit. -- A failure does not advance the Cursor or affect another user. -- Scheduled and manual Generate do not rebuild without a new Source. -- Resolve and Generate each expose exactly one HTTP success status (`200`); Generate distinguishes - `accepted/idle/review_pending` in the body. - -### Review and correction - -- The complete Profile activates automatically by default. -- Policy can switch the complete Profile to `review_required`. -- Candidate review reuses the existing Candidate state machine. -- `ArtifactCandidate.proposal`, `ReviseArtifactCandidateRequest.proposal`, Runtime `ReviewedProposal`, and Review Service - all support complete `ProfileContent`. -- Each Profile Scope has at most one pending automatic Candidate, whose Source Window can be recovered after restart. -- Reject requires an explicit `reject_and_consume` or `reject_and_retry`, with tests that respectively advance or - preserve the Cursor. -- Manual Replace and Rollback must use the current Head's opaque `ETag` as `If-Match`. -- Rollback creates a new Revision; it neither deletes history nor moves the Head backward. -- Human confirmation applies only to the complete Revision/Head through `generation_mode`; no paragraph-level trust is - inferred. - -### Database and API inventory - -- Every new table has primary keys, uniqueness constraints, foreign keys, and idempotency semantics. -- `restored_from_revision` has an exact Artifact Revision foreign key, and generation-mode, generator/window, rollback, - and Candidate binding fields have explicit CHECK constraints. -- The existing-table change matrix explicitly records that there are no physical DDL changes. -- OpenAPI enums, unions, Source schemas, and all new operations have contract tests. -- Python SDK examples cover Resolve, the dual Source write, and Profile Get/Replace/Rollback/Generate. -- Subject Context enforces its `max_bytes` budget and returns complete `ArtifactAddress` values for results and - conflicts. - -## Decision summary - -1. Add the `profile` Artifact Family, supporting only user Profiles in the first release. -2. Use the caller's business `user_id` directly as `subject_key`; support no other subject type initially. -3. Map one `subject_key` one-to-one to one `root_scope_id`; the Root is an ordinary Scope whose Parent is always `NULL`. -4. A group chat with U1, U2, and U3 uses four Scopes including the shared group-chat Scope; the shared Scope belongs to - no user Root subtree. -5. Persist each subject-keyed Source exactly twice: the original Source in the business Scope and the Root Source in the - corresponding user Root, committed in one transaction. -6. Do not add `subject_key` to existing Source or Artifact tables; use new mapping and projection tables. -7. Use the fixed `(root_scope_id, profile, profile:user)` identity in a user Root; an ordinary Scope may explicitly - enable `profile:local`. -8. Profile content is complete Markdown encoded through `ProfileContent.content` into the existing BLOB; define no - Claim categories, per-Claim risks, or Claim table. -9. Generate in the background at `02:00 Asia/Shanghai` daily by default, with configurable Cron and time zone; Manual - Generate processes only existing new Sources. -10. Trigger automatic updates only from a new Source Window; no new Source means no rebuild, and no semantic change - means no new Revision. -11. Activate the entire Revision automatically by default, with per-Profile-Scope `review_required` configuration. -12. Manual creation, replacement, approval, and rollback all create immutable Revisions; Create/Get/Replace/Rollback - return `ETag`, and Replace/Rollback use `If-Match`. -13. Add `pc_subject_roots`, `pc_subject_source_projections`, `pc_profile_policies`, - `pc_profile_revision_metadata`, and `pc_profile_candidate_metadata`; if the general processing substrate has not - landed, also add `pc_artifact_processing_pending` and `pc_artifact_processing_leases`. -14. Make no physical DDL change to existing tables including `pc_scopes`, `pc_sources`, `pc_artifacts`, Heads, Lineage, - Cursor, and Candidates. -15. Extend the three general business Source requests, Candidate proposal unions, and Capabilities additively; do not - add Profile to the generic Artifact write unions. Route every business Source entry point carrying `subject_key` - through the shared subject-routing service, and add Subject and Profile convenience APIs. -16. Future Artifact Families may reuse Subject Root and Root Sources, but existing Artifacts in a shared Scope do not - automatically become cross-Scope. +- Add only pc_profile_policies with no column/index/FK changes to existing tables; Artifact/Candidate BLOBs contain validated server metadata. +- Single-Scope Source APIs still write once; the subject endpoint writes two Sources with matching IDs/content without invoking an LLM. +- Concurrent first bindings leave no orphan Scope; explicit binding conflicts, authorization failures, and either Source failure roll back everything. +- Management rebind/unbind behavior remains intact; later writes use new bindings, historical data does not migrate, and multiple subjects may share a Scope. Subject Resolve never falls back to a default Scope on a miss. +- U1's message changes only S_GROUP and actual S_U1 journals; both may generate Profile independently without triggering U2/U3. +- Equal target Scopes are rejected; new HTTP retries may produce new Source pairs and are not described as idempotent. +- Every Scope uses the same Profile singleton ID; Create conflicts and Get/List/Replace/Review reuse existing APIs. +- Default schedule is 02:00 Asia/Shanghai with configurable Cron/timezone; startup scans recover backlog without pending/job tables. +- Filter lineage_only while advancing full windows; unchanged Markdown creates no automatic Revision, and model upgrades alone do not rebuild. +- Concurrent computations commit at most once; Policy changes, manual Replace, and Cursor changes invalidate stale results. +- Clients cannot edit Candidate processing context; pending Candidates prevent regeneration; decisions update Cursor and pointer atomically. +- Reject consumes its window without automatic retry or Source deletion; it works after Head changes while Approve must conflict. +- Rollback creates a new Revision while preserving history and Cursor; existing authorization and Source eligibility checks cover every Profile write path. +- No new automatic generation or aggregation capability is implicitly promised for Memory, Experience, Skill, Topic Memory, or other Families. # Drawbacks -- Each subject-keyed Source is stored twice, increasing storage, backup, retention, and deletion costs. -- The dual Source write expands a formerly single-Scope transaction to two Scopes, requiring consistent lock order and - stricter concurrency testing. -- The existing HTTP Source Create endpoint has no client idempotency key, so a request-level retry after a lost response - may still create duplicate facts and corresponding Root copies. -- Correct `subject_key` assignment depends on the caller; PowerContext does not merge accounts or correct a mistaken - identity. -- Daily generation means normal Profile latency can approach one day; applications needing an immediate result must - call Generate. -- A single Markdown document simplifies storage and reading but gives up Claim-level queries, risk classification, and - fine-grained provenance in the first release. -- Existing Artifacts in a shared Scope do not automatically become user-level artifacts; another family must explicitly - consume Root Sources and generate into the Root. -- Root copies of original Source content expand the privacy and forgetting surface. - -# Rationale and alternatives - -## Why Subject Root is not the group Scope parent - -A Scope has only one Parent, while a group chat can have many users. Attaching the shared Scope to any one user would -misrepresent organizational ownership; attaching it to multiple users cannot be represented by the current model. This -RFC therefore expresses the subject relationship through Source projection and reserves Parent for genuine -organization. +Dual Source writes increase storage and journal processing costs. Shared and user Scopes can independently generate +different profiles with duplicate LLM costs. Without a projection index, cross-Scope copy discovery and coordinated +deletion are inefficient. Without distributed job leases, competing workers may call the model redundantly. Review +blocks later automatic Profile windows in the same Scope; fixed Reject consumption gives up automatic retry of the +rejected window. -## Why subject_key is family-neutral +Mutable, many-to-one bindings can fragment long-lived memories or mix users' information. Applications must manage +bindings, preserve message context, and understand Scope authorization boundaries. BLOB generation metadata cannot +have direct database foreign keys or efficient field-level queries; server validation and transactions maintain its +integrity. -In the first release, `subject_key` equals the business `user_id` directly; it introduces neither an opaque key nor a -second identity. The `subject` name allows future families such as Memory, Topic Memory, and Experience to reuse the same -Root addressing and Root-local Sources without each defining another user key. +# Rationale and alternatives -## Why a ProfileContent wrapper instead of raw BLOB bytes +## Reuse scope bindings and ordinary scopes -The current Artifact Repository requires family content to be a Pydantic Model, and general -`ArtifactRevision.content` is an object. Encoding Markdown into the existing BLOB through `ProfileContent` preserves -both the shared tables and the general response shape. Writing raw Markdown bytes would require changes to the Artifact -Repository codec, runtime records, and the OpenAPI response union, which the first release does not need. +Existing Bindings already map external business identifiers to Scopes. A fixed integration, initial user kind, and +subject_key provide subject addressing. Mutable management mappings fit the existing abstraction; automatic writes +use ensure to avoid accidental rebinding. Extra Root types, reverse uniqueness constraints, and subject-specific CRUD +would add management semantics that the first release does not need. -## Why a daily Cron plus manual Generate +## One policy table and existing blobs -Daily off-peak batching coalesces frequent Sources and reduces LLM call volume and concurrency pressure. Manual Generate -provides an explicit escape hatch for applications that need a Profile immediately. The default time is operational -policy rather than Source or Artifact semantics, so deployments may change it. +Policy needs atomic CAS for configuration and a unique pending pointer. Existing Scope settings are not arbitrary +JSON configuration storage and cannot directly hold these fields. Revision and Candidate metadata are typed content +of existing objects, suitable for their BLOBs. Policy, Cursor, Source journal, and Candidate reconstruct processing +state, so no pending, lease, projection, revision metadata, or candidate metadata tables are added. -## Why no Claim categories +## Dedicated subject write convenience -The primary first-release consumer needs a human-editable Profile document that can be injected directly into context. -Splitting content into fixed Claim categories expands extraction, schema, migration, and review complexity. Complete -Markdown is a better way to validate user value first. If structured retrieval becomes necessary, a rebuildable index -can be derived from Artifact Revisions without changing the fact source or artifact identity. +Two base Source Create calls cannot guarantee atomic success. A subject dual-write endpoint follows base content +and response models and uses repositories within one transaction while preserving single-write endpoints. An +arbitrary scope_ids batch endpoint does not express subject binding resolution, so this RFC does not expand into +general batch operations. # Prior art -Existing PowerContext designs provide reusable foundations for this RFC: - -- [RFC 0019](0019_local_source_memory_runtime.md) defines Source journals, consumption Cursors, and local Runtime - transaction boundaries; -- [RFC 0050](0050_artifact_candidate_review_inbox.md) defines immutable Candidates and the review state machine; -- the [Topic Memory RFC](0000_topic_memory.md) defines general Artifact processing Pending, leases, Supervisor, and fixed - Source Windows; -- [RFC 1345](1345_scope_organization_and_agent_integration.md) defines Scope organization, isolation, and sharing; -- [RFC 1437](1437_source_artifact_rest_api.md) defines public Source and Artifact identity, Create, Replace, and Revision - APIs. - -This RFC reuses those mechanisms instead of creating a second Source, Artifact, Candidate, or background-task identity -space for Profile. - -The [official TencentDB Agent Memory README](https://github.com/Tencent/TencentDB-Agent-Memory/blob/main/README.md) -describes layered long-term memory and Persona processing. The -[official OpenViking Session documentation](https://github.com/volcengine/OpenViking/blob/main/docs/en/concepts/08-session.md#memory-extraction) -describes asynchronous Memory Extraction, the user memory namespace, and `profile.md`. These specific designs informed -the engineering choices around layered background processing, checkpoints, user Roots, and updating after reading an -existing Profile. - -This RFC borrows only their engineering ideas around asynchronous processing, cursors, and incremental generation after -reading the old Profile; it does not reuse their identity models. This document independently defines PowerContext's -`subject_key <-> root_scope_id`, shared-Scope dual writes, and authorization boundary. +- PowerContext [base REST API](1437_source_artifact_rest_api.md) supplies Source/Artifact identity, atomic commits, + ETags, and lineage_only; the [Scope RFC](1345_scope_organization_and_agent_integration.md) supplies ordinary Scopes and Bindings. +- The [Candidate Review RFC](0050_artifact_candidate_review_inbox.md) supplies candidate versions and review lifecycle; + [Topic Memory](0000_topic_memory.md) provides independent Source-window consumer references. This design does not depend on its proposed task tables. +- [TencentDB Agent Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory#technical-implementation) uses layered + asynchronous processing, and [OpenViking Session](https://github.com/volcengine/OpenViking/tree/main/openviking/session) + provides session-processing references for accumulating evidence into long-term memory. This RFC uses PowerContext's own Scope, Cursor, and transaction contracts. # Unresolved questions -The first-release feature and identity model are decided. Before the RFC merges, the minimum consistent-deletion -semantics for a Root Source and its Origin Source must still be specified: deleting or forgetting either side must use -`pc_subject_source_projections` to find and process the other side in the same authorized operation, so the Profile -cannot later consume a copy that the user requested to forget. Physical deletion, logical tombstones, retention of -generated Revisions, and audit rules must align with the project's unified data-deletion protocol. - -The following questions do not block this RFC and should be designed separately after concrete requirements emerge: - -- anonymous-to-registered user conversion, account aliases, account merging, and `subject_key` migration; -- cross-request `Idempotency-Key` support for HTTP Source Create; -- a Claim-level query, citation, or risk-analysis index derived from Profile Revisions; -- how Artifact Families other than Profile select and consume Subject Root Sources. +This document defines first-release behavior rather than leaving consistency decisions to callers. Operational +parameters such as model timeouts and deployment concurrency ceilings follow existing deployment configuration. +Cross-Scope Source deletion and forgetting, data migration after rebinding, strict reverse uniqueness, explicit +reproposal after rejection, and all-Family Context aggregation are outside this RFC and need separate designs. +Neither dual writes nor Bindings implicitly provide those capabilities. # Future possibilities -Future Artifact Families may register their own Root-local Source processing bindings and derive user-level Memory, -Topic Memory, Experience, or Skill into the Subject Root and its true child Scopes without changing the general identity -of `pc_sources` or `pc_artifacts`. Each Family's own design should decide whether to enable this derivation. - -Profile Markdown may produce a rebuildable structured retrieval index for paragraph-level recall, conflict prompts, or -evidence location. Such an index must always derive from immutable Profile Revisions and exact Source lineage. It must -not become another source of truth or change the single-Markdown content contract of Profile. - -Subject Context aggregation may evolve family quotas, conflict explanations, progressive expansion, and observability, -but it must preserve per-Scope and per-Artifact authorization and the boundary that participation does not automatically -place a shared business Scope in a user's Root subtree. - -After general Source-create idempotency, subject migration, and data-forgetting protocols each become stable, Subject -Root routing can reuse those capabilities to further reduce the operational cost of network retries, account lifecycle, -and original-content duplication. +Supported subject_type values can expand while continuing to use Scope Bindings without changing Profile singleton +identity. Unified processing policies, task leases, and cross-Scope Source copy relationships may serve all Families +in the future. Their requirements should drive separate RFCs rather than becoming implicit Profile dependencies. +Fine-grained fact review or permanent suppression of rejected content would require a separate structured fact and +governance model. diff --git a/docs/zh/rfcs/1485_profile_artifact.md b/docs/zh/rfcs/1485_profile_artifact.md index a1126be6b8..892a8e3a19 100644 --- a/docs/zh/rfcs/1485_profile_artifact.md +++ b/docs/zh/rfcs/1485_profile_artifact.md @@ -1,1791 +1,789 @@ - Proposal Name: `profile_artifact` - Start Date: 2026-09-07 - RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) -- Related RFCs: [RFC 0014](0014_memory_layer_design.md), [RFC 0019](0019_local_source_memory_runtime.md), - [RFC 0050](0050_artifact_candidate_review_inbox.md), [Topic Memory RFC](0000_topic_memory.md), - [RFC 1345](1345_scope_organization_and_agent_integration.md), - [RFC 1396](1396_handoff_access_control.md),以及 [RFC 1437](1437_source_artifact_rest_api.md) +- Related RFCs: [Scope organization](1345_scope_organization_and_agent_integration.md), + [Access control](1396_handoff_access_control.md), [Source and Artifact REST API](1437_source_artifact_rest_api.md), + [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](0000_topic_memory.md) # Summary -本 RFC 为 PowerContext 增加 `profile` Artifact Family。首期只设计固定的用户画像,不提供画像类型字段、其他画像类型或 Profile Schema Registry。 +本 RFC 增加 `profile` Artifact Family:基于一个 Scope 中的 Source 生成完整 Markdown 画像。用户画像是主要使用方式; +多人会话 Scope 也可以生成自己的整体画像。Profile 复用现有 Artifact、Head、Lineage、Candidate 和 Source Cursor, +只新增 `pc_profile_policies` 策略表,不修改已有表的列、索引或约束。 -画像是由 Source 派生的、可重建的完整快照,不是事实源。用户画像使用固定地址: - -```text -Head identity: -(root_scope_id, family="profile", artifact_id="profile:user") - -Exact revision identity: -(root_scope_id, family="profile", artifact_id="profile:user", revision) -``` - -`subject_key` 是调用方在业务 Source 写入时直接传入的业务 `user_id`。PowerContext 不生成另一套用户标识,也不解释、 -拼接或归一化该值。命名为 `subject_key`,是为了让 `subject_key -> root_scope_id` 的主体寻址和 Source 投影机制将来可被 -其他 Artifact Family 复用;首期主体仍固定为用户。 - -Scope 组织采用唯一方案: - -- 每个 `subject_key` 一一对应一个用户 Root Scope; -- 共享业务 Scope 不挂到任一用户 Root 下; -- 带 `subject_key` 的 Source 在同一事务内写入业务 Scope 和该用户 Root Scope,总共保存两条 Source 记录; -- Profile Processor 只消费 Root Scope 内的 Source journal,因此不同用户互不触发; -- 没有 `subject_key` 的普通 Scope 仍可显式启用 Scope-local Profile。 - -Profile 不再拆分 Claim category、Claim 行或风险等级。LLM 输出完整 Markdown,作为 `ProfileContent.content` 保存到现有 `pc_artifacts.content` BLOB。自动生成默认每天 `02:00` 执行,使用部署配置的 IANA 时区,默认 `Asia/Shanghai`;调用方可以修改 Cron 与时区,也可以请求立即生成。 +主体寻址使用调用方提供的 `subject_key`,通过现有 `pc_scope_bindings` 映射到一个普通 Scope。新增主体 Source +写入接口,在同一事务中向业务 Scope 与绑定的主体 Scope 各保存一条 Source。现有单 Scope Source 接口保持单写。 +默认每天 `02:00 Asia/Shanghai` 处理启用画像且有新增证据的 Scope,支持配置时间、人工 Flush、Candidate 审核、 +人工修改和通过 Replace 回退。主体绑定只负责路由,不改变 Scope 的存储、组织或授权语义。 # Motivation -面向用户的 Agent 需要跨会话、跨任务和跨业务 Scope 使用同一份长期画像。仅在原业务 Scope 内生成画像会导致同一个用户在多个 Scope 中形成多份画像;直接给所有 Source 和 Artifact 增加 `user_id` 列,又会把存储归属、内容主体、内容产生者和权限主体混为一谈。 - -多人会话进一步说明了这种区别。一个群聊 Scope 可以同时包含 U1、U2、U3 的发言,但 `pc_scopes.parent_scope_id` 只有一个值,群聊 Scope 不可能同时成为三个用户 Root 的子 Scope。正确做法是保留群聊 Scope 的原始组织关系,把每个用户自己的 Source 精确复制到自己的 Root,再在 Root 中生成用户画像。 - -本设计把通用 Source、Scope 和 Artifact 保持为事实与制品基础设施,只增加一套窄化的主体路由便利能力。接入方仍负责决定业务用户、会话和 Source 如何对应;PowerContext 负责稳定解析 Root、可靠双写 Source、后台生成画像和维护 Revision。 +一个用户可能参加多个会话,也可能与其他用户共用一个群聊 Scope。应用希望在群聊中保留完整讨论,同时把一个用户的 +相关发言积累到长期使用的独立 Scope。两个 Scope 都可以使用 PowerContext 已支持的 Artifact 能力。 -## Goals +业务系统负责判断用户身份、哪些内容属于哪个用户,以及何时管理绑定。PowerContext 提供 Scope Binding、可靠的双写 +便利接口和按 Scope 生成画像的能力。接入方无需把群聊设置为用户 Scope 的子节点,也无需把 `user_id` 加入所有 Source +和 Artifact 的关系数据库列。 -1. 新增 `profile` Artifact Family,复用现有 Artifact Head、Revision、Lineage 和 CAS 语义;写入由 Profile 专用入口 - 调用内部 RecordService,不扩展通用 Artifact Create/Replace 的公开写入联合类型。 -2. 首期只支持固定用户画像;不设计画像类型扩展、Claim category 和逐 Claim 风险模型。 -3. 以调用方业务 `user_id` 作为 `subject_key`,建立不可变的一一映射 `subject_key <-> root_scope_id`。 -4. 支持共享 Scope 中不同用户的 Source,且一个用户的新 Source 只推进该用户 Root 的 journal。 -5. 将一条带 `subject_key` 的 Source 总共保存两份:原业务 Scope 一份、对应用户 Root 一份。 -6. 默认每天 `02:00` 后台生成画像,Cron 与时区可配置,不让业务 Source 写入入口等待 LLM。 -7. 将完整 Markdown 画像保存到现有 `pc_artifacts.content` BLOB,不增加 Claim 表或 Profile 内容列。 -8. 默认自动生效;允许按 Profile Scope 配置整篇 Revision 进入 Review。 -9. 支持人工创建、替换、审核、查看历史、比较差异和非破坏性回退。 -10. 明确全部新增表、新增接口、现有表用法和现有接口变更。 -11. 让未来 Artifact Family 可以复用 Subject Root 与 Root-local Source,但不在首期实现其他主体类型或其他制品的自动派生。 +## Goals and non-goals -## Non-goals - -首期明确不包括: - -- `team`、`agent`、`customer`、`driver` 等其他画像类型; -- 自定义画像类型、主体类型、Profile Schema 注册或任意 Claim Schema; -- 用户注册、认证、账号别名、匿名转实名、账号合并和用户 ID 生成; -- 从自然语言中猜测 Source 属于哪个用户; -- 一条 Source 同时绑定多个 `subject_key`; -- 给 `pc_sources` 或 `pc_artifacts` 增加通用 `subject_key` 列; -- 把共享业务 Scope 自动挂到用户 Root,或把 Scope Parent 当作授权关系; -- 自动复制共享 Scope 内已有的 Memory、Skill、Experience、Topic Memory 等 Artifact; -- 没有新 Source 时,因模型、Prompt 或实现版本变化自动 rebuild 画像; -- 面向所有 Source 和 Artifact Family 的通用删除、撤回和遗忘协议;但 Origin/Root 双副本的最低一致清理语义必须在本 RFC 合并前确定; -- 为 Profile 以外的 Artifact Family 实现完整的主体派生生命周期。 +- 一个 Scope 最多一个 Profile Head,固定 `family="profile"`、`artifact_id="profile"`;每个 Revision 是完整快照。 +- Profile 是派生制品,不是事实源。自动更新仅由新 Source 驱动,不增加 rebuild API。 +- 保留 `subject_key`;首期 `subject_type` 默认为且仅支持 `user`,不提供主体类型或画像 Schema 注册能力。 +- 主体 Scope 是普通 Scope。自动创建时 `parent_scope_id=NULL`;不引入特殊 Root 类型,不限制已有 Scope 的 Parent。 +- Profile 只新增一个策略表。生成和审核元数据编码在已有 BLOB 中;不增加 Subject、投影、任务、Revision Metadata 表。 +- 优先使用现有 Source、Artifact、Scope Binding、权限和 Candidate API;不增加主体专属的 Artifact CRUD 或聚合接口。 +- 不实现用户认证、主体反向一对一约束、换绑迁移、账号合并、跨 Scope 自动授权或全局 Source 删除级联。 +- 不保证所有 Artifact Family 在 Source 写入后自动生成。各 Family 保持原有启用方式、生成入口和生命周期。 # Guide-level explanation -## Terminology and invariants +## Ordinary scopes and subject bindings -| 名称 | 含义 | -| --- | --- | -| `subject_key` | 调用方直接传入的业务 `user_id`;首期只表示用户主体 | -| `root_scope_id` | PowerContext 为一个 `subject_key` 创建的普通 `pc_scopes.scope_id`,是该用户长期制品的稳定存储锚点 | -| 业务 Scope | 会话、群聊、项目或应用自己组织的 Scope;可以包含多个用户的 Source | -| Root Source | 从业务 Scope 复制到用户 Root 的同一条 Source;其内容与原 Source 完全一致 | -| Scope-local Profile | 不经过 `subject_key`,直接由普通 Scope 的 Source 生成的局部画像 | -| Profile Head | 一个 Scope 内固定 `artifact_id` 的当前画像 Revision | +`subject_key` 是调用方业务用户 ID,例如 `U1`。PowerContext 原样保存并精确匹配,不生成替代用户 ID、不归一化其内容。 +调用方负责在部署使用的主体身份范围内避免不同业务用户撞号;身份字符串不是认证凭证。 -必须满足以下不变量: - -```text -one subject_key -> exactly one root_scope_id -one root_scope_id -> at most one subject_key - -one subject-keyed Source -> one origin Source + one Root Source -one origin Source -> at most one subject_key - -one user Root -> at most one Profile Head -``` - -`subject_key` 回答“这条 Source 归入哪个用户主体的数据”,不等于: - -- 谁当前登录; -- 谁拥有底层资源; -- 正文里提到了哪些用户; -- 谁有权读取 Root; -- Source 或 Artifact 的通用唯一键。 - -调用方必须保证 `subject_key` 在同一 PowerContext 部署、同一数据库范围内唯一、稳定且不复用。PowerContext 按完整字符串进行大小写敏感、字节精确比较。调用方应使用内部用户 ID,不应使用姓名、手机号、邮箱或身份证号等直接标识信息。 - -## Scope organization - -### Group chat example: exactly four Scopes +| API 或内部约定 | Scope Binding 字段 | 示例 | +| --- | --- | --- | +| 服务端固定值 | `integration` | `subject` | +| `subject_type`,默认且仅允许 `user` | `kind` | `user` | +| `subject_key` | `external_id` | `U1` | +| 实际解析的普通 Scope | `scope_id` | `S_U1` | -群聊 G1 有 U1、U2、U3 三个用户时,共有 4 个 Scope: +`subject_scope_id` 只是主体写入请求中的可选 Scope ID,以及响应中实际使用的 Scope ID,不是新 Scope 类型或数据库列。 +现有 Scope Binding Resolve 接口增加可选 `allow_default`,缺省为 true,保持旧调用的默认 Scope 回退行为。 +主体查询必须传 false,只查一个精确 binding key,未命中返回 404;随后按返回的 `scope_id` 调用现有 Artifact 和领域 API。 +双写内部直接读取精确 binding key,始终禁止回退到默认 Scope。 ```mermaid flowchart LR - K1["subject_key = U1"] --> R1["root_scope_id = R_U1"] - K2["subject_key = U2"] --> R2["root_scope_id = R_U2"] - K3["subject_key = U3"] --> R3["root_scope_id = R_U3"] - G["business scope_id = S_GROUP
U1 + U2 + U3 group chat"] - - G -. "U1 Source copy" .-> R1 - G -. "U2 Source copy" .-> R2 - G -. "U3 Source copy" .-> R3 + K1["subject/user/U1"] --> S1["S_U1:普通 Scope"] + K2["subject/user/U2"] --> S2["S_U2:普通 Scope"] + K3["subject/user/U3"] --> S3["S_U3:普通 Scope"] + G["S_GROUP:群聊 Scope"] + S1 --> P1["Profile、Memory、其他已启用制品"] + S2 --> P2["Profile、Memory、其他已启用制品"] + S3 --> P3["Profile、Memory、其他已启用制品"] + G --> PG["群聊 Profile、Topic Memory、其他已启用制品"] ``` -| Scope | 作用 | `parent_scope_id` | -| --- | --- | --- | -| `R_U1` | U1 的 Root Source、Profile 和未来用户级制品 | `NULL` | -| `R_U2` | U2 的 Root Source、Profile 和未来用户级制品 | `NULL` | -| `R_U3` | U3 的 Root Source、Profile 和未来用户级制品 | `NULL` | -| `S_GROUP` | 保存完整群聊原始记录 | 保持业务原有父关系;不指向 `R_U1/R_U2/R_U3` | +示例共有四个 Scope;图中的绑定箭头不是 Parent 或 Context Reference。主体 Scope 不包含群聊的所有制品。 +查询 `S_U1` 只能按现有权限和查询范围获取该 Scope 的数据。需要其他 Scope 时,由应用显式组织请求;本 RFC 不增加 +跨 Family 冲突裁决或自动遍历共享群聊的逻辑。现有 PrepareContext 仍按当前 Scope 与直接 Context References 工作, +其支持的 Family 不因本 RFC 自动扩展。 -图中的虚线表示 Source 投影关系,不是 `parent_scope_id`,也不是 `pc_scope_context_references`。本 RFC 不因用户参与群聊而自动写 Scope Parent 或 Context Reference。 +## Single-scope writes and subject writes -### What a Root Scope records +原入口 `POST /v1/scopes/{scope_id}/sources` 只写当前 Scope,仍不接受 `subject_key`。主体写入使用新入口: -Root Scope 本身就是一条普通 `pc_scopes` 记录,不新增 `profile_root_scope` 表,也不把用户信息塞入 `pc_scopes.title` 或 `summary`: +```http +POST /v1/scopes/S_GROUP/subject-sources +Content-Type: application/json -```text -pc_scopes - scope_id = R_U1 - title = "Subject Root" - summary = "用户主体数据根" - parent_scope_id= NULL - version = 1 +{ + "subject_type": "user", + "subject_key": "U1", + "subject_scope_id": "S_U1", + "source_type": "content", + "content": {"speaker": "U1", "text": "我偏好简洁的中文回答"} +} ``` -`subject_key=U1` 与 `R_U1` 的映射保存在新增的 `pc_subject_roots`。真正的内容分别保存在: - -- `pc_sources`:U1 从不同业务 Scope 投影来的 Source; -- `pc_artifacts` / `pc_artifact_heads`:U1 的 Profile Revision 与 Head; -- Lineage、Cursor、Pending、Policy 和 Profile Revision 元数据表。 +业务 Scope `S_GROUP` 必须存在。主体绑定按以下规则取得或建立: -Root Scope 是存储与聚合锚点,不是用户账号记录,不承担认证,也不自动授予访问权限。 +| 已有绑定 | 可选 `subject_scope_id` | 结果 | +| --- | --- | --- | +| 存在 | 未传或与绑定一致 | 复用绑定 | +| 存在 | 与绑定不一致 | `409 subject_scope_conflict`,不写 Source | +| 不存在 | 已传 | 校验该 Scope 存在及权限,建立绑定 | +| 不存在 | 未传 | 按权限规则创建普通 Scope 并建立绑定 | -### Parent rules +每次请求生成一个 `source_id`,分别用于两个 Scope。Source 完整身份含 `scope_id`,因此相同 `source_id` 不冲突。 +新入口返回 `201` 和两条现有 `SourceRecord`,其中 `content`、`content_digest`、`source_type`、`source_id` 相同, +`scope_id` 不同,`position` 独立分配且可能恰好相同。这里的双写均为数据库记录,没有主从副本角色。 -1. 用户 Root 的 `parent_scope_id` 固定为 `NULL`。 -2. 已登记为 Root 的 Scope 不允许再通过 Scope Update 设置 Parent。 -3. 共享业务 Scope 保持自己的业务组织关系,不自动 reparent 到任何用户 Root。 -4. 业务确实拥有单用户子 Scope 时,可以由业务显式创建为某个 Root 的 descendant;该行为不是 Source Create 的副作用。 -5. 按 `subject_key` 聚合上下文时,默认选择 Root 及其真实 descendants;共享群聊 Scope 不在任一用户子树中。 +```json +{ + "subject_type": "user", + "subject_key": "U1", + "subject_scope_id": "S_U1", + "sources": [ + {"scope_id": "S_GROUP", "source_type": "content", "source_id": "src_01", + "content": {"speaker": "U1", "text": "我偏好简洁的中文回答"}, "position": 101, "content_digest": "sha256:"}, + {"scope_id": "S_U1", "source_type": "content", "source_id": "src_01", + "content": {"speaker": "U1", "text": "我偏好简洁的中文回答"}, "position": 42, "content_digest": "sha256:"} + ] +} +``` -### Source is stored exactly twice +`` 是示例占位符,真实值为 canonical JSON content 的 SHA-256。响应顺序固定为业务 Scope、主体 Scope。 +两 Scope 相同则返回 `422 distinct_scopes_required`;只需单写时使用现有接口。新接口沿用基础 Create 的重试语义: +不接受 Idempotency-Key,新的 HTTP 请求会生成新的 Source ID;一次请求内部的事务重试复用已生成的 ID。 -U1 在群聊中的一条 Source 写入后,数据库中总共存在两条内容相同的 Source: +截图式的逐条消息调用可以通过下列拟新增 Client 方法表达。Scope 的取得、绑定管理及 Policy 配置在消息写入前完成: -```text -(S_GROUP, source_type="content", source_id="source_01") # origin -(R_U1, source_type="content", source_id="source_01") # Root copy +```python +messages = [ + {"user_id": "U1", "text": "我偏好简洁的中文回答"}, + {"user_id": "U2", "text": "请先给结论,再展示详细分析"}, +] +for message in messages: + await client.create_subject_source( + "S_GROUP", + CreateSubjectSourceRequest( + subject_key=message["user_id"], + content={"speaker": message["user_id"], "text": message["text"]}, + ), + ) ``` -Source identity 包含 `scope_id`,所以两条记录可以复用同一个 `source_type + source_id`。新路径先生成部署内唯一的 Source ID,再在两个 Scope 中复用同一个 `ContentSource`;因此两条记录的 `payload` 相同,但 `journal_position` 分别由 `S_GROUP` 和 `R_U1` 的 Source journal 分配。新增关系表记录两者的精确地址和内容摘要。 +不能再对相同消息额外调用群聊 Source Create,否则群聊会重复保存。整段多人对话应由业务拆分并明确说话人; +不依赖 LLM 猜测主体路由。“同意”等消息需要业务补充所指上下文,否则画像生成应放弃推断。 -U1 的 Source 不写入 `R_U2` 或 `R_U3`;因此一次 U1 写入只会使 `S_GROUP` 与 `R_U1` 的 journal 前进。 +## Binding management semantics -例外:如果调用方直接在 `R_U1` 创建 `subject_key=U1` 的 Source,原 Scope 已经是目标 Root,只保存一条 Source,不做自我复制。 +双写接口仅负责取得或建立绑定。现有管理 API 保留换绑、解绑能力,且允许多个主体绑定同一 Scope。 +换绑和解绑不迁移、不删除任何 Source 或 Artifact。解绑后再次调用自动创建路径,可能产生新的 Scope。 +多个用户绑定同一 Scope 会汇聚数据并形成整体画像,该 Scope 不能再解释为某个用户的独占数据空间。 -用户 Root 是受保护的主体存储边界。通过公开 Source Create 直接写 Root 时必须携带与映射一致的 `subject_key`;缺少 key 或 key 不一致都被拒绝,避免无法归属的 Source 污染全局画像。 +一次请求以实际读到的绑定为准,解析后固定目标。并发管理操作不把该请求重定向到另一 Scope;响应给出实际写入目标。 +不增加绑定版本、反向唯一性检查、不可变性限制或迁移协议。相同 Source ID 也不能作为跨 Scope 全局投影索引, +本 RFC 不承诺通过一条 Source 反查所有副本或自动级联删除。 -### Multi-user Source boundary +## Profile meaning and lifecycle -每次 Source Create 最多携带一个 `subject_key`。在群聊中,接入应用应按说话人或可独立归属的消息拆分 Source: +Profile 描述本 Scope 中证据形成的稳定特征。用户 Scope 可生成用户画像;群聊 Scope 可生成参与者特点、共同偏好等 +整体画像。混合证据应写成“U1 偏好简洁回答,U2 需要详细分析”,不能混为同一个人的偏好。 -```python -await client.sources.create( - scope_id="S_GROUP", - content={"role": "user", "text": "请优先给我简洁结论"}, - subject_key="U1", -) - -await client.sources.create( - scope_id="S_GROUP", - content={"role": "user", "text": "我希望看到详细分析"}, - subject_key="U2", -) +```text +Head: (scope_id, family="profile", artifact_id="profile") +Revision: (scope_id, family="profile", artifact_id="profile", revision) ``` -一个包含多名用户发言的批量 Source 必须先拆分;PowerContext 不让 LLM 猜测整份内容该归入哪个用户。没有 `subject_key` 的 Source 只保存在当前 Scope,不进入任何用户 Root;如果该普通 Scope 已通过 `pc_profile_policies` 显式启用 Scope-local Profile,同一 Source 事务还要 upsert 当前 Scope 的 `profile-source-window` Pending,使每日 Scheduler 能发现它。 +每个 Scope 独立维护一个 Profile。相同内容进入两个 Scope 后,分别参与各自启用的生成流程;由于其他证据和旧画像不同, +输出不一定相同。更新以旧画像和新证据为输入,精确去重后合并语义重复,明确冲突以最新有效证据为准;不能丢弃仍有效的 +旧内容,也不能把一次临时指令变成长久偏好。不细分 Claim categories 或逐项风险等级。 -### Root creation and authorization +默认新建的主体 Scope 同时创建启用、自动生效的 Profile Policy。复用已有 Scope 不隐式改变其 Policy; +普通群聊 Scope 和未启用的用户 Scope 可以通过 Policy API 显式启用。其他 Family 的配置不随之改变。 -`subject_key` 永远不推导 Principal。调用 Principal 只来自认证 middleware 或可信 internal bridge;可选 -`root_contributor` 是请求明确指定的既有 `PrincipalRef`,省略时取调用 Principal,且类型只能是 `user` 或 `service`。 +默认后台每天 `02:00 Asia/Shanghai` 处理新 Source。`review_required` 时生成 Candidate,正式画像保持不变, +用户可修改候选后批准,或拒绝候选并消费本次窗口。人工 Create/Replace 保持现有显式提交语义,不受自动生成审核策略阻拦。 -Root 不存在时,自动创建必须形成完整授权闭环: +# Reference-level explanation -1. 调用 Principal 对 Origin Scope 必须拥有 `scope.contribute`。 -2. 同一个调用 Principal 还必须拥有 `server.admin`;部署也可以配置一个可信 provisioning service principal,由它在 - 内部承担 `server.admin`,但不能替代调用 Principal 对 Origin Scope 的 `scope.contribute`。 -3. 在同一协调事务中创建 `pc_scopes` Root、`pc_subject_roots` 映射、默认 `pc_profile_policies`,并通过 Access Control - RelationshipWriter 为明确的 `root_contributor` 建立 `scope.contributor` Binding。 -4. Binding 建立成功后,路由服务以内部分支完成首次 Root Source 写入、投影关系与 Pending;任一步失败都不提交 - Origin Source、Root 或单边授权关系。 +## Scope binding and atomic source transaction -若外部 Authorization Provider 的 RelationshipWriter 不能参加该协调事务,自动创建必须返回 -`503 relationship_management_unavailable`;部署应先通过可信 provisioning 流程创建 Root、映射、Policy 和 Binding, -再提交业务 Source,不能先写 Origin 后异步补权限。 +内部 `ensure_binding` 使用现有 `(integration, kind, external_id)` 唯一键,只在不存在时 INSERT,不使用覆盖式 upsert。 +并发插入冲突时回滚整个尝试,重新读取绑定并应用上表规则;不允许先提交一个无人引用的新 Scope 再重试。 +现有管理端 `set_binding/clear_binding` 保持原样,不强制复用这个 ensure 行为。 -Root 已存在时不需要 `server.admin`,但调用 Principal 对 Origin Scope 和 Root Scope 都必须拥有 -`scope.contribute`。请求中的 `root_contributor` 不得改变已有 Binding,也不能用于冒充当前调用 Principal。 +一次主体写入的事务步骤如下,所有数据库操作使用同一个连接和事务: -### Atomic write flow +1. 校验请求与业务 Scope 权限,规范化 content,生成一个 Source ID。 +2. 读取绑定;若缺失则校验候选 Scope,或创建普通 Scope,然后 INSERT 绑定。 +3. 校验实际主体 Scope 的写权限,拒绝两个 Scope 相同。自动新建 Scope 的授权见下文。 +4. 按 `scope_id` 排序取得两个 journal 的写入锁,将同一个 Source value 写入两处,各自分配 position。 +5. 提交 Scope、绑定、必要的新 Policy、两条 Source 和 journal heads;任一步失败全部回滚。 ```mermaid sequenceDiagram participant App as Application - participant API as Source API - participant PEP as Access Control - participant DB as PowerContext DB - - App->>API: Create Source(scope=S_GROUP, subject_key=U1) - API->>PEP: require scope.contribute on Origin - alt Root absent - API->>PEP: require server.admin or trusted provisioner - else Root exists - API->>PEP: require scope.contribute on Root - end - API->>DB: BEGIN - API->>DB: resolve or atomically provision U1 -> R_U1 - API->>DB: if new, bind explicit root_contributor - API->>DB: insert origin Source into S_GROUP journal - API->>DB: insert identical Source into R_U1 journal - API->>DB: insert pc_subject_source_projections relation - API->>DB: upsert Profile pending for R_U1 - API->>DB: COMMIT - API-->>App: 201 Source + committed subject projection -``` - -图中使用 HTTP Source API 展示调用,但双写不是 HTTP handler 的专有逻辑。Runtime API、Python SDK、MCP、Connector -和其他业务采集适配器只要携带 `subject_key`,都必须进入同一个 `SubjectSourceRoutingService` application service。 -该服务统一执行 Root Resolve、双 Scope 锁、Source 双写、投影关系和 Pending upsert;任何入口不得自行实现其中一部分, -也不得绕过它直接写一条带主体归属的 Origin Source。 - -首期明确扩展的业务入口请求为 `CreateSourceRequest`、`CaptureContentSourceRequest` 和 -`SubmitSourceObservationRequest`。三者共享 `subject_key/root_contributor` 路由字段和同一 application service; -Connector 最终提交 observation 时也不得绕过该服务。 - -Artifact 写入为 provenance 生成的内部 `lineage_only` 系统 Source,以及 Artifact Family 自己维护的内部 domain -Source,都不属于上述业务入口,不接受 `subject_key`,不进入主体投影服务。它们保留在目标 Scope,由对应领域服务 -直接写入。 - -双写必须满足: - -- 原 Source、Root Source、投影关系与 Root 的 Profile pending 在同一数据库事务提交;任一步失败则整体回滚; -- 同时锁定两个 Source journal 时,按 `scope_id` 排序加锁,避免并发死锁; -- 同一 Source 内部重试复用相同 `source_type + source_id`,相同 payload 视为幂等成功,不同 payload 返回冲突;Source ID 必须在生成时保证部署内唯一; -- `subject_key` 与 Root 的一一映射由数据库唯一约束和事务共同保证; -- Source 是不可变事实记录,写错 `subject_key` 后不能原地改归属,只能追加纠正 Source,并由后续画像 Revision 修正。 - -## Profile Artifact - -### Identity and singleton - -Subject-keyed user Profile 固定为: - -```text -(root_scope_id, family="profile", artifact_id="profile:user") + participant API as Subject Source API + participant DB as Existing tables + Policy + App->>API: business scope + subject_key + optional subject_scope_id + content + API->>DB: Begin transaction; read/ensure binding + API->>DB: Authorize actual scopes; lock journals in scope order + API->>DB: Insert (S_GROUP, content, src_01) + API->>DB: Insert (S_U1, content, src_01) + API->>DB: Commit both Sources and journal heads + API-->>App: 201, actual scope IDs and two SourceRecords + Note over API,DB: No LLM invocation on the Source write path ``` -同一个 Root 首次写入使用 Profile 专用 Create;已有 `profile:user` 时再次 Create 返回 `409 Conflict`,后续只能使用 -Profile 专用 Replace。 -HTTP Replace 必须原样回传当前 Head 的不透明 `ETag` 作为 `If-Match`;内部 Profile RecordService 使用同一 Head CAS,不能另设 -一套以请求体 Revision 代替 HTTP 条件写的并发契约。 +绑定的事务重试不等于 API 幂等。对于同 ID、不同 payload 的冲突,现有 Source repository 仍拒绝覆盖。 +首期主体双写仅面向基础 API 支持的 `content` Source。现有 capture、observation、Connector、MCP 单写入口不隐式双写; +需要双写的接入通过新 application service/Client 方法调用。内部 `lineage_only` Source 不调用主体双写入口。 -不带 `subject_key` 的普通 Scope 可以显式启用 Scope-local Profile: +## Authorization and confidentiality -```text -(scope_id, family="profile", artifact_id="profile:local") -``` +复用现有权限动作:业务和主体 Scope 分别要求 `scope.contribute`;读取按 `scope.read/artifact.read`; +已有绑定不存在时,建立绑定还要求现有 Binding 管理入口的 `server.admin`。若需要自动新建 Scope,则还遵守现有 +Scope Create 的 `server.admin`,并在同一事务中用现有 RelationshipWriter 为已认证调用 Principal 建立该新 Scope 的 +`scope.contributor` 角色绑定。此初始化只适用于新建 Scope;`server.admin` 本身不能被视为任意已有 Scope 的写权限。 +这一授权初始化是新便利入口的行为,现有 Scope Create 接口不改变。未启用授权的部署沿用现有部署模式。 +当前权限 repository 自行开启事务,实施时需增加可接受外部连接的内部写入路径,使新 Scope 的授权、审计和关系版本 +与主体写入共用事务;不能调用一个提前独立提交权限的公开管理 API。公开权限接口的语义不变。 -共享或多人 Scope 默认不启用 Scope-local Profile,避免把 U1、U2、U3 混成同一画像。 +主体 key 不推导 Principal,不代替权限检查。Policy 更新要求 `scope.admin`;Flush 要求 `scope.contribute`; +Candidate 操作使用既有 Review 权限。后台使用可信 Runtime 服务身份,只处理部署允许的 Scope。 -### Profile content +需要在现有 Artifact Access Profile 注册 `profile`:enabled=true,share_unit=artifact,shareable_states={committed}, +base_action=artifact.read,grantable_roles={artifact.viewer},selector=forbidden,mutation_semantics={artifact.write}。 +Candidate 不作为已提交 Artifact 暴露。日志默认不输出原始 subject_key、Source 正文或画像正文。 -Profile Revision 是一份完整 Markdown 当前快照。首期不定义 Claim category、Claim 主键、结构化 Claim 列表或逐 Claim 风险等级。 +## Profile content and server-owned metadata -为保持现有 Artifact Repository 的“family content 是 Pydantic Model”约束,Profile 使用只有一个正文载荷的模型: +Markdown 正文放在 `ProfileContent.content`;生成元数据与正文一起编码到 `pc_artifacts.content` BLOB。 +沿用当前 codec 的 Pydantic JSON UTF-8 bytes,不把该 codec 描述为 RFC 8785。公开 `content_digest` 仍遵循基础 API +的 canonical JSON 规则。LLM 只生成正文,服务端填写 generation;不让模型或客户端伪造审核状态、时间或 Source 窗口。 ```python from typing import Annotated, Literal +from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator -from pydantic import BaseModel, ConfigDict, Field, field_validator - -class ProfileContent(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) +Identifier = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] - schema: Literal["powercontext.profile.v1"] = "powercontext.profile.v1" - media_type: Literal["text/markdown"] = "text/markdown" - content: Annotated[str, Field(min_length=1)] - - @field_validator("content") - @classmethod - def validate_markdown(cls, value: str) -> str: - normalized = normalize_profile_markdown(value) - if len(normalized.encode("utf-8")) > 262_144: - raise ValueError("profile Markdown exceeds 256 KiB") - return normalized -``` - -逻辑内容示例: - -```json -{ - "schema": "powercontext.profile.v1", - "media_type": "text/markdown", - "content": "# 用户画像\n\n用户偏好中文简洁回答。国内酒店通常选择大床房,常见预算约为 500~700 元。\n" -} -``` - -其中 `content` 完全由 LLM 生成或由授权用户编辑,格式为 Markdown: - -```markdown -# 用户画像 - -用户偏好中文简洁回答。国内酒店通常选择大床房,常见预算约为 500~700 元。 -``` +class SourceWindow(BaseModel): + after: int = Field(ge=0) + through: int = Field(ge=0) -规范化规则固定为 UTF-8、Unicode NFC、LF 换行、无 BOM、文件末尾一个换行。服务端校验非空、大小和 Markdown 文档边界;不把标题层级解释成数据库分类。 - -### Physical BLOB encoding - -现有 `pc_artifacts.content` 已是 `BLOB`,OceanBase/MySQL 变体为 `MEDIUMBLOB`,因此表结构无需变化。首期沿用当前 Artifact codec:将 `ProfileContent` 序列化为 Pydantic JSON UTF-8 bytes 写入 BLOB。也就是说,BLOB 中是包含 Markdown 字符串的模型字节,不是新的 Claim 列,也不是绕过 Artifact Repository 写入裸文本。 - -```text -pc_artifacts.content - = UTF8_BYTES('{"schema":"powercontext.profile.v1",' - '"media_type":"text/markdown",' - '"content":"# 用户画像\\n...\\n"}') -``` - -Profile 专用 API 将其解码并以字符串返回;通用 Artifact API 仍返回 `content` object,所以不需要改变现有 `ArtifactRevision.content: object` 的响应形状。 - -### Revision lineage and generation metadata - -每次自动生成、人工创建、人工替换、审核通过和回退都创建新的不可变 Revision: - -- 自动生成或审核通过的 Revision 在 `pc_artifact_lineage_sources` 中引用本次实际消费的 Root-local 业务 Source, - 不引用被窗口过滤掉的 `lineage_only` Source; -- 人工 Create、Replace 和 Rollback 由 Profile 专用 API 解析固定 identity,再调用内部 Artifact RecordService; - RecordService 保留 [RFC 1437](1437_source_artifact_rest_api.md) 的 provenance 语义,为该次写入命令生成 - `lineage_only` 系统 Source,并将它放在新 Revision 直接 Source lineage 的 ordinal 0; -- `pc_artifact_lineage_artifacts` 在更新时引用上一版 Profile 的精确 Revision; -- `pc_profile_revision_metadata` 保存生成方式、Source Window、生成器版本和回退来源; -- 不在 Markdown 中混入运行时游标或内部任务状态。 + @model_validator(mode="after") + def ordered(self): + if self.through < self.after: + raise ValueError("through must be >= after") + return self -人工写入生成的系统 Source 仍是可审计 provenance,但 Profile Processor 必须过滤它,不能让一次画像修改再次成为 -下一次画像生成的证据。 +class ProfileGeneration(BaseModel): + mode: Literal["automatic", "manual_create", "manual_replace", "review_approved", "rollback"] + created_at: str # Server-generated UTC RFC 3339 timestamp. + generator_id: str | None = None + generator_version: str | None = None + source_window: SourceWindow | None = None + restored_from_revision: int | None = Field(default=None, ge=1) -### Update rules +class ProfileWriteContent(BaseModel): + model_config = ConfigDict(extra="forbid") + content: str = Field(min_length=1) + restored_from_revision: int | None = Field(default=None, ge=1) -自动更新的模型输入是: +class ProfileContent(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_: Literal["powercontext.profile.v1"] = Field(default="powercontext.profile.v1", alias="schema") + media_type: Literal["text/markdown"] = "text/markdown" + content: str + generation: ProfileGeneration -```text -current Profile Markdown -+ Root Source window (cursor, source_through] --> full next Profile Markdown | NOOP +class ProfileCandidateProposal(BaseModel): + schema_: Literal["powercontext.profile-candidate.v1"] = Field(default="powercontext.profile-candidate.v1", alias="schema") + content: str + source_window: SourceWindow + generator_id: str + generator_version: str + created_at: str ``` -合并规则: - -1. 只有 Root Source journal 中出现尚未消费的业务 Source 才允许自动调用 LLM;模型、Prompt、代码版本变化以及只有 - `lineage_only` Source 到达都不触发 rebuild。 -2. Worker 先过滤所有 `lineage_only` Source,再按精确 Source address 与 content digest 去重。窗口只有过滤项时不调用 - LLM、不创建 Revision,但仍以 CAS 推进 Cursor,避免永久重复扫描。 -3. LLM 读取当前完整 Markdown 和新 Source,只保留稳定、跨会话有价值的用户信息。 -4. 完全重复的内容合并;新且明确的用户表达覆盖冲突的旧表述;证据不足时保留原表述,不做敏感推断。 -5. `pc_profile_revision_metadata.generation_mode` 只描述整篇 Revision 如何成为 Head。冲突处理可以把 - `manual_create`、`manual_replace`、`review_approved` 的当前 Head 作为一个整体排在 `automatic` Head 之前,但不能 - 把这种优先级继承到某个段落,也不能声称一篇包含旧自动内容的人工 Revision 已逐段获得人工确认。新 Source 明确 - 记录用户纠正时,下一版仍按完整文档重新生成或人工编辑。 -6. LLM 必须返回完整 Markdown 或 `NOOP`,不能直接操作数据库字段。 -7. 服务端规范化并计算 digest;与当前 Head 相同则不创建空 Revision,只推进 Cursor。 -8. 校验失败、模型失败或 CAS 冲突不推进 Cursor;CAS 冲突时重读 Head 后重新合并。 +上述模型展示核心类型;提交验证还包括:正文非空白、统一 NFC/LF、去除 BOM、末尾一个换行,正文 UTF-8 最大 256 KiB; +时间必须可解析且归一为 UTC;automatic/review_approved 必须有有效窗口与生成器信息;人工操作不伪造窗口; +仅 rollback 有 restored_from_revision,且目标是同一个 Scope/Family/Artifact 的已有 Revision。 +Candidate 的窗口及生成器字段是服务端只读字段,Revise 请求使用单独的正文输入 schema,不复用可任意写的持久化模型。 -移除 Claim 结构后的取舍是:首期只提供 Revision 级 lineage,不提供 Claim 级查询、Claim 级风险判断或 Claim 级引用。需要这些能力时,应通过后续可重建索引实现,而不是重新把 Claim 分类写入事实表。 +只有正文参与生成结果的 no-change 比较,不能因时间或生成器字段不同而创建空更新 Revision。 +基础人工 Replace 仍保持每次成功创建 Revision 的既有语义。人工确认优先仅是整篇 Revision 的生成参考, +不声称能识别某段文字曾被人工确认;后续明确的新 Source 仍可更新相应内容。 -## Background automatic generation +## Daily scheduling and source consumption -### Schedule configuration +复用现有 APScheduler sidecar 表,增加 Cron job;不引入 durable pending、lease 或 job 业务表。 +任务分页扫描 `pc_profile_policies` 中启用的 Scope,比较 `pc_source_journal_heads.position` 与该 Scope +在 `pc_source_cursors` 的 `profile-source-window` Cursor。缺失 Cursor 视为 sequence=0。 -默认每天部署时区的 `02:00` 发起一个 Profile 自动处理波次: - -```python -from typing import Annotated -from zoneinfo import ZoneInfo - -from pydantic import BaseModel, Field - -class ProfileGenerationSchedule(BaseModel): - enabled: bool = True - cron: str = "0 2 * * *" - timezone: str = "Asia/Shanghai" - source_window_limit: Annotated[int, Field(ge=1, le=1000)] = 200 - max_concurrency: Annotated[int, Field(ge=1, le=128)] = 8 - worker_timeout_seconds: Annotated[int, Field(ge=30, le=3600)] = 900 - retry_max_delay_seconds: Annotated[int, Field(ge=30, le=86_400)] = 1800 - - def tzinfo(self) -> ZoneInfo: - return ZoneInfo(self.timezone) +```yaml +profile: + schedule: + cron: "0 2 * * *" + timezone: "Asia/Shanghai" + misfire_grace_seconds: 86400 + max_concurrency: 4 + max_sources_per_window: 32 ``` -`02:00` 是默认低峰时间点。部署可以修改 Cron 和 IANA timezone;大规模部署可以配置调度抖动,但默认不抖动。实现必须使用带时区的 CronTrigger,不能用“每 86,400 秒”的 IntervalTrigger,否则服务重启和夏令时会造成时间漂移。 - -### Scheduled call flow +Cron 和 IANA timezone 可配置,无效值启动失败。调度启用 coalesce 和单进程 max_instances=1;启动时执行一次补偿扫描, +使长期停机或超出 misfire 宽限期后仍能发现未消费 Source。任务每次按固定高水位和有界窗口处理; +同一 Scope 顺序处理窗口,不同 Scope 可并行。一个 Scope 每轮最多处理 100 个窗口,达到上限后留给下一次扫描或 Flush。 +窗口大小最多 32 条 journal 记录,同时保证 Candidate 的 Source 与 Artifact evidence 总计不超过现有 32 条限制; +若旧 Profile 作为 Artifact evidence,则窗口最多 31 条。不得把额外使用的证据悄悄省略出 lineage。 ```mermaid sequenceDiagram - participant Cron as Profile Cron Scheduler - participant Sup as Artifact Processing Supervisor - participant DB as Metadata + Artifact DB - participant Worker as Profile Worker - participant LLM as LLM - - Cron->>Sup: daily wave at 02:00 - Sup->>DB: acquire/renew global lease - Sup->>DB: page pending(binding=profile-source-window) - DB-->>Sup: dirty Profile scopes and source_through - Sup->>Worker: assign(scope, after, through, generation) - Worker->>DB: read Cursor + current Profile + fixed Source window - Worker->>LLM: current Markdown + new Sources - LLM-->>Worker: complete Markdown or NOOP - Worker->>Worker: normalize, validate, digest - alt automatic and changed - Worker->>DB: CAS Create/Replace Revision + metadata + Cursor - else review_required and changed - Worker->>DB: create full-Markdown Candidate; wait for decision - else NOOP - Worker->>DB: CAS advance Cursor only + participant Cron as 02:00 Scheduler / Manual Flush + participant Worker as Profile Processor + participant DB as Policy + Journal + Cursor + Artifact/Candidate + participant LLM as Model + Cron->>Worker: Scan enabled scopes + Worker->>DB: Read policy version, pending pointer, cursor and profile head + alt Candidate pending or no new journal entries + Worker-->>Cron: review_pending / noop + else New source window + Worker->>DB: Read bounded (after, through] window + Worker->>Worker: Filter lineage_only; normalize and deduplicate evidence + Worker->>LLM: Old profile + eligible evidence, if any + LLM-->>Worker: Complete Markdown + Worker->>DB: Begin transaction; lock Policy; recheck version, cursor, head + alt Automatic activation + Worker->>DB: Commit revision + lineage + cursor atomically + else Review required + Worker->>DB: Commit candidate + pending pointer; cursor unchanged + end + Worker-->>Cron: updated / review_pending end - Worker-->>Sup: success / review_pending / failure ``` -详细流程: - -1. 统一的 `SubjectSourceRoutingService` 已在业务 Source 写入事务中将 Root journal 高水位 upsert 到 - `pc_artifact_processing_pending`,但不立即调用 LLM。普通 Scope 显式启用 Scope-local Profile 时,其自身 journal - 高水位也会登记为独立 target;共享 Scope 默认不启用。 -2. 每天 `02:00`,持有 Supervisor lease 的实例启动本日波次;持久化 scheduler 使用 `coalesce=true`,错过执行时间后恢复时补执行一次。 -3. Supervisor 分页读取 `binding_name="profile-source-window"` 的 dirty targets,并按 `max_concurrency` 公平调度。 -4. Worker 冻结本轮 `source_through`,读取 `pc_source_cursors` 的 `after`,按默认最多 200 条 Source 的 Window 分批 - 读取,并在调用模型前排除 `lineage_only`。新 Source 在推理期间到达时位置大于 `through`,留给下一波。 -5. `after >= through` 或固定 Window 过滤后为空时跳过 LLM;后者仍推进 Cursor。达到 Pending 高水位后清理 Pending。 -6. Worker 在事务外读取当前 Profile、固定 Source Window 并调用 LLM,避免长事务占锁。 -7. Worker 校验完整 Markdown。自动生效时,用 Head CAS、Cursor CAS 和 Supervisor fencing 在一个短事务中提交 Revision、Lineage、Revision Metadata 和 Cursor。 -8. 无语义变化时不创建 Revision,只 CAS 推进 Cursor。 -9. `review_required` 时,在一个事务中创建完整 Profile Candidate、持久化其 Source Window,并占用 Policy 的单一 - `pending_candidate_id`;有未决 Candidate 时,定时与 Manual Generate 都不重复生成。批准后创建 Revision 并推进到 - Candidate 的 `source_through`。拒绝必须显式选择 `reject_and_consume` 或 `reject_and_retry`:前者推进 Cursor,避免 - 次日重复提出同一内容;后者不推进 Cursor 并保留 Pending,使同一窗口可以在后续波次重新生成。 -10. 单个用户处理失败不阻塞其他用户;失败不推进 Cursor,不删除 Pending,并按指数退避重试,最大间隔默认 30 分钟。 - -### Why a durable dirty set instead of a Job history table +纯 `lineage_only` 窗口不调用 LLM、不创建制品,按完整 through 推进 Cursor。有效证据未改变正文也只推进 Cursor。 +自动生成只依赖本 Scope 的 Source;复制到 S_U1 的 Source 不推进 S_U2 的 Cursor。 +读取旧画像只是合并上下文,不把其全部历史 Source 反复作为待处理新证据。 -Profile 复用 Topic Memory RFC 定义的通用 `pc_artifact_processing_pending`、`pc_artifact_processing_leases` 和 `pc_source_cursors`。Pending 表达“哪个 `(binding_name, scope_id)` 仍有未消费 Source”,不是无限增长的任务历史。 +LLM 运行期间不持有数据库事务锁。提交时锁定 Policy 并比较快照中的 version、pending pointer、Cursor generation +及 Head;任一改变则丢弃当前计算,不推进 Cursor。SQLite 使用写事务序列化,OceanBase 使用行锁及 CAS。 +所有成功的画像处理和 Policy 指针变动增加 Policy version;基础 Profile Create/Replace 也取得同一 Policy 锁, +确保与后台/审核操作串行提交。首次人工创建 Policy 时也必须用主键和事务处理竞争。 -首期不增加 `pc_profile_generation_jobs`。处理状态由 Pending、Cursor、当前 journal head 和最近 Profile Revision Metadata 组合得到;运行日志和指标用于观测每次尝试。若 Topic Memory 的通用处理表在 Profile 实现前尚未落地,则它们作为本 RFC 的新增通用表一并实现,而不能被描述成已有表。 +多进程可能重复调用 LLM,但只能有一个结果提交;不宣称 APScheduler 的单进程选项具有分布式锁效果。 +模型超时、格式错误和事务失败保留原 Cursor,记录不含正文的错误日志,下一次计划扫描或手动 Flush 重试。 +Source、Cursor 是恢复依据,不要求持久任务记录。模型或 Prompt 变更本身不触发重算。 -### Manual generation +## Review, manual editing and rollback -`POST /v1/profile/generate` 不同步等待 LLM。它读取当前 Source journal head、递增 Pending 的 `flush_generation` 并唤醒 -Supervisor。该 operation 只有一个成功 HTTP 状态 `200 OK`,body 的 `status` 为 `accepted`、`idle` 或 -`review_pending`;无新 Source 时返回 `idle`,已有未决 Candidate 时返回 `review_pending`,两种情况都不会 rebuild -当前 Profile。 +自动 Candidate 和 `pending_candidate_id` 同事务写入;每个 Scope 最多一个未决自动 Profile Candidate。 +存在未决候选时仍可写入 Source,但后台与手动 Flush 均不再生成新候选。修改 Policy 不自动批准或丢弃已有候选。 -## Review, edit and rollback - -Claim category 和风险等级移除后,审核粒度是整篇 Markdown Revision: - -```python -from typing import Literal - -from pydantic import BaseModel, ConfigDict - -class ProfilePolicy(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - generation_enabled: bool = True - activation_mode: Literal["automatic", "review_required"] = "automatic" - version: int -``` +| 操作 | 原子更新 | Cursor | +| --- | --- | --- | +| 生成 Candidate | Candidate versions/heads、Policy 指针与 version | 不变 | +| Revise Candidate | 新 Candidate version;只修改正文,保留窗口/target/evidence | 不变 | +| Approve | 新 Artifact/Head/lineage、Candidate approved/result、Policy 清指针、Cursor | 推进到该候选 through | +| Reject | Candidate rejected/reason、Policy 清指针、Cursor | 推进到该候选 through | -- `automatic`:默认值,合法的新 Markdown 直接 Create/Replace 并成为 Head; -- `review_required`:生成结果写入现有 Artifact Candidate 表,批准后才成为新 Revision; -- 政策由服务端配置或授权用户通过 Policy API 按目标 Scope 修改,不由 LLM 判断; -- 不再存在“某一 Claim 风险等级自动、另一等级 Review”的配置,因为首期没有 Claim 级结构。 +复用现有 Candidate get/list/revise/approve/reject。请求继续带 `scope_id`、`candidate_id`、`expected_version`, +Reject 继续要求 reason,不增加 disposition。Profile 分支校验 Policy 指针、待审状态、Cursor.sequence=after。 +Approve 还校验当前 Head 等于 Candidate target;首次创建 target=NULL 时固定 Profile Head 必须不存在。 -拒绝自动 Candidate 时,审核请求必须显式提交 `disposition`: +人工 Replace 在等待审核期间允许执行。旧候选 Approve 返回 `409` 并保留候选;Reject 无需匹配当前 Head,仍可消费原窗口。 +用户可在 Reject 前读取候选并人工应用需要的内容。Revise 不自动重定向 target,避免未经确认地覆盖新的画像。 +Approve/Reject 失败不部分推进 Cursor;终态重复请求遵循既有 Candidate 冲突语义,客户端通过 Get 确认结果。 -- `reject_and_consume`:记录拒绝、推进 Cursor 到 Candidate 的 `source_through`、更新 Pending 并清空 Policy 指针; -- `reject_and_retry`:记录拒绝、保持 Cursor 不变、保留或重新 upsert Pending,并清空 Policy 指针。 +拒绝仅消费本次窗口,不删除 Source。候选正文不进入有效画像,也不成为下一次生成的旧画像输入。后续新证据仍可表达同一事实; +拒绝不是永久的事实屏蔽机制。若 journal 在审核期间从 42 增长到 50,决定后下一次处理窗口从 42 开始。 +重启后根据持久化的 Policy 指针与 Candidate 恢复等待状态,不重新生成。 -人工修改必须提交完整 Markdown、原因和当前 Head 的 `If-Match`,并创建新 Revision。回退不是把 Head 指针倒拨,而是 -读取目标旧 Revision 的 Markdown,将其复制为当前 Head 的下一个 Revision;Revision Metadata 记录 -`restored_from_revision`,HTTP 请求同样使用 `If-Match` 保护当前 Head。 +人工 Create/Replace 使用基础 Artifact API 的 Family writer,保留系统 `lineage_only` Source、ordinal=0、ETag/If-Match +及现有 lineage 规则。Create 固定 artifact_id=profile,已有 Head 返回 409。自动提交使用同一 Family 校验与 repository, +但引用真实 evidence Source,不伪造人工系统 Source。 -Candidate、人工修改和回退都使用 Artifact Head CAS。审核期间 Head 已发生变化时,批准返回冲突并要求重新生成或重新修订 Candidate,不能把基于旧 Head 的内容静默覆盖到新 Head。 +回退无需新 API:先 GET 历史 Revision,再 GET 当前 Head 的 ETag,PUT 完整正文并可在 ProfileWriteContent 中带 +`restored_from_revision`。服务端校验历史 Revision 存在且规范化正文相同,写入新的 rollback Revision;不移动 Head 回旧版本, +不回退 Cursor。未提供该可选字段时视为普通人工 Replace。Create 不允许指定 restored_from_revision。 +历史比较由客户端读取两个 Revision 完成,不新增 diff/history-list 接口。 -## Subject context aggregation +## Persistence inventory and example rows -`subject_key` 不只用于找到 Profile,也定义一个可供不同 Artifact Family 复用的稳定查询入口: +下面示例中的 BLOB 展示解码后的 JSON,外键和 lineage 使用实际完整身份。时间、摘要使用可读示例值;省略的默认列 +在实现中仍按现有表定义写入。现有表均无 DDL 变动,只扩展 Profile 对应的类型化 BLOB schema 和代码分支。 ```mermaid -flowchart LR - K["subject_key"] --> Resolve["resolve root_scope_id"] - Resolve --> Select["root + true descendants"] - Select --> Auth["authorize every Scope and Artifact"] - Auth --> Profile["exact Profile Head"] - Auth --> Recall["family-specific recall"] - Recall --> Dedup["exact + semantic dedup"] - Profile --> Compose["conflict-aware composition"] - Dedup --> Compose - Compose --> Budget["rank + family quota + max_bytes"] +erDiagram + PC_SCOPES ||--o{ PC_SCOPE_BINDINGS : scope_id + PC_SCOPES ||--o| PC_PROFILE_POLICIES : scope_id + PC_SCOPES ||--o{ PC_SOURCES : "logical scope membership" + PC_SCOPES ||--o{ PC_SOURCE_CURSORS : "logical scope membership" + PC_ARTIFACTS ||--o| PC_ARTIFACT_HEADS : current_revision + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : revision + PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : local_evidence + PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_ARTIFACTS : revision + PC_ARTIFACT_CANDIDATE_VERSIONS ||--o| PC_ARTIFACT_CANDIDATE_HEADS : current_version + PC_ARTIFACT_CANDIDATE_HEADS o|--o| PC_PROFILE_POLICIES : pending_candidate ``` -范围选择遵循以下规则: - -1. 服务端先通过 `pc_subject_roots` 得到唯一 `root_scope_id`。 -2. 候选范围是 Root 与其真实 descendants;Parent 只用于组织,仍需逐 Scope、逐 Artifact 授权。 -3. 共享群聊 Scope 不属于任何用户 Root 子树,不能因用户参与群聊而被隐式加入。 -4. Profile 使用固定地址精确读取,不参与普通向量召回;Memory、Topic Memory、Skill、Experience 等使用各自 family 的召回器。 -5. 相同 `(scope_id, family, artifact_id, revision)` 只保留一次;同一 Head 与其精确 Revision 不重复注入。跨 Scope - 返回值必须使用包含 `scope_id` 的 `ArtifactAddress`,不能只返回同 Scope 才完整的 `ArtifactRef`。 -6. family 内部先按稳定身份和内容摘要去重,再做语义去重;不同 family 的程序性知识不能只因文本相似就合并。 -7. Markdown Profile 与其他制品表达冲突时,只能按当前 Head 的整篇 `generation_mode`、时间和直接证据排序;不得把 - Revision 级人工模式解释成段落级信任。仍无法判断时同时返回冲突摘要与双方精确 `ArtifactAddress`,不修改任何源 - Artifact。 -8. 最终结果使用 family quota 和请求的 `max_bytes` 限制;服务端按 UTF-8 实际字节数计量,被截断的内容保留可继续 - 读取的完整地址。 - -Memory Entry 等 family-owned subresource 也必须返回包含 `scope_id` 的完整地址;主体聚合结果中不得出现依赖隐含当前 -Scope 才能解引用的裸 `ArtifactRef`、Entry ref 或其他 subresource ref。 - -现有 Prepare Context 只处理调用方显式 Scope 范围,不会自动遍历 Subject Root。本 RFC 的 Subject Context API 负责服务端解析范围,再复用各 family 的既有召回能力。 - -首期自动生成的用户级制品只有 Profile。未来其他 Artifact Family 若复用本设计,应从 Root-local Source journal 消费证据,并把产物写到 Root 或其真实子 Scope;共享 Scope 中已经存在的 Artifact 不会仅因 Source 被复制而自动跨 Scope 生效。 +图中的 logical membership 不是新增外键;`pc_sources` 和 `pc_source_cursors` 保持现有约束。 +跨 Scope 的两条 Source 没有新增关系表或 FK。`pc_artifact_lineage_artifacts` 仍保存同 Scope 的上游 Revision。 -# Reference-level explanation - -## Database metadata design - -### Relationship diagram +### Scopes and bindings -```mermaid -erDiagram - PC_SCOPES ||--o| PC_SUBJECT_ROOTS : "root_scope_id" - PC_SCOPES ||--o{ PC_SOURCES : owns - PC_SUBJECT_ROOTS ||--o{ PC_SUBJECT_SOURCE_PROJECTIONS : routes - PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "origin Source" - PC_SOURCES ||--o| PC_SUBJECT_SOURCE_PROJECTIONS : "Root Source" - PC_SCOPES ||--o{ PC_ARTIFACTS : owns - PC_ARTIFACTS ||--o| PC_PROFILE_REVISION_METADATA : "Profile subset" - PC_ARTIFACTS ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : cites - PC_SOURCES ||--o{ PC_ARTIFACT_LINEAGE_SOURCES : evidence - PC_SCOPES ||--o| PC_PROFILE_POLICIES : configures - PC_ARTIFACT_CANDIDATE_HEADS ||--o| PC_PROFILE_CANDIDATE_METADATA : tracks_window - PC_SCOPES ||--o{ PC_SOURCE_CURSORS : consumes - PC_SCOPES ||--o{ PC_ARTIFACT_PROCESSING_PENDING : marks_dirty -``` +`pc_scopes` 保存普通 Scope。以下是同一群聊的四条示例,均无 Parent,但群聊可保留其原有组织关系: -`pc_artifact_processing_leases` 通过 Supervisor 的 `holder_id + supervisor_generation` 在运行时 fencing Worker 提交;它与 Pending 没有数据库外键,因而不在 ER 实线关系中。 +| scope_id | title | summary | parent_scope_id | version | +| --- | --- | --- | --- | --- | +| S_GROUP | Discussion | Group conversation evidence | NULL | 1 | +| S_U1 | User workspace | Long-lived conversation evidence | NULL | 1 | +| S_U2 | User workspace | Long-lived conversation evidence | NULL | 1 | +| S_U3 | User workspace | Long-lived conversation evidence | NULL | 1 | -### New table: `pc_subject_roots` +`pc_scope_bindings`:主键仍为 `(integration, kind, external_id)`;不增加 scope_id 唯一约束。 -Artifact Family 无关的主体到 Root Scope 映射: - -| 字段 | 类型 | 约束 | 含义 | +| integration | kind | external_id | scope_id | | --- | --- | --- | --- | -| `subject_key` | `VARCHAR(256)` binary collation | PK | 调用方业务 `user_id`,精确匹配 | -| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, UNIQUE, FK -> `pc_scopes.scope_id` | PowerContext 生成的用户 Root | -| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | 映射创建时间 | +| subject | user | U1 | S_U1 | +| subject | user | U2 | S_U2 | +| subject | user | U3 | S_U3 | -额外定义 `UNIQUE(subject_key, root_scope_id)`,供投影表建立复合外键。映射一经创建不可重绑;账号合并与迁移另行设计。 +`pc_scope_context_references`、`pc_scope_external_references`、`pc_scope_settings` 在本例均无新增行。 +内部自动 Scope 创建不假装使用公开 Scope Create 的 Idempotency-Key,因此 `pc_scope_creation_requests` 无本次请求行; +若应用事先调用现有 Scope Create,则其记录沿用原流程。 -### New table: `pc_subject_source_projections` +### Sources, journal heads and cursors -记录业务 Scope Source 与 Root Source 的精确一一投影: +`pc_sources` 仍以 `(scope_id, source_type, source_id)` 为主键。P 表示同一个合法的完整 ContentSource payload; +两条复用相同 name/src_01,因此内部 envelope 也可相同。Source ID 不是全局唯一键。 -| 字段 | 类型 | 约束 | -| --- | --- | --- | -| `origin_scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_sources.scope_id` | -| `origin_source_type` | `VARCHAR(128)` binary collation | PK part, FK part | -| `origin_source_id` | `VARCHAR(256)` binary collation | PK part, FK part | -| `subject_key` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | -| `root_scope_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_subject_roots` | -| `projected_source_type` | `VARCHAR(128)` binary collation | NOT NULL, FK part -> `pc_sources` | -| `projected_source_id` | `VARCHAR(256)` binary collation | NOT NULL, FK part -> `pc_sources` | -| `content_digest` | `VARCHAR(71)` binary collation | NOT NULL, `sha256:` | -| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | - -约束: +| scope_id | source_type | source_id | payload | journal_position | +| --- | --- | --- | --- | --- | +| S_GROUP | content | src_01 | P | 101 | +| S_U1 | content | src_01 | P | 42 | -```text -PRIMARY KEY (origin_scope_id, origin_source_type, origin_source_id) -UNIQUE (root_scope_id, projected_source_type, projected_source_id) -FOREIGN KEY (origin_scope_id, origin_source_type, origin_source_id) - REFERENCES pc_sources(scope_id, source_type, source_id) -FOREIGN KEY (root_scope_id, projected_source_type, projected_source_id) - REFERENCES pc_sources(scope_id, source_type, source_id) -FOREIGN KEY (subject_key, root_scope_id) - REFERENCES pc_subject_roots(subject_key, root_scope_id) -CHECK (origin_scope_id <> root_scope_id) -``` +P 的业务 content 为 `{"speaker":"U1","text":"我偏好简洁的中文回答"}`,按现有 adapter 编码;不增加主体内部字段。 -首期 `projected_source_type/id` 与原 Source 相同;单独保留字段是为了让关系两端地址完整,并允许未来定义不同的内部 Source adapter。 +`pc_source_journal_heads`: -### New table: `pc_profile_policies` +| scope_id | position | +| --- | --- | +| S_GROUP | 101 | +| S_U1 | 42 | -同时支持 Subject Root Profile 和显式启用的 Scope-local Profile: +`pc_source_cursors`,本例为 Source 写入之后、生成之前: -| 字段 | 类型 | 约束 | 默认值 | +| scope_id | binding_name | cursor BLOB | generation | | --- | --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK, FK -> `pc_scopes.scope_id` | - | -| `generation_enabled` | `BOOLEAN` | NOT NULL | `TRUE` for Subject Root | -| `activation_mode` | `VARCHAR(32)` binary collation | CHECK `automatic/review_required` | `automatic` | -| `pending_candidate_id` | `VARCHAR(128)` binary collation | nullable, FK part -> `pc_artifact_candidate_heads` | `NULL` | -| `version` | `BIGINT` | NOT NULL, CHECK > 0 | `1` | -| `updated_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | current time | - -创建 Subject Root 时同时创建默认 Policy。普通 Scope 没有 Policy 表示未启用 Scope-local Profile;调用方显式配置后才加入每日扫描。 +| S_GROUP | profile-source-window | {"sequence":100} | 8 | +| S_U1 | profile-source-window | {"sequence":41} | 5 | -`pending_candidate_id` 与同一行的 `scope_id` 组成外键,指向 `pc_artifact_candidate_heads(scope_id, candidate_id)`。Worker 只能在该字段为 `NULL` 时创建自动 Profile Candidate,并在同一事务中设置它;Approve/Reject 在完成 Cursor/Pending 处理后清空它。这个单值指针保证每个 Profile Scope 同时最多一个未决自动 Candidate,包括 Manual Generate 并发路径。 +两 Scope 分别成功处理后,sequence 变为 101/42,generation 分别变为 9/6。Memory 等其他 binding 的 Cursor 不变。 -### New table: `pc_profile_revision_metadata` +### The only new table: pc_profile_policies -Markdown 是纯画像内容,运行元数据单独关联到 Artifact Revision: - -| 字段 | 类型 | 约束 | +| 字段 | SQLAlchemy 类型 | 约束/含义 | | --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifacts` | -| `family` | `VARCHAR(128)` binary collation | PK part, FK part, CHECK `family='profile'` | -| `artifact_id` | `VARCHAR(128)` binary collation | PK part, FK part | -| `revision` | `INTEGER` | PK part, FK part | -| `generation_mode` | `VARCHAR(32)` binary collation | `automatic/manual_create/manual_replace/review_approved/rollback` | -| `generator_id` | `VARCHAR(128)` binary collation | NULL for manual operations | -| `generator_version` | `VARCHAR(128)` binary collation | NULL for manual operations | -| `source_after` | `BIGINT` | nullable, CHECK >= 0 | -| `source_through` | `BIGINT` | nullable, CHECK >= `source_after` | -| `restored_from_revision` | `INTEGER` | nullable, CHECK > 0;与同一 `scope_id/family/artifact_id` 组成复合 FK | -| `operation_reason` | `TEXT` | nullable | -| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | - -约束: +| scope_id | identity_string(256) | PK,FK -> pc_scopes.scope_id,ON DELETE CASCADE | +| generation_enabled | Boolean | NOT NULL,是否参与计划扫描/Flush | +| activation_mode | identity_string(32) | NOT NULL,automatic 或 review_required | +| pending_candidate_id | identity_string(128) | nullable,与 scope_id 组成 FK -> pc_artifact_candidate_heads | +| version | BigInteger | NOT NULL,>0,配置及处理状态 CAS 版本 | +| updated_at | DateTime(timezone=True) | NOT NULL,UTC | ```text -PRIMARY KEY (scope_id, family, artifact_id, revision) -FOREIGN KEY (scope_id, family, artifact_id, revision) - REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) -FOREIGN KEY (scope_id, family, artifact_id, restored_from_revision) - REFERENCES pc_artifacts(scope_id, family, artifact_id, revision) -CHECK (family = 'profile') -CHECK (generation_mode IN - ('automatic', 'manual_create', 'manual_replace', 'review_approved', 'rollback')) -CHECK ((source_after IS NULL) = (source_through IS NULL)) -CHECK (source_after IS NULL OR (source_after >= 0 AND source_through >= source_after)) -CHECK ( - (generation_mode IN ('automatic', 'review_approved') AND source_after IS NOT NULL) - OR - (generation_mode IN ('manual_create', 'manual_replace', 'rollback') AND source_after IS NULL) -) -CHECK ( - (generation_mode = 'rollback' AND restored_from_revision IS NOT NULL) - OR - (generation_mode <> 'rollback' AND restored_from_revision IS NULL) -) +PRIMARY KEY (scope_id) +CHECK (activation_mode IN ('automatic', 'review_required')) +CHECK (version > 0) +FOREIGN KEY (scope_id, pending_candidate_id) + REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) ON DELETE RESTRICT ``` -### New table: `pc_profile_candidate_metadata` - -现有 Candidate 表不保存生成窗口,不能在拒绝时可靠知道 Cursor 应推进到哪里。Profile 自动 Candidate 因此增加一条窄化的处理元数据记录: - -| 字段 | 类型 | 约束 | -| --- | --- | --- | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK part -> `pc_artifact_candidate_heads` | -| `candidate_id` | `VARCHAR(128)` binary collation | PK part, FK part | -| `binding_name` | `VARCHAR(128)` binary collation | NOT NULL, CHECK `binding_name='profile-source-window'` | -| `source_after` | `BIGINT` | NOT NULL, CHECK >= 0 | -| `source_through` | `BIGINT` | NOT NULL, CHECK >= `source_after` | -| `claimed_flush_generation` | `BIGINT` | NOT NULL, CHECK >= 0 | -| `rejection_disposition` | `VARCHAR(32)` binary collation | nullable;`reject_and_consume/reject_and_retry` | -| `created_at` | `DateTime(timezone=True)`,按 UTC 归一化 | NOT NULL | +| scope_id | generation_enabled | activation_mode | pending_candidate_id | version | updated_at | +| --- | --- | --- | --- | --- | --- | +| S_GROUP | true | automatic | NULL | 3 | 2026-09-07T18:00:00Z | +| S_U1 | true | review_required | cand_01 | 7 | 2026-09-07T18:00:00Z | -```text -PRIMARY KEY (scope_id, candidate_id) -FOREIGN KEY (scope_id, candidate_id) - REFERENCES pc_artifact_candidate_heads(scope_id, candidate_id) -CHECK (binding_name = 'profile-source-window') -CHECK (rejection_disposition IS NULL OR rejection_disposition IN - ('reject_and_consume', 'reject_and_retry')) -``` +缺少 Policy 表示自动生成未启用。新建主体 Scope 的 Policy 默认 enabled=true、automatic、version=1; +基础人工创建画像时若缺少 Policy,则创建 enabled=false、automatic 的 Policy,用于并发协调,不隐式开启后台生成。 +Policy PUT 保留 pending_candidate_id;该字段不能由客户端指定或清除。 -Candidate Create 同时写 Candidate、该元数据和 `pc_profile_policies.pending_candidate_id`,但不推进 Cursor。Approve 在同一 -事务中提交 Profile Revision、Revision Metadata、Candidate 状态、Cursor/Pending 和 Policy 指针。Reject 不创建 Artifact: -`reject_and_consume` 在同一事务中推进到 `source_through` 并更新 Pending;`reject_and_retry` 保持 Cursor 不变并保留或重新 -upsert Pending。两者都记录 `rejection_disposition`、拒绝原因并清空 Policy 指针。若期间 Head 已变化,操作冲突并保留 -Candidate,不推进 Cursor。 +### Artifact content, heads and lineage -### New generic tables shared with Topic Memory +`pc_artifacts` 示例: -如果 Topic Memory 尚未先行创建,下列两张表由本 RFC 一并增加。 +| scope_id | family | artifact_id | revision | content BLOB | +| --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 3 | C3 | +| S_U1 | profile | profile | 4 | C4 | +| S_GROUP | profile | profile | 2 | Group profile snapshot | -`pc_artifact_processing_pending`: +C4 是批准 cand_01 后的完整数据,正文示例没有 Claim 行或 category: -| 字段 | 类型 | 约束 | -| --- | --- | --- | -| `binding_name` | `VARCHAR(128)` binary collation | PK part | -| `scope_id` | `VARCHAR(256)` binary collation | PK part, FK -> `pc_scopes.scope_id` | -| `source_through` | `BIGINT` | NOT NULL, CHECK >= 1 | -| `flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK >= 0 | -| `handled_flush_generation` | `BIGINT` | NOT NULL, DEFAULT 0, CHECK between 0 and `flush_generation` | +```json +{ + "schema": "powercontext.profile.v1", + "media_type": "text/markdown", + "content": "# 用户画像\n\n- 偏好简洁的中文回答。\n", + "generation": { + "mode": "review_approved", + "created_at": "2026-09-08T01:00:00Z", + "generator_id": "profile-source-window", + "generator_version": "1", + "source_window": {"after": 41, "through": 42}, + "restored_from_revision": null + } +} +``` -Profile 使用 `binding_name="profile-source-window"`。 +`pc_artifact_heads`,对应审核前后分别指向 Revision 3/4;下表为审核后: -`pc_artifact_processing_leases`: +| scope_id | family | artifact_id | revision | searchable_text | lifecycle_state | replacement_artifact_id | governance_generation | +| --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | 偏好简洁的中文回答 | active | NULL | 0 | +| S_GROUP | profile | profile | 2 | U1 偏好简洁中文;U2 需要详细分析 | active | NULL | 0 | -| 字段 | 类型 | 约束 | -| --- | --- | --- | -| `supervisor_group` | `VARCHAR(128)` binary collation | PK;首期固定 `global` | -| `holder_id` | `VARCHAR(128)` binary collation | NOT NULL | -| `supervisor_generation` | `BIGINT` | NOT NULL, CHECK > 0 | -| `lease_expires_at` | `DateTime(timezone=True)`,按 UTC 归一化 | nullable for single-process SQLite | +`pc_artifact_lineage_sources`: -两张表是通用 Artifact processing substrate,不属于 Profile 内容模型。 +| scope_id | family | artifact_id | revision | ordinal | source_type | source_id | +| --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | 0 | content | src_01 | +| S_GROUP | profile | profile | 2 | 0 | content | src_01 | -### Existing tables: no physical schema changes +`pc_artifact_lineage_artifacts`: -本 RFC 不修改以下已有表的列、主键或外键: +| scope_id | family | artifact_id | revision | ordinal | upstream_family | upstream_artifact_id | upstream_revision | +| --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | profile | profile | 4 | 0 | profile | profile | 3 | -| 现有表 | 本 RFC 的用法 | DDL 变更 | -| --- | --- | --- | -| `pc_scopes` | 保存业务 Scope 和用户 Root;Root 的 `parent_scope_id=NULL` | 无 | -| `pc_scope_bindings` | 本方案不用于 Subject Root 映射 | 无 | -| `pc_scope_context_references` | Source Create 不自动写入 | 无 | -| `pc_sources` | 原 Scope 与 Root 各保存一条相同 Source | 无 | -| `pc_source_journal_heads` | 两个 Scope 各自维护 journal 高水位 | 无 | -| `pc_source_cursors` | 保存 `profile-source-window` 的消费位置 | 无 | -| `pc_artifacts` | 保存不可变 Profile Revision;`content` 已是 BLOB/MEDIUMBLOB | 无 | -| `pc_artifact_heads` | 保存 `profile:user` 或 `profile:local` 当前 Head | 无 | -| `pc_artifact_lineage_sources` | 自动 Profile 引用同 Scope 的可消费 Root Source;人工操作保留同 Scope `lineage_only` 系统 Source | 无 | -| `pc_artifact_lineage_artifacts` | 新 Profile Revision 引用上一 Revision | 无 | -| `pc_artifact_candidate_versions` | `review_required` 时保存完整 ProfileContent proposal | 无 | -| `pc_artifact_candidate_heads` | 保存 Profile Candidate 当前审核状态 | 无 | -| `pc_artifact_publications` | 本 RFC 的 Source 复制不使用 Artifact Publication | 无 | -| `powercontext_scheduler_jobs` | APScheduler sidecar 增加一个 Profile Cron job row | 表结构无变化 | - -虽然数据库 DDL 不变,Artifact 与 Candidate 的代码/OpenAPI family 枚举需要增加 `profile`,见接口变更。 - -### Example rows for one U1 message +自动更新引用作为生成输入的上一画像;基础人工 Replace 的 lineage 仍按基础 API 规则处理,不把其他 Revision 的 +lineage_only Source 当作新证据。`pc_artifact_publications` 在主体 Source 双写中无新增行。 -```text -pc_subject_roots - (U1, R_U1) +### Candidates and scheduler -pc_sources - (S_GROUP, content, source_01, payload=P, journal_position=101) - (R_U1, content, source_01, payload=P, journal_position=42) +`pc_artifact_candidate_versions`,审核前的示例: -pc_subject_source_projections - (S_GROUP, content, source_01, U1, R_U1, content, source_01, sha256:...) +| scope_id | candidate_id | version | family | proposal BLOB | source_refs BLOB | artifact_refs BLOB | target_family | target_artifact_id | target_revision | reason | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | cand_01 | 1 | profile | Q1 | [{"source_type":"content","source_id":"src_01"}] | [{"family":"profile","artifact_id":"profile","revision":3}] | profile | profile | 3 | New evidence | -pc_artifact_processing_pending - (profile-source-window, R_U1, source_through=42, ...) +```json +{ + "schema": "powercontext.profile-candidate.v1", + "content": "# 用户画像\n\n- 偏好简洁的中文回答。\n", + "source_window": {"after": 41, "through": 42}, + "generator_id": "profile-source-window", + "generator_version": "1", + "created_at": "2026-09-07T18:00:00Z" +} ``` -U2/U3 的 Root、journal、Cursor 和 Pending 均不变化。 +以上为 Q1。Revise 插入 version=2,保留所有服务端处理信息和 target,仅改变 content。 +`pc_artifact_candidate_heads` 的三个示例状态互斥,实际只存在一条当前 Head: -## API design +| scope_id | candidate_id | family | version | status | result_family | result_artifact_id | result_revision | decision_reason | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| S_U1 | cand_01 | profile | 1 | pending | NULL | NULL | NULL | NULL | +| S_U1 | cand_01 | profile | 1 | approved | profile | profile | 4 | NULL | +| S_U1 | cand_01 | profile | 1 | rejected | NULL | NULL | NULL | Evidence is too temporary | -### Python request and response types - -以下类型展示首期公开契约的关键字段;已有模型未展示的字段保持不变: - -```python -from __future__ import annotations +approve/reject 两种结果都会清空 Policy 指针并把 Cursor 从 41 推进到 42;只有 approve 产生 C4。 +历史窗口保留在 Candidate version 中,因此无需 `pc_profile_candidate_metadata`。 -from typing import Annotated, Any, Generic, Literal, Mapping, TypeVar +`powercontext_scheduler_jobs` 复用 APScheduler 的 id/next_run_time/job_state: -from pydantic import BaseModel, ConfigDict, Field, model_validator +| id | next_run_time | job_state | +| --- | --- | --- | +| powercontext.profile.source-window.v1 | 1788804000.0 | APScheduler serialized CronTrigger: 02:00 Asia/Shanghai, dispatch_profile_windows | +该时间对应 `2026-09-08T02:00:00+08:00`;job_state 由 APScheduler 序列化,不手写 BLOB。 +权限关系使用已有 Access Control 表和 RelationshipWriter;以下列出自动创建及画像提交时的代表性字段,其他审计、 +摘要和版本字段由现有服务填写。假设调用 Principal 为 service/app-agent,其身份与业务主体 U1 没有自动对应关系: -SubjectKey = Annotated[str, Field(min_length=1, max_length=256, pattern=r".*\S.*")] -ETag = Annotated[str, Field(min_length=1)] +| 已有表 | 实际数据示例(关键列) | +| --- | --- | +| pc_access_relationships | binding_id=bind_01, subject_type=service, subject_id=app-agent, resource_type=scope, scope_id=S_U1, role=scope.contributor, state=active, version=1 | +| pc_access_relationship_heads | name=authorization, revision=12;按现有服务在关系变动时递增 | +| pc_access_idempotency | actor_id=, operation=binding.create, result_binding_id=bind_01;内部授权操作的去重记录,不是 Source HTTP 幂等 | +| pc_access_audit | principal_type=service, principal_id=app-agent, scope_id=S_U1, allowed=true;operation/action 按现有授权与审计服务生成 | +| pc_access_owners | owner_kind=artifact, scope_id=S_U1, family=profile, artifact_id=profile, owner_type=service, owner_id=app-agent;Candidate owner_kind=candidate、candidate_id=cand_01 使用既有规则 | +不新增权限表。生成与审核沿用已有 owner 建立/继承规则;后台由配置的可信服务 Principal 负责,不能把 subject_key +作为 owner_id。上表 owner 示例适用于以 app-agent 身份提交的场景,并非由 U1 自动推导。 -class PrincipalRef(BaseModel): - type: Literal["user", "service"] - id: Annotated[str, Field(min_length=1, max_length=256)] - description: str | None = None +## API surface and Python examples +仅新增四个 HTTP operation;下表路径和类型是本 RFC 的实现目标,不表示当前版本已经提供。 -class SubjectRoutingFields(BaseModel): - subject_key: SubjectKey | None = None - root_contributor: PrincipalRef | None = None +| operationId | 方法与路径 | 成功状态 | 用途 | +| --- | --- | --- | --- | +| create_subject_source | POST /v1/scopes/{scope_id}/subject-sources | 201 | 解析主体绑定并原子双写 | +| get_profile_policy | GET /v1/scopes/{scope_id}/profile-policy | 200 | 读取策略及未决指针 | +| put_profile_policy | PUT /v1/scopes/{scope_id}/profile-policy | 200 | 显式启用/停用及设置审核策略 | +| flush_profile | POST /v1/profile/flush | 200 | 立即执行一个有界窗口,复用后台 Processor | +Policy GET 缺失记录返回 404;PUT 使用 expected_version,0 表示仅允许首次创建,其他正值必须匹配当前版本。 +GET 要求 scope.read,PUT 要求 scope.admin。Policy 更新与处理提交共享 version,冲突后客户端重新 GET。 +Flush 在 Policy 不存在或 generation_enabled=false 时返回 disabled,不强行开启生成;本次调用等待一个窗口处理完成,有部署配置的超时上限。 +超时不能推断事务未提交,客户端通过现有 Artifact/Candidate 和 Policy 读取状态;重试仍经 Cursor/CAS 判断。 -class CreateSourceRequest(SubjectRoutingFields): - # Existing fields remain unchanged. +```python +class CreateSubjectSourceRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + subject_key: Identifier + subject_type: Literal["user"] = "user" + subject_scope_id: Identifier | None = None source_type: Literal["content"] = "content" - content: Any - - -class CaptureContentSourceRequest(SubjectRoutingFields): - # Existing fields remain unchanged. - scope_id: str - source_id: str - content: str - metadata: dict[str, Any] | None = None - - -class SubmitSourceObservationRequest(SubjectRoutingFields): - # Existing SourceObservation schema remains unchanged. - scope_id: str - observation: Any - - -class SourceAddress(BaseModel): - scope_id: str - source_type: str - source_id: str - - -class SubjectProjectionReceipt(BaseModel): - subject_key: SubjectKey - root_scope_id: str - origin_source: SourceAddress - root_source: SourceAddress - status: Literal["committed", "already_in_root"] - - -# DELTA ONLY: this is not a replacement definition for SourceRecord. -# SourceRecord keeps every existing field, including receipt_identity. -class SourceRecordDelta(BaseModel): - subject_projection: SubjectProjectionReceipt | None = None - - -class ArtifactRef(BaseModel): - family: str - artifact_id: str - revision: int - - -class ArtifactAddress(BaseModel): - scope_id: str - artifact: ArtifactRef - - -class MemoryEntryAddress(BaseModel): - memory: ArtifactAddress - entry_id: str - entry_version_id: str - - -class ProfileTarget(BaseModel): - subject_key: SubjectKey | None = None - scope_id: str | None = None - - @model_validator(mode="after") - def exactly_one_target(self): - if (self.subject_key is None) == (self.scope_id is None): - raise ValueError("provide exactly one of subject_key or scope_id") - return self - - -class ResolvedProfileTarget(BaseModel): - scope_id: str - artifact_id: Literal["profile:user", "profile:local"] - # Both are populated for a subject-keyed Profile and null for Scope-local. - subject_key: SubjectKey | None = None - root_scope_id: str | None = None - - -class ResolveSubjectRequest(BaseModel): - subject_key: SubjectKey - create_if_absent: bool = True - origin_scope_id: str | None = None - root_contributor: PrincipalRef | None = None - - @model_validator(mode="after") - def require_origin_for_create(self): - if self.create_if_absent and self.origin_scope_id is None: - raise ValueError("origin_scope_id is required when create_if_absent=true") - return self - - -class ResolveSubjectResponse(BaseModel): - subject_key: SubjectKey - root_scope_id: str - created: bool - - -class ProfileGenerationMetadata(BaseModel): - mode: Literal[ - "automatic", - "manual_create", - "manual_replace", - "review_approved", - "rollback", - ] - source_after: int | None = None - source_through: int | None = None - restored_from_revision: int | None = None - created_at: str - - -class ProfileRecord(BaseModel): - target: ResolvedProfileTarget - artifact: ArtifactAddress - media_type: Literal["text/markdown"] = "text/markdown" - content: str - content_digest: str - generation: ProfileGenerationMetadata + content: JsonValue +class CreateSubjectSourceResponse(BaseModel): + subject_type: Literal["user"] + subject_key: Identifier + subject_scope_id: Identifier + sources: list[SourceRecord] # Existing model; exactly two, business then subject. -class ProfileResponse(BaseModel): - """Python SDK wrapper; the wire body is ProfileRecord and ETag is a header.""" - - record: ProfileRecord - etag: ETag - - -class CreateProfileRequest(BaseModel): - target: ProfileTarget - content: str - reason: str - - -class GetProfileRequest(BaseModel): - target: ProfileTarget - - -class ListProfileChangesRequest(BaseModel): - target: ProfileTarget - limit: Annotated[int, Field(ge=1, le=100)] = 50 - cursor: str | None = None - - -class ProfileChange(BaseModel): - artifact: ArtifactAddress - generation: ProfileGenerationMetadata - content_digest: str - - -class ProfileChangesPage(BaseModel): - target: ResolvedProfileTarget - items: tuple[ProfileChange, ...] - next_cursor: str | None = None - - -class DiffProfileRequest(BaseModel): - target: ProfileTarget - from_revision: Annotated[int, Field(ge=1)] - to_revision: Annotated[int, Field(ge=1)] - - -class ProfileDiffHunk(BaseModel): - old_start: int - old_lines: int - new_start: int - new_lines: int - lines: tuple[str, ...] - - -class ProfileDiff(BaseModel): - from_artifact: ArtifactAddress - to_artifact: ArtifactAddress - hunks: tuple[ProfileDiffHunk, ...] - - -class ReplaceProfileRequest(BaseModel): - # If-Match is an HTTP header, not a body field. - target: ProfileTarget - content: str - reason: str - - -class RollbackProfileRequest(BaseModel): - # If-Match is an HTTP header, not a body field. - target: ProfileTarget - restore_revision: Annotated[int, Field(ge=1)] - reason: str - - -class GenerateProfileRequest(BaseModel): - target: ProfileTarget - - -class ProfileGenerationResponse(BaseModel): - target: ResolvedProfileTarget - status: Literal["accepted", "idle", "review_pending"] - binding_name: Literal["profile-source-window"] - source_through: int | None = None - flush_generation: int | None = None - - -class GetProfileProcessingRequest(BaseModel): - target: ProfileTarget - - -class ProfileProcessingStatus(BaseModel): - target: ResolvedProfileTarget - journal_head: int - cursor_after: int - pending_through: int | None = None - pending_flush_generation: int | None = None - pending_candidate_id: str | None = None - last_result: Literal["success", "noop", "review_pending", "failure"] | None = None - - -class GetProfilePolicyRequest(BaseModel): - target: ProfileTarget - - -class ProfilePolicyRecord(BaseModel): - target: ResolvedProfileTarget +class PutProfilePolicyRequest(BaseModel): + model_config = ConfigDict(extra="forbid") generation_enabled: bool - activation_mode: Literal["automatic", "review_required"] - version: int - + activation_mode: Literal["automatic", "review_required"] = "automatic" + expected_version: int = Field(ge=0) -class UpdateProfilePolicyRequest(BaseModel): - target: ProfileTarget +class ProfilePolicyResponse(BaseModel): + scope_id: Identifier generation_enabled: bool activation_mode: Literal["automatic", "review_required"] - expected_version: Annotated[int, Field(ge=1)] - - -ContextAddress = ArtifactAddress | MemoryEntryAddress - - -class PrepareSubjectContextRequest(BaseModel): - subject_key: SubjectKey - query: Annotated[str, Field(min_length=1)] - families: tuple[Literal["profile", "memory", "topic-memory", "skill", "experience"], ...] - max_bytes: Annotated[int, Field(ge=1, le=4_194_304)] - - -class SubjectContextItem(BaseModel): - address: ContextAddress - content: str - selected_bytes: int - - -class SubjectContextConflict(BaseModel): - summary: str - left: ContextAddress - right: ContextAddress - - -class PreparedSubjectContext(BaseModel): - subject_key: SubjectKey - root_scope_id: str - scope_ids: tuple[str, ...] - items: tuple[SubjectContextItem, ...] - conflicts: tuple[SubjectContextConflict, ...] - used_bytes: int - max_bytes: int - truncated: bool + pending_candidate_id: str | None + version: int = Field(ge=1) + updated_at: str +class FlushProfileRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + scope_id: Identifier -T = TypeVar("T") - - -class HttpResult(BaseModel, Generic[T]): - body: T - headers: Mapping[str, str] - - -def with_profile_metadata(result: HttpResult[ProfileRecord]) -> ProfileResponse: - """Shared SDK helper used by Profile Create, Get, Replace, and Rollback.""" - - etag = result.headers.get("ETag") - if etag is None: - raise RuntimeError("Profile response omitted required ETag") - return ProfileResponse(record=result.body, etag=etag) +class FlushProfileResponse(BaseModel): + status: Literal["updated", "noop", "review_pending", "disabled", "conflict"] + previous_cursor: int + current_cursor: int + high_watermark: int + processed_source_count: int + artifact: ArtifactRef | None = None # Existing exact ref, scoped by request. + candidate_id: str | None = None ``` -`ProfileTarget(subject_key=...)` 解析到 `root_scope_id + profile:user`。`ProfileTarget(scope_id=...)` -先检查该 Scope 是否登记在 `pc_subject_roots`:若是用户 Root,同样规范化为 `profile:user`;只有普通 Scope -才解析为 `profile:local`。因此不能用不同 selector 在同一用户 Root 创建两个 Profile Head。 - -`ProfileResponse` 是 Python SDK 的 metadata-aware wrapper,不是新的 HTTP body envelope。Profile Create、Get、 -Replace 和 Rollback 的 wire body 都是 `ProfileRecord`,SDK 通过共享的 `with_profile_metadata` helper 同时读取 -response body 与 `ETag` header,构造 `ProfileResponse(record=..., etag=...)`。Scope-local Profile 的 -`subject_key` 和 `root_scope_id` 都为 `None`。 +所有新增模型拒绝未知请求字段并验证 ID/枚举;响应里的 SourceRecord 和 ArtifactRef 复用现有类型及可选字段。 +Flush 的 processed_source_count 为本次读取窗口中的 eligible Source 数量;无新调用模型的 review_pending/disabled 返回 0。 +并发 conflict 返回现读 Cursor,且不包含被丢弃结果的 artifact/candidate_id。其余字段为非负整数。 -上面的 `SourceRecordDelta` 只展示本 RFC 增加的字段。最终 `SourceRecord` 必须保留现有全部字段,包括 -`receipt_identity`,再增加可选 `subject_projection`;不得用该代码片段覆盖现有 schema。 - -### Existing API changes - -| 已有接口/Schema | 变更 | 兼容性 | -| --- | --- | --- | -| 所有业务 Source 写入 application service | `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 增加可选 `subject_key` 和 `root_contributor`;传入 key 时统一经 `SubjectSourceRoutingService` | 不传时行为不变;HTTP、Runtime、MCP 和 Connector 共用 | -| `POST /v1/scopes/{scope_id}/sources` | HTTP adapter 将扩展后的 `CreateSourceRequest` 交给上述统一服务 | 不传 key 时行为不变;加法式变更 | -| `SourceRecord` | 增加可选 `subject_projection`,返回 Root 与 Root Source 地址 | 旧客户端可忽略 | -| Root Scope 上的 Source Create | 必须携带与 Root 映射一致的 `subject_key`;内部投影除外 | 普通 Scope 行为不变;新增 Root 边界校验 | -| `PUT /v1/scopes/{scope_id}` | 当目标是已登记的用户 Root 时,禁止把 `parent_scope_id` 改为非空 | 请求结构不变;新增 Root 不变量冲突 | -| `BaseArtifactFamily` | 枚举增加 `profile`,用于通用 Artifact 读取地址和响应 | 加法式变更 | -| `CreateArtifactRequest`、`ReplaceArtifactRequest` | 首期不增加 Profile 分支;通用 Artifact Create/Replace 不接受 `profile` 写入 | 现有写入 union 不变;Profile 写入只能走专用 API | -| 通用 Artifact Get head、Get revision、List | 接受 `family=profile`,内容仍是 `ProfileContent` object | 路径和响应外形不变 | -| `CandidateFamily` | 枚举增加 `profile` | 加法式变更 | -| `ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` | union 增加 `ProfileContent` | 加法式变更 | -| `/v1/artifact-candidates/list|get|approve|reject|revise` | 支持完整 Markdown Profile Candidate;Profile Reject 强制 `disposition=reject_and_consume/reject_and_retry`;Approve/Reject 联动 Cursor、Pending、窗口元数据和 Policy 指针 | 路径不变,Profile 分支增加原子副作用 | -| Profile Create/Get/Replace/Rollback response | wire body 为 `ProfileRecord`,全部返回 `ETag` header;Python SDK 返回 `ProfileResponse` | 新增 metadata-aware helper,不改变通用 Client 返回类型 | -| `GET /v1/capabilities` | `artifact_families` 包含 `profile`,并增加 `profile_generation` 能力位 | 加法式变更 | - -除上表列出的 Root Parent 保护与可选 Source 投影信息外,Scope、Source exact identity、Artifact identity、ETag、Revision 和 Candidate 状态语义不变。首期仍不增加 Source Update;新的事实或纠正通过 Create 新 Source 表达。 - -当前 Source Create 与 Source exact Get 共用 `SourceRecord`,所以选择在 `SourceRecord` 增加可选字段时,两者都会得到这一加法式字段。读取 Origin Source 时可以返回投影关系;读取 Root Source 时可以返回其 Origin。若实现只希望 Create 返回 receipt,则必须新增 `CreateSourceResponse` 并把 `201` 响应从 `SourceRecord` 改为该类型,不能只修改服务端返回值而不修改 OpenAPI。 - -Candidate 数据库表虽然 family-neutral,现有 Review Service 仍只处理 Experience/Skill。支持 Profile 时, -`ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` 和内部 `ReviewedProposal` 都要加入 -`ProfileContent`。ReviewService 增加 Profile 分支:解析 Candidate 的固定目标后调用内部 Profile RecordService,提交到 -`profile:user` 或 `profile:local` 并执行 Head CAS、Cursor/Pending 和 Policy 指针事务;不得经通用 Artifact Create/Replace -分配随机 Artifact ID。只扩展 `CandidateFamily` 枚举不够。 - -已有非 HTTP 配置与 Python 组装也有加法式变化: - -| 位置 | 变更 | +| 现有接口/组件 | 变动 | | --- | --- | -| Runtime configuration | 增加 Profile Cron、IANA timezone、Window limit、并发与超时配置;现有 Memory/Experience interval 配置不变 | -| Scheduler assembly | 新增 `configure_profile_generation_job` 和带独立 timezone 的 CronTrigger;复用 `powercontext_scheduler_jobs`,不以 86,400 秒 Interval 代替每日时间点 | -| Artifact registry / read codecs | 注册 `ProfileContent`,供通用 exact Get、revision Get 和 List 解码;不注册公开 generic write 分支 | -| Profile RecordService | Profile 专用 API、Processor 和 ReviewService 解析固定 identity 后,复用内部 Artifact RecordService 的 Create/Replace/Head CAS | -| System provenance Source target | 允许 `family="profile"`;人工 Create/Replace/Rollback 保留 `lineage_only` Source,自动 Profile Window 必须过滤 | -| Review Service | `ReviewedProposal` 增加 `ProfileContent`,并将 Profile Approve/Reject 与 RecordService、Cursor/Pending 原子联动 | - -### New APIs - -PowerContext 已有 operation-style POST 接口。本 RFC 使用请求体承载 `subject_key`,避免把业务用户 ID 固定暴露在 URL path 和访问日志中。 - -| 新接口 | 用途 | 成功结果 | -| --- | --- | --- | -| `POST /v1/subjects/resolve` | 幂等解析或创建 `subject_key -> root_scope_id` | 固定 `200`;body 用 `created` 区分 | -| `POST /v1/profile/create` | 人工创建首个完整 Markdown Profile | `201` + `ETag`;已存在为 `409` | -| `POST /v1/profile/get` | 按 `ProfileTarget` 获取当前 Head | `200` + `ETag` | -| `POST /v1/profile/changes` | 列出 Revision 与生成元数据 | `200` | -| `POST /v1/profile/diff` | 比较两个 Markdown Revision | `200` unified/structured line diff | -| `POST /v1/profile/replace` | 人工提交完整 Markdown,必须携带当前 Head 的 `If-Match` | `200` new Revision + `ETag` | -| `POST /v1/profile/rollback` | 复制旧内容为新的 Head Revision,必须携带当前 Head 的 `If-Match` | `200` new Revision + `ETag` | -| `POST /v1/profile/generate` | 请求立即处理现有新 Source,不等待 LLM | 固定 `200`;body `status=accepted/idle/review_pending` | -| `POST /v1/profile/processing/get` | 读取 journal head、Cursor、Pending 和最近结果 | `200` | -| `POST /v1/profile/policy/get` | 读取自动生效/Review Policy | `200` | -| `POST /v1/profile/policy/update` | 使用 expected policy version 修改 Policy | `200` | -| `POST /v1/subjects/context/prepare` | 解析 Root 并聚合 Root 及真实 descendants 中被授权的 Artifact | `200` | - -Profile Create、Get、Replace、Rollback 的成功响应都在 header 返回当前 Head 的不透明 `ETag`;wire body 固定为 -`ProfileRecord`。Python SDK 使用 metadata-aware helper 返回 `ProfileResponse(record, etag)`。 - -Profile 审核的 list/get/approve/reject/revise 复用现有 Artifact Candidate 接口,不另建第二套审核状态机。Profile Reject -request 在现有原因之外必须携带 `disposition`,以明确同一 Source Window 是消费还是重试。 - -```python -from typing import Annotated, Literal - -from pydantic import BaseModel, ConfigDict, Field - - -class RejectArtifactCandidateRequest(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - scope_id: str - candidate_id: str - expected_version: Annotated[int, Field(ge=1)] - reason: Annotated[str, Field(min_length=1, max_length=2000)] - disposition: Literal["reject_and_consume", "reject_and_retry"] | None = None -``` - -`disposition` 对 Experience/Skill 保持可选且必须为 `None`;服务端解析 Candidate 后,仅对 `family=profile` 强制非空。 - -例如,审核者确认该窗口不应改变画像时提交: - -```json -{ - "scope_id": "R_U1", - "candidate_id": "candidate_01", - "expected_version": 3, - "reason": "这段内容只是一次性请求,不应成为长期画像", - "disposition": "reject_and_consume" -} -``` - -### Resolve Subject Root +| 基础 Source Create/Get、capture、observation | request/response 和单写语义不变 | +| Scope Create/Get/List、Binding Set/Clear | 契约不变;新入口内部使用 insert-only ensure,不改管理行为 | +| Scope Binding Resolve | 增加 allow_default=true;主体查询传 false,禁止未命中时使用默认 Scope | +| Artifact Create/Get/Get Revision/List/Replace | Family enum、输入联合类型、Family writer 增加 profile;仍使用现有路径 | +| Candidate Get/List/Revise/Approve/Reject | 增加 Profile proposal 和 committer;Profile 分支联动 Policy/Cursor | +| Artifact Access Profile、capabilities/readiness、内部权限 repository | 注册并报告 profile;支持事务内授权初始化,不增加权限动作或改变公开管理语义 | +| RuntimeConfig、scheduler register/configure | 增加 Profile Cron 配置和扫描回调,沿用现有 sidecar | +| Python Client、HTTP adapter | 新增上述四个 operation;既有 Artifact/Candidate 方法支持 profile | +| PrepareContext、其他 Family 生成接口 | 不扩展聚合范围或自动生成承诺 | + +Profile 人工创建沿用原来的 body 外形: ```http -POST /v1/subjects/resolve -Content-Type: application/json -``` - -```json -{ - "subject_key": "U1", - "create_if_absent": true, - "origin_scope_id": "S_GROUP", - "root_contributor": {"type": "user", "id": "principal-u1"} -} -``` +POST /v1/scopes/S_U1/artifacts -```json -{ - "subject_key": "U1", - "root_scope_id": "R_U1", - "created": true -} +{"family":"profile","content":{"content":"# 用户画像\n\n- 偏好简洁回答。\n"}} ``` -Root 创建成功后,映射不可重绑。`create_if_absent=false` 且不存在时返回 `404`。 -无论本次创建还是命中已有映射,成功状态都固定为 `200 OK`,由 response 的 `created` 布尔值表达结果。 - -`create_if_absent=false` 是只读解析,要求对已有 Root 的 `scope.read`。`create_if_absent=true` 是可创建的路由准备: -Root 不存在时执行 Origin `scope.contribute`、`server.admin`/可信 provisioner、Root/mapping/policy/Binding 同事务闭环; -Root 已存在时要求调用 Principal 同时拥有 Origin 与 Root 的 `scope.contribute`。`root_contributor` 省略时默认调用 -Principal;其值不会从 `subject_key` 推导。 +读取和替换仍为: -### Create Source with subject_key - -```http -POST /v1/scopes/S_GROUP/sources -Content-Type: application/json -``` - -```json -{ - "source_type": "content", - "content": { - "role": "user", - "text": "请优先给我简洁结论" - }, - "subject_key": "U1" -} +```text +GET /v1/scopes/S_U1/artifacts/profile/profile +GET /v1/scopes/S_U1/artifacts/profile/profile/revisions/3 +GET /v1/scopes/S_U1/artifacts/profile +PUT /v1/scopes/S_U1/artifacts/profile/profile (If-Match required) ``` ```json -{ - "scope_id": "S_GROUP", - "source_type": "content", - "source_id": "source_01", - "content": { - "role": "user", - "text": "请优先给我简洁结论" - }, - "position": 101, - "content_digest": "sha256:...", - "subject_projection": { - "subject_key": "U1", - "root_scope_id": "R_U1", - "origin_source": { - "scope_id": "S_GROUP", - "source_type": "content", - "source_id": "source_01" - }, - "root_source": { - "scope_id": "R_U1", - "source_type": "content", - "source_id": "source_01" - }, - "status": "committed" - } -} +{"content":{"content":"# 用户画像\n\n- 偏好简洁回答。\n","restored_from_revision":3}} ``` -`201` 表示两条 Source 与投影关系都已提交;它不表示 Profile 已生成。`subject_projection` 始终用 `origin_source` 和 `root_source` 明确方向,读取关系任一端时也返回同一对地址。 - -幂等保证只覆盖同一次服务端命令及其数据库事务重试:服务端复用已经生成的 `source_id`,不会在 Root 重复插入。现有 HTTP Create Source 没有 `Idempotency-Key`;客户端在提交成功但响应丢失后重新发送 HTTP 请求,仍会创建一个新的 Source 及其 Root 副本。通用 HTTP 创建幂等应由独立 RFC 解决,本设计不隐含扩大其语义。 - -### Get Profile +PUT 示例表示恢复 Revision 3 的正文;响应沿用 ArtifactRevision,包含服务端生成的 generation 和新的 ETag。 +SDK 对 Replace 继续使用现有 If-Match 参数机制,不假设 response model 自带 `.etag` 字段。 ```http -POST /v1/profile/get -Content-Type: application/json -``` +POST /v1/artifact-candidates/reject -```json -{ - "target": {"subject_key": "U1"} -} +{"scope_id":"S_U1","candidate_id":"cand_01","expected_version":1,"reason":"这只是临时要求"} ``` -```http -HTTP/1.1 200 OK -ETag: "profile:R_U1:profile:user:12:sha256-abc" -Content-Type: application/json -``` - -```json -{ - "target": { - "scope_id": "R_U1", - "artifact_id": "profile:user", - "subject_key": "U1", - "root_scope_id": "R_U1" - }, - "artifact": { - "scope_id": "R_U1", - "artifact": { - "family": "profile", - "artifact_id": "profile:user", - "revision": 12 - } - }, - "media_type": "text/markdown", - "content": "# 用户画像\n\n用户偏好中文简洁回答。\n", - "content_digest": "sha256:...", - "generation": { - "mode": "automatic", - "source_after": 37, - "source_through": 42, - "created_at": "2026-09-07T02:04:18+08:00" - } -} -``` - -Profile 专用响应将内部 `ProfileContent.content` 展平为 Markdown 字符串。通用 Artifact Get 仍返回完整 `ProfileContent` object。 - -### Create, replace and rollback - -首次人工创建: - -```python -created = await client.profile.create( - target=ProfileTarget(subject_key=app_user.user_id), - content="# 用户画像\n\n用户偏好中文回答。\n", - reason="user confirmed initial profile", -) -``` - -替换必须原样回传 Get/Create 返回的不透明 ETag;Python Client 以 `if_match` 参数映射到 HTTP `If-Match` header: - -```python -updated = await client.profile.replace( - target=ProfileTarget(subject_key=app_user.user_id), - content="# 用户画像\n\n用户偏好中文简洁回答。\n", - if_match=created.etag, - reason="user edited profile", -) -``` - -回退创建新 Revision: - -```python -restored = await client.profile.rollback( - target=ProfileTarget(subject_key=app_user.user_id), - restore_revision=3, - if_match=updated.etag, - reason="restore user-confirmed version", -) -``` - -Profile Replace 和 Rollback 缺少 `If-Match` 返回 `428 Precondition Required`;与当前 Head ETag 不一致返回 -`412 Precondition Failed`。ETag 必须保持不透明,不能由客户端根据 Revision 自行拼接。 - -首期通用 Artifact Create/Replace 不接受 `family=profile`。以上专用 API 与 Profile Processor 在解析 -`profile:user/profile:local` 后直接调用内部 RecordService;通用 Artifact exact Get、Revision Get 和 List 仍可读取 -Profile。 - -### Generate now - -```python -receipt = await client.profile.generate( - target=ProfileTarget(subject_key=app_user.user_id), -) -``` - -```json -{ - "target": { - "scope_id": "R_U1", - "artifact_id": "profile:user", - "subject_key": "U1", - "root_scope_id": "R_U1" - }, - "status": "accepted", - "binding_name": "profile-source-window", - "source_through": 42, - "flush_generation": 8 -} -``` - -该接口只要求立即开始处理已经存在的新 Source。成功 HTTP 状态始终是 `200 OK`:已唤醒处理返回 -`{"status":"accepted"}`,没有新 Source 返回 `{"status":"idle"}`,已有未决 Candidate 返回 -`{"status":"review_pending"}`。 - -### Subject context aggregation API +不新增主体 Artifact CRUD、Subject Resolve、Profile history/diff/rollback/context API。 +按 subject_key 查询时,先用 Scope Binding Resolve 精确查询,再调用普通 Scope API。Resolve 仍要求现有 server.observe: ```http -POST /v1/subjects/context/prepare -Content-Type: application/json -``` - -```json -{ - "subject_key": "U1", - "query": "推荐适合用户的酒店", - "families": ["profile", "memory", "topic-memory", "skill", "experience"], - "max_bytes": 262144 -} -``` +POST /v1/scope-bindings/resolve -```json -{ - "subject_key": "U1", - "root_scope_id": "R_U1", - "scope_ids": ["R_U1", "S_U1_PROJECT"], - "items": [ - { - "address": { - "scope_id": "R_U1", - "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} - }, - "content": "# 用户画像\n\n用户偏好中文简洁回答。\n", - "selected_bytes": 58 - }, - { - "address": { - "memory": { - "scope_id": "S_U1_PROJECT", - "artifact": {"family": "memory", "artifact_id": "memory", "revision": 7} - }, - "entry_id": "hotel-preference", - "entry_version_id": "mev_01" - }, - "content": "国内酒店偏好大床房。", - "selected_bytes": 33 - } - ], - "conflicts": [ - { - "summary": "预算信息存在时间冲突", - "left": { - "scope_id": "R_U1", - "artifact": {"family": "profile", "artifact_id": "profile:user", "revision": 12} - }, - "right": { - "scope_id": "S_U1_PROJECT", - "artifact": {"family": "topic-memory", "artifact_id": "travel", "revision": 4} - } - } - ], - "used_bytes": 91, - "max_bytes": 262144, - "truncated": false -} +{"binding_keys":[{"integration":"subject","kind":"user","external_id":"U1"}],"allow_default":false} ``` -这是新增的 `SubjectContextAdapter` 及其 HTTP/Python adapter,不表示现有 Prepare Context 已支持 Subject Root 遍历。 -该 adapter 解析 `R_U1`,逐 Scope 授权后选择 Root 与真实 descendants,再调用各 family 现有的精确读取或召回入口, -完成去重、冲突标注、排序和按 `max_bytes` 装配。共享群聊 `S_GROUP` 不会因为 U1 是参与者而被纳入;首期也不会自动 -复制其已有 Artifact。所有 Artifact 返回 `ArtifactAddress`;Memory Entry 等 subresource 通过包含 `ArtifactAddress` -的 family-owned address 返回。 - -未来其他 Artifact Family 若复用本设计,应为 Root Source 注册自己的处理 binding,并把用户级 Artifact 生成到 `R_U1` 或其真实子 Scope。这样它们自然进入同一主体查询范围,而不需要给通用 Artifact 表增加 `subject_key`。 - -## Access control and privacy - -权限实现复用 [RFC 1396](1396_handoff_access_control.md) 的现有 `scope.*` 与 `artifact.*` action,不新增 -`subject.*` 或 `profile.*` action vocabulary: - -| Profile/Subject operation | 既有 action | -| --- | --- | -| 解析已有 Subject Root | 返回映射前要求对 Root 拥有 `scope.read`;授权不足固定返回 `403` | -| 创建 Subject Root | 调用 Principal 对 Origin 要求 `scope.contribute`,并要求其拥有 `server.admin` 或由可信 provisioning service principal 承担该 action | -| subject-keyed 业务 Source 写入 | Root 已存在时,对 Origin Scope 和 Root Scope 都要求 `scope.contribute` | -| Profile Get、Changes、Diff | 对逻辑 Profile 要求 `artifact.read`;通过 Scope 列表发现时还要求 `scope.read` | -| 人工创建首个 Profile、请求 Generate | 对目标 Scope 要求 `scope.contribute`;创建成功后按既有 Artifact 流程建立 owner | -| Profile Replace、Rollback | 对逻辑 Profile 要求 system-managed owner relation 和 `artifact.write` | -| Profile Candidate 审核 | 对目标 Scope 要求 `scope.review` | -| Profile Policy Get/Update | Get 要求 `scope.read`,Update 要求 `scope.admin` | -| Subject Context Prepare | 对纳入范围的每个 Scope 要求 `scope.read`,对精确资源授权路径要求 `artifact.read` | - -Parent、Root 映射和 `subject_key` 都不授予权限,也不能把业务 `user_id` 转换为 Principal。Root 首次创建时, -`root_contributor` 省略则取调用 Principal,显式提供时必须是认证系统已解析的 `user` 或 `service` PrincipalRef。在同一 -协调事务中创建 Root、映射、Policy 和该 Principal 的 `scope.contributor` Binding 后,内部路由才可以执行首次 Root -写入。已有 Root 不修改 Binding,并要求调用 Principal 同时通过 Origin 与 Root 的 `scope.contribute`。 - -Profile 必须在 RFC 1396 的 Artifact Family Access Profile registry 中显式注册: - -| Field | Profile registration | -| --- | --- | -| enabled | `true` | -| share_unit | `artifact`,即固定逻辑 `profile:user` 或 `profile:local` | -| shareable_states | `{committed}` | -| base_action | `artifact.read` | -| grantable_roles | `{artifact.viewer}` | -| selector | forbidden;不接受 family-owned subresource selector | -| transitivity | `none`;读取 Profile 不授予 lineage Source 或其他 Artifact 读取权 | -| mutation_semantics | direct owner 通过 `artifact.write` 修改 | - -该注册不增加 Profile 专用 action。后台 Processor 必须携带配置的 service/system Principal;空 Principal 不得执行生成。 - -隐私要求: +## Errors, compatibility and implementation -- 日志、指标和错误默认不输出原始 `subject_key` 或 Source/Markdown 原文; -- 数据库直接保存业务 `user_id` 作为 `subject_key`,读取、备份和审计按用户标识保护策略处理; -- Root Source 是原文副本,需要与原 Source 使用一致的加密、保留和删除策略; -- 不在 Root Scope 的 title/summary 中写用户 ID; -- 聚合查询逐 Scope、逐 Artifact 授权,不泄露未授权 Scope 的存在或数量; -- 审核、编辑和回退记录操作者、时间、原因和目标 Revision。 - -## Error semantics - -| 场景 | 建议结果 | +| 条件 | 结果 | | --- | --- | -| `subject_key` 为空或超过 256 字符 | `422 invalid_subject_key` | -| `subject_key` 不存在且禁止创建 Root | `404 subject_root_not_found` | -| Root 不存在,调用 Principal 缺少 Origin `scope.contribute` 或所需 `server.admin` | `403 Forbidden` | -| `root_contributor.type` 不是 `user/service` | `422 invalid_root_contributor` | -| Authorization Provider 无法事务性建立 Binding,且没有可用可信 provisioner | `503 relationship_management_unavailable` | -| 两个 key 试图绑定同一个 Root | `409 subject_root_binding_conflict` | -| 当前 Scope 是另一个用户的 Root | `409 subject_key_mismatch` | -| 公开请求无 key 直接写用户 Root | `422 subject_key_required` | -| Origin Source 已投影到另一个 key | `409 source_subject_conflict` | -| 原 Source 与 Root Source 相同身份但 payload 不同 | `409 source_projection_content_conflict` | -| 双写中任一步失败 | 整体回滚,不留下单边 Source | -| Subject Resolve 创建或命中已有 Root | 固定 `200 OK`,以 `created` 区分 | -| 没有新 Source 时 Generate | `200 idle` | -| 已有未决自动 Profile Candidate | `200 review_pending`,不重复生成 | -| 已唤醒 Profile 处理 | `200 accepted` | -| 后台 LLM 或校验失败 | 保留旧 Head,不推进 Cursor,重试 | -| Head 或 Cursor CAS 冲突 | 重读最新状态并重新处理 | -| Profile Create 已有 Head | `409 profile_already_exists` | -| 通用 Artifact Create/Replace 请求写入 `family=profile` | `422 profile_requires_dedicated_api` | -| Replace/Rollback 缺少 `If-Match` | `428 Precondition Required` | -| Replace/Rollback 的 ETag 与当前 Head 不一致 | `412 Precondition Failed` | -| Review 时 Head 已变化 | `409 profile_revision_conflict`,保留 Candidate 且不推进 Cursor | -| Profile Reject 缺少 `disposition`,或非 Profile Reject 携带该字段 | `422 invalid_rejection_disposition` | -| Rollback 目标 Revision 不存在 | `404 profile_revision_not_found` | -| 已认证但无权访问 Root、子 Scope 或 Profile | 固定 `403 Forbidden` | - -## Configuration - -```yaml -profile: - enabled: true - artifact_id: "profile:user" - local_artifact_id: "profile:local" - max_content_bytes: 262144 - processing_binding: "profile-source-window" - schedule: - cron: "0 2 * * *" - timezone: "Asia/Shanghai" - source_window_limit: 200 - max_concurrency: 8 - worker_timeout_seconds: 900 - retry_max_delay_seconds: 1800 -``` - -Schedule 是部署级配置。`generation_enabled` 和 `activation_mode` 是 Scope 级 Policy。首期不提供每个用户单独配置 Cron,以避免为大量用户创建独立 scheduler job;一个每日波次公平处理所有 dirty targets。 - -## OpenAPI impact - -`openapi/powercontext.yaml` 是契约事实源,需要完成以下修改并重新生成代码: - -1. `BaseArtifactFamily` 增加 `profile`,供通用 Artifact Get head、Get revision 和 List 使用; - `CreateArtifactRequest`、`ReplaceArtifactRequest` 的写入 union 保持不变,不增加 Profile 分支。 -2. 新增 `ProfileContent`、Profile 专用 request/response/page/diff/processing/policy schemas; - `ArtifactRevision.content` 继续为 object,不改为裸字符串。 -3. `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 都增加可选 - `subject_key` 与 `root_contributor`;`SourceRecord` 在保留 `receipt_identity` 等已有字段的基础上增加可选 - `subject_projection`。 -4. `CandidateFamily` 增加 `profile`;`ArtifactCandidate.proposal`、`ReviseArtifactCandidateRequest.proposal` 和 - transport/internal `ReviewedProposal` union 增加 `ProfileContent`。 -5. `RejectArtifactCandidateRequest` 保留 `scope_id/candidate_id/expected_version/reason`,新增可选 - `disposition`;仅 Profile Candidate 要求该值非空。 -6. Profile Create、Get、Replace、Rollback 的成功响应都声明 `ETag` header;Replace/Rollback 声明必填 - `If-Match`,缺失或失配沿用 `428/412`。 -7. 新增 Subject resolve/context prepare 和 Profile create/get/changes/diff/replace/rollback/generate/processing/policy - operations;每个 operation 只声明一个成功 HTTP 状态。其中 Resolve 固定 `200` 并返回 `created`,Generate 固定 - `200` 并返回 `status=accepted/idle/review_pending`。 -8. Subject Context schema 使用 `max_bytes`,Artifact 结果使用 `ArtifactAddress`,Memory Entry 等 subresource 地址 - 必须包含 Scope。 -9. Capabilities 暴露可读 `profile` family、`profile_generation` 和 Subject Context adapter 能力。 -10. 生成文件继续通过 `make api-generate` 产生,不能手工修改 `src/powercontext/http/_generated/`。 - -## Implementation plan - -1. 增加 Profile family read codec、`ProfileContent`、固定 Artifact identity、Markdown 规范化和内部 Profile RecordService; - 通用 Artifact Create/Replace union 保持不变。 -2. 增加 `pc_subject_roots`,实现 Root Resolve、唯一约束、Root Parent 保护,以及 Root/mapping/policy/ - `scope.contributor` Binding 的首次创建授权事务。 -3. 增加共享的 `SubjectSourceRoutingService`,让 `CreateSourceRequest`、`CaptureContentSourceRequest` 和 - `SubmitSourceObservationRequest` 携带 `subject_key` 时统一完成双 Scope 锁、同事务 Source 双写、投影关系和 - Pending upsert。 -4. 落地或复用通用 Pending、Cursor、Lease 和 Artifact Processing Supervisor。 -5. 增加带时区的 Profile CronTrigger,默认每天 `02:00 Asia/Shanghai`。 -6. 实现 Profile Worker:固定 Window、read-before-write、LLM Markdown、NOOP、Head/Cursor CAS。 -7. 增加 Revision Metadata、Candidate Window Metadata、Policy 单一 pending 指针、`ProfileContent` proposal union 和 - 两种 Reject disposition。 -8. 实现 Profile convenience API、全部响应类型、metadata-aware Python SDK、`ETag`/`If-Match`、历史、Diff、人工 - 替换和回退。 -9. 注册 Profile ArtifactFamilyAccessProfile,并实现使用 `max_bytes`、`ArtifactAddress` 和 scoped subresource address - 的新增 Subject Context adapter。 -10. 补充首次 Resolve 授权、双写原子性、群聊隔离、调度恢复、`lineage_only` 过滤、单成功状态、条件写、Review - disposition 和回退测试。 +| 无效 subject_type、空白 key、非法正文或未知输入字段 | 422 | +| 已有绑定与显式 subject_scope_id 不一致 | 409 subject_scope_conflict | +| 两个实际 Scope 相同 | 422 distinct_scopes_required | +| 显式 Scope 不存在 | 404;不按调用方指定 ID 隐式创建 | +| 缺少任一实际 Scope/管理权限 | 403,无部分写入 | +| Profile Create 已存在 | 409 | +| Replace 缺少 If-Match / 不匹配 | 428 / 412 | +| Policy、Candidate 版本或审核 Cursor 冲突 | 409,不推进 Cursor | +| Approve 的目标 Head 已变化 | 409,保留候选 | +| 模型/存储暂时不可用 | 503,保留可恢复状态 | + +所有响应沿用 Request-ID 和既有错误 envelope,避免在错误中暴露无权限 Scope 的正文和绑定详情。 +新增 Profile family 要同时更新 OpenAPI 联合类型、只读输出类型、Candidate proposal 类型及 Family 注册。 +服务端生成字段与客户端输入分开,不能把 GET 返回的 generation 原样当作可写输入。 + +实施顺序: + +1. 增加 Profile content/write/proposal 模型和 Family writer,复用固定 Singleton ID、Artifact repository、lineage 和授权。 +2. 只创建 Policy 表;为生成元数据、Candidate processing context 定义带版本 schema 的 BLOB 编解码和服务端验证。 +3. 实现 insert-only ensure 和同事务双写 application service,包括并发首次创建、权限与完整回滚。 +4. 实现 Source-window Processor、Policy/Cursor/Head 协调、Candidate 生命周期和每日 Cron。 +5. 在 OpenAPI 增加四个 operation,扩展已有 Family/Candidate 分支;运行 `make api-generate`,不手改生成文件。 +6. 增加中英文使用文档与 SQLite/OceanBase 行为测试;运行 `make contract-test`、`make test`、`make check`、`make docs-test`。 ## Acceptance criteria -### Scope and identity - -- U1、U2、U3 与一个群聊只产生 `R_U1/R_U2/R_U3/S_GROUP` 四个 Scope; -- 群聊 Scope 不被自动设置为任何用户 Root 的 child 或 context reference; -- 同一 `subject_key` 并发 Resolve 只产生一个 Root; -- 不同 `subject_key` 不能映射到同一个 Root; -- Root 的 Parent 始终为 `NULL`; -- Root 首次创建只有在 Origin `scope.contribute` 和 `server.admin`/可信 provisioner 均通过后,才在同一事务创建 - Root、mapping、policy 和明确 `root_contributor` 的 `scope.contributor` Binding; -- Root 已存在时,subject-keyed 写入同时检查 Origin 与 Root 的 `scope.contribute`,且不从 `subject_key` 推导 Principal; -- 通过 `subject_key=U1` 或 `scope_id=R_U1` 访问 Profile 都规范化到同一个 `profile:user`,不能创建 `profile:local`; -- Profile 内容与身份模型只使用 `subject_key`、`root_scope_id` 和固定 Profile Artifact 地址,不增加第二套用户标识或画像类型字段。 - -### Source routing - -- 不带 `subject_key` 时,各业务 Source 入口保持现有持久化行为; -- `CreateSourceRequest`、`CaptureContentSourceRequest`、`SubmitSourceObservationRequest` 都通过同一 - `SubjectSourceRoutingService`; -- 带 `subject_key` 时,总共写入 Origin 与对应 Root 两条 Source; -- 两条 Source 的 payload 相同,journal position 在各自 Scope 独立分配; -- 任一步失败均不留下单边写入; -- U1 Source 不改变 U2/U3 Root 的 journal、Pending 或 Cursor; -- 同一次服务端命令的事务重试不产生重复 Root Source;新的 HTTP Create 请求仍按现有语义创建新 Source; -- 多用户批量内容不能作为单条 subject-keyed Source 写入。 - -### Profile content and revision - -- Profile 内容只有完整 Markdown,不存在 Claim category、Claim 表或逐 Claim 风险等级; -- Markdown 通过 `ProfileContent` 编码到现有 BLOB,已有 Artifact 表无需 DDL 变更; -- 一个 Root 只有一个 `profile:user` Head,`artifact_id` 是唯一身份的一部分; -- Create 已存在时冲突,Replace 使用 CAS; -- 通用 Artifact Create/Replace 不接受 Profile;通用 exact Get、Revision Get 和 List 可以读取 Profile; -- Profile Create、Get、Replace 和 Rollback 均返回 `ETag`,后两者用 `If-Match` 并验证 `428/412`; -- Scope-local `ProfileRecord` 的 `subject_key/root_scope_id` 为 null; -- 自动生成、人工编辑、审核通过和回退都创建不可变 Revision; -- 无语义变化不创建空 Revision。 - -### Automatic generation - -- 默认每天 `02:00 Asia/Shanghai` 启动,Cron 和时区可配置; -- 业务 Source 提交不等待 LLM; -- Scheduler 错过时间后可恢复一个合并波次; -- Worker 固定 `(after, through]` Window; -- Worker 排除 `lineage_only` 系统 Source,过滤后为空的窗口不调用 LLM 但仍可推进 Cursor; -- 同一个 Profile 串行,不同 Profile 在并发上限内并行; -- 失败不推进 Cursor,且不影响其他用户; -- 无新 Source 时定时或手工 Generate 均不 rebuild。 -- Resolve 成功固定为 HTTP `200` 并返回 `created`;Generate 成功固定为 `200` 并返回 - `accepted/idle/review_pending`。 - -### Review and correction - -- 默认整篇 Profile 自动生效; -- Policy 可切换为整篇 `review_required`; -- Candidate 审核复用现有 Candidate 状态机; -- 每个 Profile Scope 同时最多一个未决自动 Candidate;其 Source Window 可在重启后恢复; -- Reject 必须显式选择 `reject_and_consume` 或 `reject_and_retry`,并分别验证推进或保留 Cursor; -- 人工 Replace 和 Rollback 必须使用当前 Head 的不透明 `ETag` 作为 `If-Match`; -- Rollback 创建新 Revision,不删除历史或倒拨 Head。 -- `ArtifactCandidate.proposal`、Revise proposal 和 `ReviewedProposal` 都接受 `ProfileContent`,ReviewService 使用固定 - Profile identity 和内部 RecordService。 - -### Database and API inventory - -- 所有新增表均有主键、唯一约束、外键和幂等语义; -- 现有表变更矩阵明确为无物理 DDL 变化; -- OpenAPI 枚举、union、Source schema 和全部新 operation 均有契约测试; -- Revision Metadata 的 rollback 复合外键、mode/null CHECK,以及 Candidate 固定 binding CHECK 均有约束测试; -- Profile ArtifactFamilyAccessProfile、固定 `403` 和 Root provisioning 授权均有 conformance test; -- Python SDK 示例覆盖 Resolve、三类 Source 入口、Profile 全部 API 和 metadata-aware `ProfileResponse`; -- Subject Context 使用 `max_bytes`,跨 Scope Artifact/Memory Entry 只返回完整 scoped address。 - -## Decision summary - -1. 新增 `profile` Artifact Family,首期只支持用户画像。 -2. `subject_key` 的值直接使用调用方业务 `user_id`,首期不支持其他主体类型。 -3. 一个 `subject_key` 一一对应一个 `root_scope_id`;Root 是普通 Scope,Parent 固定为 `NULL`。 -4. 群聊 U1、U2、U3 加共享群聊共四个 Scope;共享 Scope 不属于任一用户 Root 子树。 -5. subject-keyed Source 总共保存两份:业务 Scope 原始 Source 与对应用户 Root Source;两者同事务提交。 -6. `subject_key` 不加入现有 Source 或 Artifact 表,由新增映射与投影表表达关系。 -7. 用户 Root 中固定使用 `(root_scope_id, profile, profile:user)`;普通 Scope 可显式启用 `profile:local`。 -8. Profile 内容是完整 Markdown,通过 `ProfileContent` 的 `content` 字段编码进现有 BLOB;不设计 Claim category、逐 Claim 风险或 Claim 表。 -9. 默认每天 `02:00 Asia/Shanghai` 后台生成,Cron 与时区可配置;手工 Generate 只处理已有新 Source。 -10. 自动更新只由新 Source Window 触发;无新 Source 不 rebuild,无语义变化不创建 Revision。 -11. 默认整篇 Revision 自动生效,可按 Profile Scope 配置整篇 `review_required`。 -12. 人工创建、替换、审核通过和回退均创建不可变 Revision;Create/Get/Replace/Rollback 返回 `ETag`,Replace/Rollback - 使用 `If-Match`。 -13. 新增 `pc_subject_roots`、`pc_subject_source_projections`、`pc_profile_policies`、`pc_profile_revision_metadata`、`pc_profile_candidate_metadata`;若通用 processing substrate 尚未落地,再新增 `pc_artifact_processing_pending` 和 `pc_artifact_processing_leases`。 -14. `pc_scopes`、`pc_sources`、`pc_artifacts`、Head、Lineage、Cursor 和 Candidate 等现有表均无物理 DDL 变更。 -15. 三类通用业务 Source 请求、Candidate proposal union 和 Capabilities 做加法式扩展;通用 Artifact 写入 union - 不增加 Profile。所有携带 `subject_key` 的业务 Source 入口共用主体路由服务;新增 Subject 与 Profile convenience APIs。 -16. 未来其他 Artifact Family 可以复用 Subject Root 与 Root Source,但共享 Scope 内已有 Artifact 不会自动跨 Scope 生效。 +- 本功能仅新增 pc_profile_policies,已有表的列/索引/FK 无变更,Artifact/Candidate BLOB 包含可验证的服务器元数据。 +- 单 Scope Source API 仍只写一条;主体入口双写两条同 ID/content 的 Source,不调用 LLM。 +- 首次并发绑定不会留下孤立 Scope;显式绑定冲突、权限失败或任一 Source 写失败都整体回滚。 +- 管理换绑/解绑保持原样,后续写入使用新绑定;历史数据不迁移,多主体同 Scope 合法。主体 Resolve 未命中不能回退到默认 Scope。 +- U1 的消息只改变 S_GROUP 和实际 S_U1 的 journal;两者可独立生成 Profile,U2/U3 不被触发。 +- 两个 Scope 相同拒绝;新 HTTP 重试可产生新 Source 对,不误称为幂等。 +- 任意 Scope 使用同一 Profile singleton ID,Create 冲突,Get/List/Replace/Review 复用现有接口。 +- 默认 02:00 Asia/Shanghai,可配置时间与时区;启动扫描恢复积压,不依赖 pending/job 表。 +- lineage_only 被过滤且可推进完整窗口;无有效正文变化不创建自动 Revision;无新 Source 不因模型升级重建。 +- 并发生成最多提交一次;Policy 变更、人工 Replace、Cursor 变化令陈旧结果失效。 +- Candidate 上下文不可由客户端修改;待审期间不重复生成;批准/拒绝与 Cursor 和指针原子更新。 +- Reject 消费窗口、不自动重试、不删除 Source;Head 已变化仍允许 Reject,Approve 必须冲突。 +- 回退提交新 Revision,保留历史与 Cursor;已有授权动作、Source 生成准入在所有 Profile 写入路径生效。 +- 本 RFC 不承诺 Memory、Experience、Skill、Topic Memory 等 Family 自动具备新的生成或聚合能力。 # Drawbacks -- 每条 subject-keyed Source 保存两份,增加存储、备份、保留和删除成本; -- Source 双写将一个原本单 Scope 的事务扩大为双 Scope 事务,需要一致锁顺序和更严格的并发测试; -- 现有 HTTP Source Create 没有客户端幂等键,响应丢失后的请求级重试仍可能形成重复事实及对应 Root 副本; -- `subject_key` 的正确性依赖调用方,PowerContext 不负责账号合并或纠正错误身份; -- 每天生成意味着画像存在最长约一天的正常延迟,需要即时结果时调用 Generate; -- 单一 Markdown 简化了存储与阅读,但首期失去 Claim 级查询、风险分级和精细 provenance; -- 共享 Scope 的已有 Artifact 不会自动成为用户制品;其他 family 需要显式消费 Root Source 后再生成到 Root; -- Root Source 原文副本扩大隐私和遗忘处理面。 - -# Rationale and alternatives - -## Why Subject Root is not the group Scope parent - -Scope 只有一个 Parent,而群聊可以有多个用户。把共享 Scope 挂给任何一个用户都会错误表达组织归属;尝试挂给多个用户则无法由现有模型表达。因此本 RFC 用 Source 投影表达主体关系,Parent 只保留真实组织关系。 +Source 双写增加存储和 journal 处理成本。共享 Scope 与用户 Scope 可分别生成画像,可能产生不同结论和重复 LLM 成本。 +没有投影索引意味着无法高效进行跨 Scope 副本发现与联动删除;没有分布式任务租约意味着竞争者可能重复调用模型。 +审核会阻塞同 Scope 后续自动画像窗口;Reject 的固定消费语义放弃自动重试被拒绝的证据窗口。 -## Why subject_key is family-neutral +可变、多对一 Binding 可能拆分长期记忆或混合多人的信息。应用需要管理绑定、保留消息上下文并理解 Scope 授权范围。 +生成元数据存在 BLOB 中,数据库不能直接对其建立外键或高效按字段检索,必须通过服务端验证和事务维护完整性。 -`subject_key` 首期直接等于业务 `user_id`,不引入 opaque key 或第二套身份。使用 `subject` 命名,是为了让未来 Memory、Topic Memory、Experience 等 family 可以复用同一 Root 寻址与 Root-local Source,而无需各自定义用户键。 +# Rationale and alternatives -## Why a ProfileContent wrapper instead of raw BLOB bytes +## Reuse scope bindings and ordinary scopes -当前 Artifact Repository 要求 family content 是 Pydantic Model,通用 `ArtifactRevision.content` 也是 object。使用 `ProfileContent` 把 Markdown 编码进现有 BLOB,可以不修改共享表和通用响应形状。直接写裸 Markdown bytes 会扩大到 Artifact Repository codec、运行时记录和 OpenAPI 的联合响应类型,首期没有必要。 +现有 Binding 已表达外部业务标识到 Scope 的映射。固定 integration、首期 user kind 加 subject_key 足够支持主体寻址。 +管理端保持可变映射符合现有抽象;自动双写只采用 ensure,避免普通数据写入意外换绑。额外的 Root 类型、反向唯一约束和 +主体专属 CRUD 会增加管理语义,首期没有必要。 -## Why a daily Cron plus manual Generate +## One policy table and existing blobs -每天低峰批处理能合并高频 Source,降低 LLM 调用量和并发压力;手工 Generate 为需要即时画像的业务提供明确出口。默认时间是策略而不是 Source/Artifact 语义,部署可调整。 +Policy 承担配置与唯一待审指针,需要原子 CAS,现有 Scope settings 并不是任意 JSON 配置表,不能直接容纳这些字段。 +Revision 与 Candidate 元数据属于已有对象的类型化内容,使用现有 BLOB 足够。完整处理状态可从 Policy、Cursor、 +Source journal 和 Candidate 重建,因此不新增 pending、lease、projection、revision metadata 或 candidate metadata 表。 -## Why no Claim categories +## Dedicated subject write convenience -首期的主要消费者需要一份可直接注入上下文、可由人编辑的画像文档。将内容细分为固定 Claim category 会扩大抽取、Schema、迁移和审核复杂度。完整 Markdown 更适合先验证用户价值;以后如需结构化检索,可以从 Artifact Revision 建立可重建索引,而不改变事实源与制品身份。 +两次基础 Source Create 不能保证一起成功。专用双写入口沿用基础 API 的内容和返回模型,复用事务内 repository, +提供原子性,同时保留原单写入口。任意 scope_ids 批量写入接口不能表达主体绑定解析,本 RFC 不扩大为通用批量操作。 # Prior art -PowerContext 已有设计为本 RFC 提供了可复用的基础: - -- [RFC 0019](0019_local_source_memory_runtime.md) 定义 Source journal、消费 Cursor 与本地 Runtime 事务边界; -- [RFC 0050](0050_artifact_candidate_review_inbox.md) 定义不可变 Candidate 与审核状态机; -- [Topic Memory RFC](0000_topic_memory.md) 定义通用 Artifact processing pending、lease、Supervisor 与固定 Source Window; -- [RFC 1345](1345_scope_organization_and_agent_integration.md) 定义 Scope 的组织、隔离和共享语义; -- [RFC 1437](1437_source_artifact_rest_api.md) 定义 Source 和 Artifact 的公开身份、Create、Replace 与 Revision API。 - -本 RFC 复用这些机制,不为 Profile 建立第二套 Source、Artifact、Candidate 或后台任务身份空间。 - -[TencentDB Agent Memory 的官方 README](https://github.com/Tencent/TencentDB-Agent-Memory/blob/main/README.md) -描述了分层长期记忆与 Persona;[OpenViking Session 官方文档](https://github.com/volcengine/OpenViking/blob/main/docs/en/concepts/08-session.md#memory-extraction) -描述了异步 Memory Extraction、用户记忆空间和 `profile.md`。这些具体设计为后台分层处理、checkpoint、用户 Root -与读取已有画像后更新的工程取舍提供参考。 - -本 RFC 只借鉴异步、游标和读取旧画像后增量生成的工程思路,不沿用它们的身份模型。PowerContext 的 `subject_key <-> root_scope_id`、共享 Scope 双写和权限边界由本文独立定义。 +- PowerContext [基础 REST API](1437_source_artifact_rest_api.md)提供 Source/Artifact 身份、原子提交、ETag 和 lineage_only; + [Scope RFC](1345_scope_organization_and_agent_integration.md)提供普通 Scope 与 Binding。 +- [Candidate Review RFC](0050_artifact_candidate_review_inbox.md)提供候选版本与审核生命周期; + [Topic Memory RFC](0000_topic_memory.md)提供独立 Source-window consumer 的参考。本设计不依赖其拟新增的任务表。 +- [TencentDB Agent Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory#technical-implementation)的分层异步处理, + 以及 [OpenViking Session](https://github.com/volcengine/OpenViking/tree/main/openviking/session)的会话处理, + 为证据累积后更新长期记忆提供参考;本设计采用 PowerContext 自己的 Scope、Cursor 和事务契约。 # Unresolved questions -首期功能与身份模型已经确定。RFC 合并前仍须明确 Root Source 与 Origin Source 的最小一致删除语义:删除或遗忘任一端时, -实现必须通过 `pc_subject_source_projections` 找到另一端并在同一授权操作中处理,不能让 Profile 后续继续消费已被要求 -遗忘的副本。物理删除、逻辑墓碑、已生成 Revision 的保留与审计规则需要与项目统一的数据删除协议对齐。 - -下列问题不阻塞本 RFC 合并,需在实际需求明确后独立设计: - -- 匿名用户转正式用户、账号别名、账号合并与 `subject_key` 迁移; -- HTTP Source Create 的跨请求 `Idempotency-Key`; -- 从 Profile Revision 派生 Claim 级查询、引用或风险分析索引; -- Profile 以外的 Artifact Family 如何选择并消费 Subject Root Source。 +首期行为以本文为准,不将实施所需的一致性决策留给调用方。运行参数如模型超时和部署并发上限由现有部署配置约束。 +跨 Scope Source 删除与遗忘、绑定变更后的数据迁移、强反向唯一性、审核拒绝后的显式重新提案,以及全 Family +Context 聚合都不属于本 RFC,应有独立设计;不暗示这些能力已经由双写或 Binding 提供。 # Future possibilities -后续 Artifact Family 可以注册自己的 Root-local Source processing binding,在不修改 `pc_sources` 或 -`pc_artifacts` 通用身份的前提下,把用户级 Memory、Topic Memory、Experience 或 Skill 派生到 Subject Root -及其真实子 Scope。是否启用这些派生能力应由各 Family 的独立设计决定。 - -Profile Markdown 可以产生可重建的结构化检索索引,用于段落级召回、冲突提示或证据定位。该索引应始终以不可变 -Profile Revision 和精确 Source lineage 为输入,不成为新的事实源,也不改变 Profile 的单一 Markdown 内容契约。 - -Subject Context 聚合可以继续演进 family quota、冲突解释、渐进式展开和可观察性,但必须维持逐 Scope、逐 Artifact -授权以及“共享业务 Scope 不因用户参与而自动进入 Root 子树”的边界。 - -在通用 Source 创建幂等、主体迁移和数据遗忘协议分别稳定后,Subject Root 路由可以复用这些能力,进一步降低 -网络重试、账号生命周期与原文双写带来的运营成本。 +可以扩展 subject_type 的受支持值,并继续复用 Scope Binding,而不改变 Profile singleton 身份。 +未来可为所有 Family 引入统一的处理策略、任务租约和跨 Scope Source 复制关系;应由各自的需求和 RFC 驱动, +不作为首期 Profile 的隐式依赖。若需要细粒度事实审核或永久屏蔽被拒绝内容,应单独设计结构化事实与治理模型。 From 2eff699476c9508aeecbad62c80cf5339f1db2ac Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Mon, 7 Sep 2026 22:41:15 +0800 Subject: [PATCH 4/4] docs(rfc): clarify profile scheduling and publication limits --- docs/en/rfcs/1485_profile_artifact.md | 13 +++++++++++++ docs/zh/rfcs/1485_profile_artifact.md | 11 +++++++++++ 2 files changed, 24 insertions(+) diff --git a/docs/en/rfcs/1485_profile_artifact.md b/docs/en/rfcs/1485_profile_artifact.md index ad0e766280..6f98437f36 100644 --- a/docs/en/rfcs/1485_profile_artifact.md +++ b/docs/en/rfcs/1485_profile_artifact.md @@ -316,8 +316,20 @@ create an automatic Revision. Base manual Replace retains its existing behavior successful call. Human confirmation is a whole-Revision generation signal; it does not establish paragraph-level confirmation. Later explicit Source evidence may still update the corresponding content. +## Cross-Scope publication + +Profiles cannot be copied or published across Scopes. Existing `POST /v1/artifact-publications` requests whose source +family is `profile` return HTTP 422, code `artifact_publication_unsupported`, and `details.family=profile`, whether +or not the target Scope already has a Profile. Rejected requests and retries create no target Artifact, publication, +or Profile policy and do not change existing Profiles. Python/SDK publication uses the same rule. Other supported +Families retain their behavior; no new copy endpoint is introduced. Target Profiles are maintained through their own +Scope's generation flow or existing Create/Replace operations. + ## Daily scheduling and source consumption +Background scheduling is independently controlled by `RuntimeConfig.profile_schedule_enabled`, defaulting to false. +Configuring a generation model does not implicitly enable scheduling. When enabled, use the default time and startup +catch-up scan below. Manual Flush remains available without scheduling or a background principal. Reuse the APScheduler sidecar table and add a Cron job. Add no durable pending, lease, or business job tables. Page enabled Scopes in `pc_profile_policies` and compare `pc_source_journal_heads.position` with the `profile-source-window` Cursor in `pc_source_cursors`. A missing Cursor means sequence=0. @@ -709,6 +721,7 @@ and no artifact/candidate_id from the discarded result. Other numeric response f | Scope Create/Get/List and Binding Set/Clear | Unchanged contract; the new endpoint uses internal insert-only ensure | | Scope Binding Resolve | Add allow_default=true; subject queries pass false to prohibit fallback on a miss | | Artifact Create/Get/Get Revision/List/Replace | Add profile to Family enums, input unions, and Family writer; reuse paths | +| Artifact publication / copy | Keep the existing path and request shape; source family profile returns 422 artifact_publication_unsupported with no target writes; other Families retain their behavior | | Candidate Get/List/Revise/Approve/Reject | Add Profile proposal and committer; coordinate Profile Policy/Cursor | | Artifact Access Profile, capabilities/readiness, internal authorization repository | Register/report profile and support transactional permission bootstrap without new actions or public management changes | | RuntimeConfig and scheduler registration/configuration | Add Profile Cron configuration and scan callback using existing sidecar | diff --git a/docs/zh/rfcs/1485_profile_artifact.md b/docs/zh/rfcs/1485_profile_artifact.md index 892a8e3a19..8115487ce0 100644 --- a/docs/zh/rfcs/1485_profile_artifact.md +++ b/docs/zh/rfcs/1485_profile_artifact.md @@ -282,8 +282,18 @@ Candidate 的窗口及生成器字段是服务端只读字段,Revise 请求使 基础人工 Replace 仍保持每次成功创建 Revision 的既有语义。人工确认优先仅是整篇 Revision 的生成参考, 不声称能识别某段文字曾被人工确认;后续明确的新 Source 仍可更新相应内容。 +## Cross-Scope publication + +画像不支持跨 Scope 复制或发布。现有 `POST /v1/artifact-publications` 在源制品的 family 为 `profile` 时, +无论目标 Scope 是否已有画像,均返回 HTTP 422,错误码 `artifact_publication_unsupported`, +`details.family` 为 `profile`。请求及其重试均不创建目标 Artifact、发布记录或画像策略,也不改变已有画像。 +Python/SDK 的发布入口复用同一规则。其他支持复制的制品保持原行为;不新增复制接口。 +目标 Scope 的画像只能通过本 Scope 的生成流程或既有 Create/Replace 接口维护。 + ## Daily scheduling and source consumption +后台调度由 `RuntimeConfig.profile_schedule_enabled` 独立控制,默认关闭;配置生成模型不隐式启用调度。 +开启后采用下述默认时间和启动补偿扫描;手动 Flush 不受此开关影响,也不要求后台 Principal。 复用现有 APScheduler sidecar 表,增加 Cron job;不引入 durable pending、lease 或 job 业务表。 任务分页扫描 `pc_profile_policies` 中启用的 Scope,比较 `pc_source_journal_heads.position` 与该 Scope 在 `pc_source_cursors` 的 `profile-source-window` Cursor。缺失 Cursor 视为 sequence=0。 @@ -648,6 +658,7 @@ Flush 的 processed_source_count 为本次读取窗口中的 eligible Source 数 | Scope Create/Get/List、Binding Set/Clear | 契约不变;新入口内部使用 insert-only ensure,不改管理行为 | | Scope Binding Resolve | 增加 allow_default=true;主体查询传 false,禁止未命中时使用默认 Scope | | Artifact Create/Get/Get Revision/List/Replace | Family enum、输入联合类型、Family writer 增加 profile;仍使用现有路径 | +| Artifact publication / 复制 | 原路径和请求结构不变;源 Family 为 profile 时返回 422 artifact_publication_unsupported,无目标写入;其他制品保持原行为 | | Candidate Get/List/Revise/Approve/Reject | 增加 Profile proposal 和 committer;Profile 分支联动 Policy/Cursor | | Artifact Access Profile、capabilities/readiness、内部权限 repository | 注册并报告 profile;支持事务内授权初始化,不增加权限动作或改变公开管理语义 | | RuntimeConfig、scheduler register/configure | 增加 Profile Cron 配置和扫描回调,沿用现有 sidecar |