Files
Assistant/architecture/GEN2_CANONICAL_DATA_MODEL.md
2026-08-29 01:53:27 +03:00

4210 lines
94 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Домовой — Canonical Data Model Gen2
**Статус:** proposed canonical semantic/data model for Architecture Generation 2
**Дата:** 2026-08-29
**Основание:** `GEN2_TARGET_ARCHITECTURE.md`, `DOMOVOY_GEN2_GAP_MAP.md`, Architecture Generation 1 contracts/migrations и принятая Конституция Домового.
**Назначение:** определить, какие данные Gen2 считаются каноническими, кто ими владеет, как они версионируются, стареют, связываются, извлекаются в память и мигрируют из V1.
---
# 0. Решение уровня модели данных
Gen2 **не создаёт одну универсальную таблицу памяти** и не переносит все сущности в generic `Entity + JSON`.
Модель строится из двух уровней:
```text
STRICT OPERATIONAL CORE EVOLVING SEMANTIC WORLD
─────────────────────── ────────────────────────
Identity Interaction evidence
Authority Situation / Focus
Commit World referents/vocabulary
Continuity state Epistemic knowledge
Recovery Experience
Audit Skills / Reflexes
Configuration
SELF
Search projections
```
Ключевое правило:
> **Расширяемость достигается не отсутствием схемы, а возможностью добавлять новые типизированные и версионируемые определения поверх маленького стабильного meta-kernel.**
При этом:
- факты выполнения внешнего действия остаются строго типизированными;
- raw evidence не переписывается при появлении лучшей модели;
- derived knowledge может быть переоценено и superseded;
- embeddings, search index и собранный model context никогда не являются source of truth;
- у mutable canonical concept ровно один semantic owner;
- cross-owner ссылки не создают cross-owner ownership.
---
# 1. Законы Gen2 Data Model
## 1.1 Canonical owner один
Для каждого mutable semantic concept существует один owner.
Примеры:
```text
HumanUtterance -> Interaction
FocusFrame -> Situation
WorldObject -> World
Observation/Claim -> Epistemics
Goal/Task -> Work
ProspectiveItem -> Continuity
Skill/Reflex -> Capability
SettingAssignment -> Configuration
CompetenceAssessment -> SELF
ActionAttempt -> Commit
Artifact -> Artifact
```
Другой owner хранит только typed reference и собственный смысл вокруг него.
---
## 1.2 История не переписывается молча
Gen2 различает четыре класса данных.
### A. Immutable evidence
После записи содержание не изменяется:
- HumanUtterance content;
- SourceSnapshot;
- SourceExcerpt;
- raw Observation;
- immutable Artifact version;
- ActionProposal;
- ExecutionReceipt;
- ExperienceRecord;
- evidence attachment.
Исправление создаёт новую запись и relation/supersession, а не меняет прошлое.
### B. Versioned semantic records
Определение или оценка получает новую revision:
- FocusFrame;
- FacetDefinition;
- RelationDefinition;
- BeliefAssessment;
- Episode;
- Skill;
- Reflex;
- SettingDefinition;
- SettingAssignment;
- WeaknessPattern;
- CompetenceAssessment family;
- ConsequenceAssessment.
Старые revisions остаются читаемыми.
### C. Mutable operational heads + append-only transition ledger
Для state machines нужен быстрый current head, но переходы сохраняются:
- Goal/Task;
- LongRunningWork;
- ProspectiveItem;
- AttentionItem;
- ActionAttempt;
- DevelopmentGate;
- Focus activation state.
Текущая строка/head может обновляться optimistic revision, но каждый существенный переход должен иметь audit/transition record.
### D. Rebuildable projections
Можно удалить и построить заново:
- PersonalMemory compatibility view;
- vector embeddings;
- FTS/search index;
- entity adjacency index;
- temporal index;
- positive/negative experience index;
- current knowledge view;
- current FocusStack view;
- EffectiveConfiguration;
- SELF aggregate dashboard;
- ModelContext;
- hot/warm/cold memory tiers as indexes.
Проекция никогда не становится единственным местом, где существует смысл.
---
## 1.3 Memory != storage table
Термин **Memory** в Gen2 обозначает способность восстановить нужную часть прошлого и текущего состояния.
Он не обозначает отдельный bounded context и не означает таблицу `memory_items`.
Memory Retrieval читает через owner contracts:
```text
Interaction
Situation
World
Epistemics
Work
Continuity
Capability
Configuration
SELF
Artifact
```
и строит task-specific context.
---
## 1.4 Truth != latest value
Новое значение не обязано автоматически уничтожать старое.
Пример:
```text
2026: Company A / UNF structure = V1
2027: Company A / UNF structure = V2
```
Обе записи могут быть верны в своём valid-time/version scope.
Gen2 хранит:
- когда это наблюдали;
- к какой версии/окружению относится;
- когда это считалось действующим;
- чем подтверждено;
- что supersede/contradict эту запись.
---
## 1.5 Freshness != deletion
Старение знания влияет прежде всего на **право использовать его как текущую истину**, а не на физическое существование записи.
Старое знание может быть:
- текущим;
- допустимым с предупреждением;
- историческим;
- аналогией;
- стартовой гипотезой;
- слишком старым для конкретной задачи.
---
## 1.6 Scope before similarity
До semantic/vector ranking применяются hard filters:
1. Principal/data access;
2. required ContextScope bindings;
3. explicit organization/environment/system/database/repository constraints;
4. known version constraints;
5. sensitivity/data-policy restrictions.
Только после этого применяются semantic similarity, recency и другие ranking signals.
---
## 1.7 Creator != Evaluator
Ни Skill, ни Reflex, ни новая модель, ни self-written code не могут сами объявить себя validated/trusted/better без внешнего evidence.
---
# 2. Общие примитивы данных
Эти примитивы являются техническими value objects. Они не являются generic domain entities.
## 2.1 Stable ID
Сохраняется действующий принцип `platform/ids`:
```text
128-bit cryptographically random opaque ID
```
Правила:
- ID не содержит domain meaning;
- каждый bounded context оборачивает его в strong semantic type;
- stable ID живёт через все revisions объекта;
- revision не кодируется внутри ID;
- historical refs не переписываются после merge/split;
- bare generic ID не передаётся через domain API.
Пример:
```go
type FocusFrameID ids.ID
type WorldObjectID ids.ID
type SkillID ids.ID
```
---
## 2.2 Revision
Для versioned aggregate:
```text
Revision uint64, starts at 1
```
Новая revision immutable.
Current head хранит только:
```text
stable_id
current_revision
current_state where needed
updated_at
```
Запись новой revision требует expected-current-revision guard.
---
## 2.3 Time primitives
Семантически используется один UTC instant.
```text
Instant = Unix milliseconds UTC
```
Если PostgreSQL хранит одновременно `BIGINT` и `TIMESTAMPTZ`, только одно значение является authoritative, второе должно быть generated/derived.
Различаются:
- `recorded_at` — когда Домовой записал record;
- `observed_at` — когда произошло/наблюдалось событие;
- `captured_at` — когда зафиксирован raw source snapshot;
- `valid_from` / `valid_until` — когда утверждение относится к миру;
- `verified_at` — когда evidence было повторно проверено;
- `effective_from` / `effective_until` — когда настройка/версия действует.
Нельзя заменять эти понятия одним `created_at`.
---
## 2.4 Cross-owner SemanticRef
Физическое cross-owner хранилище не имеет FK/JOIN ownership.
Для transport/storage используется технический reference envelope:
```text
SemanticRef
owner_namespace
semantic_kind
stable_id
revision? // optional exact evidence binding
```
В domain contracts он оборачивается в конкретный typed ref.
Нельзя создавать API:
```go
SaveAny(ref SemanticRef, payload any)
```
`SemanticRef` разрешает ссылку, а не универсальный CRUD.
---
## 2.5 Principal data realm
Все user-specific canonical semantic records должны быть привязаны к `PrincipalID`, если они не являются глобальным schema definition.
Это позволяет позже выразить:
- личную память владельца;
- отдельного члена семьи;
- shared family principal;
- рабочий principal;
- публичное/system-defined vocabulary.
`PrincipalID` не заменяет AuthorityScope.
---
## 2.6 SensitivityClass
Минимальная классификация:
```text
PUBLIC
PRIVATE
RESTRICTED
SECRET_REFERENCE
```
Secret value никогда не является обычным semantic payload.
`SECRET_REFERENCE` означает reference/locator в Secrets boundary, а не сам секрет.
Context projection вычисляет совместимость с выбранным DataPolicy до передачи модели.
---
# 3. ContextScope и Focus primitives
Gen2 окончательно разделяет:
```text
AuthorityScope = что разрешено
ContextScope = о чём/где/с чем сейчас работаем
```
## 3.1 ContextScope
`ContextScope` — Situation-owned versioned value.
```text
ContextScope
ID
PrincipalID
Revision
Bindings[]
RecordedAt
```
`ContextBinding`:
```text
RoleKey
TargetRef
MatchPolicy
Provenance
ConfidenceMillis
SourceRef?
```
### MatchPolicy
```text
REQUIRED // candidate outside binding excluded before similarity
PREFERRED // strong positive ranking signal
RELATED // association, not hard filter
EXCLUDED // explicit negative scope
```
### Core RoleKeys
Foundation defines only the most useful roles:
```text
PERSON
ORGANIZATION
FAMILY
ENVIRONMENT
LOCATION
SYSTEM
DATABASE
REPOSITORY
BRANCH
VERSION
ACTIVITY
PROJECT
ACTIVE_ENTITY
```
Новые виды объектов не требуют новой колонки: `TargetRef` может ссылаться на новый `WorldObject`.
RoleKey registry остаётся Situation semantic vocabulary. Добавление новых core routing roles требует Situation contract revision; произвольный Skill не может тихо создать новый hard-filter role.
---
## 3.2 FocusFrame
```text
FocusFrame
ID
PrincipalID
ActorID
Revision
AuthorityScopeRef
ContextScopeRef + exact revision
GoalRef?
TaskRef?
SourceUtteranceRef?
Provenance
ConfidenceMillis
State
ParentFrameRef?
ActivatedAt
SuspendedAt?
ExpiredAt?
RecordedAt
```
State:
```text
CANDIDATE
ACTIVE
SUSPENDED
EXPIRED
SUPERSEDED
```
Provenance:
```text
EXPLICIT_HUMAN
USER_CONFIRMED
INHERITED
ENTITY_REFERENCE
TASK_REFERENCE
REPOSITORY_REFERENCE
ENVIRONMENT_OBSERVATION
INFERRED
```
---
## 3.3 FocusTransition
Append-only:
```text
FocusTransition
TransitionID
FrameID
FromRevision
ToRevision
Operation // ACTIVATE/SUSPEND/RESUME/SUPERSEDE/EXPIRE
CauseRef
RecordedAt
```
`FocusStack` является Situation-owned rebuildable projection из FocusFrame + transitions.
Короткое отвлечение создаёт child/temporary frame и suspend/resume, а не уничтожает рабочий контекст.
---
# 4. World Model canonical data
World — registry referents и extensible typed vocabulary. World **не владеет фактическими значениями свойств мира**.
## 4.1 WorldObject
```text
WorldObject
ID
PrincipalID
KindDefinitionRef
KindRevision
LifecycleState
CreatedAt
```
Lifecycle:
```text
ACTIVE
MERGED
SPLIT
RETIRED
UNKNOWN_IDENTITY
```
Примеры WorldObject:
- человек Иван;
- Company A;
- база Company A / UNF production;
- ATLAS repository;
- living-room TV;
- street camera;
- комната;
- автомобиль;
- физическое место.
WorldObject означает **referent**, а не «таблицу всех его истинных свойств».
---
## 4.2 WorldObjectKindDefinition
Versioned schema definition:
```text
WorldObjectKindDefinition
KindKey
Revision
DisplayName
ParentKindRef?
Lifecycle
DefinitionDigest
RecordedAt
```
Примеры:
```text
PERSON
ORGANIZATION
SOFTWARE_SYSTEM
DATABASE
REPOSITORY
DEVICE
ROOM
LOCATION
VEHICLE
```
Новая capability может предложить новый kind через governed schema registration; она не получает право произвольно менять существующие definitions.
---
## 4.3 WorldAlias
```text
WorldAlias
ID
PrincipalID
WorldObjectID
Namespace
AliasValue
NormalizedValue
SourceRef
EvidenceRefs[]
State
RecordedAt
```
State:
```text
CANDIDATE
CONFIRMED
REJECTED
RETIRED
```
Например:
```text
"Иван"
"Ваня"
Telegram user id
phone contact id
CRM counterparty/contact id
```
Alias не объединяет объекты автоматически.
---
## 4.4 FacetDefinition
FacetDefinition описывает **какое свойство возможно выразить**, но не его текущее значение.
```text
FacetDefinition
ID
Namespace
Key
Revision
ApplicableKindRefs[]
ValueTypeSpec
DefaultVolatilitySpec?
Description
Lifecycle
SupersedesRevision?
RecordedAt
```
Пример:
```text
namespace = onec.configuration
key = configuration_version
value = STRING
```
или:
```text
namespace = device.air_purifier
key = filter_resource_percent
value = DECIMAL
```
---
## 4.5 RelationDefinition
```text
RelationDefinition
ID
Namespace
Key
Revision
SourceKindConstraints[]
TargetKindConstraints[]
Directionality
Cardinality
InverseRelationRef?
DefaultVolatilitySpec?
Lifecycle
RecordedAt
```
Примеры:
```text
WORKS_WITH
BELONGS_TO
LOCATED_IN
CONNECTED_TO
DEPENDS_ON
USES_DATABASE
```
Факт `A CONNECTED_TO B` хранится не в World, а как epistemic proposition/evidence.
---
## 4.6 Typed Value Algebra
Для extensible semantic values используется ограниченный algebra:
```text
STRING
INTEGER
DECIMAL
BOOLEAN
TIME
DURATION
ENUM
REFERENCE
BINARY_REF
LIST<T>
STRUCT<field definitions>
```
`ValueTypeSpec` является рекурсивным typed AST, а не arbitrary JSON schema.
Физически payload может сериализоваться JSONB, но только как **encoding уже проверенного TypedValue**.
Domain API не принимает `map[string]any`.
Каждый encoded value хранит:
```text
schema_definition_id
schema_revision
value_type_fingerprint
payload
```
и должен повторно валидироваться при чтении/migration.
---
## 4.7 Identity Resolution
World владеет решением referent identity, но решение всегда evidence-backed.
```text
IdentityResolutionDecision
ID
PrincipalID
CandidateObjectRefs[]
Decision // SAME / DISTINCT / MERGE / SPLIT / UNRESOLVED
EvidenceRefs[]
ConfidenceMillis
DecidedAt
Revision
```
### Merge
Исторические refs не переписываются.
Создаётся lineage:
```text
old A ----\
-> canonical C
old B ----/
```
Resolver может вернуть current canonical ref, но evidence продолжает указывать исходный ID.
### Split
Ошибочное объединение обратимо через split lineage. Новые записи используют successor refs; старые записи не переписываются молча.
---
# 5. Epistemics Gen2 — evidence, propositions and knowledge
Gen2 не создаёт отдельный canonical `KnowledgeItem`.
То, что в разговоре называется «знанием», является результатом:
```text
raw source
-> Observation
-> Claim/Proposition
-> BeliefAssessment
-> task-relative FreshnessAssessment
```
`BeliefAssessment` может считаться knowledge retrieval candidate, но raw evidence остаётся отдельно.
---
## 5.1 Source
Сохраняется существующий смысл Source/Snapshot/Excerpt и расширяется до любых ingress sources.
```text
Source
ID
PrincipalID
SourceKind
LocatorRef
DisplayName
Publisher/Origin?
WorldObjectRef?
SensitivityClass
RecordedAt
```
SourceKind примеры:
```text
AUTHENTICATED_HUMAN
WEB_RESOURCE
REPOSITORY
DATABASE
DEVICE_SENSOR
PHONE_CALL
EMAIL
CALENDAR
FILE
CAMERA
MICROPHONE
SYSTEM_RUNTIME
EXECUTOR
```
`LocatorRef` не обязан быть публичным URL. Secret-bearing locator хранит только safe reference.
---
## 5.2 SourceSnapshot
Immutable evidence boundary:
```text
SourceSnapshot
ID
PrincipalID
SourceID
ArtifactRef?
ContentDigest
CapturedAt
SourceVersionRef?
AcquisitionMethod
SensitivityClass
```
Важно: `Freshness=CURRENT/STALE` **не является постоянным каноническим свойством snapshot**.
V1 поле Freshness на snapshot мигрирует как historical assessment/evidence, а Gen2 freshness вычисляется task-relative.
---
## 5.3 SourceExcerpt
```text
SourceExcerpt
ID
SnapshotID
ArtifactRangeRef?
Text?
StartOffset?
EndOffset?
ContentDigest
```
Large binary/video/audio evidence не копируется в text tables. Excerpt может ссылаться на Artifact segment/time range.
---
## 5.4 Observation
Observation означает «что было непосредственно зафиксировано/извлечено из source».
```text
Observation
ID
PrincipalID
SourceSnapshotRef
SourceExcerptRef?
ContextScopeRef?
ObservedAt
RecordedAt
ObservationKind
Payload
ExtractorRef?
ExtractionConfidenceMillis?
```
ObservationKind foundation:
```text
TEXT
STRUCTURED_VALUE
RELATION_CANDIDATE
STATE_CHANGE
EVENT
EXECUTION_RECEIPT_OBSERVATION
```
`ExtractionConfidence` оценивает качество извлечения, а не истинность мира.
Пример:
```text
Audio segment -> STT extracted "позвонить Ивану в пятницу"
```
Высокая STT confidence не означает автоматически, что это обязательство пользователя.
---
## 5.5 Proposition
Для машинно используемых знаний Gen2 вводит structured proposition.
```text
Proposition
PropositionKind
SubjectRef
PredicateRef?
ObjectValue?
ObjectRef?
Qualifiers[]
TextFallback?
```
### PropositionKind
```text
WORLD_FACET
WORLD_RELATION
OWNER_DEFINED
TEXTUAL
```
Пример world facet:
```text
SubjectRef = WorldObject CompanyA_UNF
PredicateRef = FacetDefinition onec.configuration/configuration_version@3
ObjectValue = "1.6.28"
```
Пример relation:
```text
SubjectRef = Ivan
PredicateRef = RelationDefinition WORKS_WITH@2
ObjectRef = ProjectA
```
Structured proposition предпочтителен, если vocabulary известен.
Free text разрешён для неизвестных понятий, но не должен быть единственной машинной основой high-risk mutation.
---
## 5.6 Claim
Claim — утверждение, которое может быть истинным или ложным.
```text
Claim
ID
PrincipalID
Proposition
StatementText
SourceKind
ObservationRefs[]
SourceUtteranceRefs[]
ContextScopeRef?
TemporalApplicability
SubjectVersionRefs[]
ClaimState
RecordedAt
```
ClaimState:
```text
UNVERIFIED
SUPPORTED
REJECTED
CONFLICTED
UNKNOWN
SUPERSEDED
```
Claim может быть создан из:
- human assertion;
- trusted sensor observation;
- research extraction;
- inference/cognition;
- reprocessing old Artifact.
Но source chain всегда сохраняется.
---
## 5.7 BeliefAssessment
Belief Gen2 — не «вера модели», а evidence-backed current assessment конкретного Claim/Proposition.
```text
BeliefAssessment
ID
PrincipalID
ClaimRef
Revision
State
ConfidenceMillis
SupportingEvidenceRefs[]
ContradictingEvidenceRefs[]
TemporalProfile
SourceReliabilityAssessmentRefs[]
AssessedAt
SupersedesAssessmentRef?
```
State:
```text
PROVISIONAL
VERIFIED
CONFLICTED
REJECTED
UNKNOWN
HISTORICAL
```
Новая оценка создаёт новую revision/assessment; прошлое assessment не стирается.
---
## 5.8 Knowledge не является новой таблицей
Для retrieval понятие knowledge определяется как query:
```text
BeliefAssessment
WHERE state in task-allowed states
AND ContextScope compatible
AND temporal/version applicability compatible
AND data access allowed
```
Поэтому не вводится `knowledge_items` с копиями Claim text.
Current knowledge view — projection.
---
# 6. Temporal applicability, freshness и скорость устаревания
Это один из фундаментальных элементов Gen2.
## 6.1 TemporalApplicability
```text
TemporalApplicability
ObservedAt?
ValidFrom?
ValidUntil?
LastVerifiedAt?
VolatilitySpec
VersionBindings[]
```
`ValidUntil` отсутствует, если неизвестен, а не означает «вечный».
---
## 6.2 VolatilitySpec
Volatility описывает ожидаемую скорость изменения знания.
```text
VolatilityMode
IMMUTABLE
VERSION_BOUND
VERY_SLOW
SLOW
MEDIUM
FAST
EPHEMERAL
CUSTOM
```
Дополнительные параметры:
```text
ExpectedChangeIntervalMillis?
RevalidateAfterMillis?
HardStaleAfterMillis?
InvalidateOnVersionChange bool
RevalidationPolicyRef?
```
Примеры:
```text
π -> IMMUTABLE
дата рождения -> VERY_SLOW / manual correction
структура конкретной УНФ -> VERSION_BOUND + MEDIUM
текущая цена -> FAST
"сервер доступен" -> EPHEMERAL
```
Не требуется выбирать идеальную математическую half-life для каждого знания. Foundation должен хранить достаточно metadata, чтобы ranking policy можно было заменить позже.
---
## 6.3 VersionBinding
```text
VersionBinding
SubjectRef
VersionRef
MatchMode
```
MatchMode:
```text
EXACT
COMPATIBLE_FAMILY
AT_OR_BEFORE
UNKNOWN
```
Например знание о структуре УНФ может быть привязано к конкретному configuration snapshot/version.
---
## 6.4 TaskFreshnessRequirement
Freshness requirement принадлежит Work/task requirements, а не самой памяти.
```text
TaskFreshnessRequirement
Mode
MaximumAgeMillis?
RequiredVersionRefs[]
RevalidationRequired bool
FallbackPolicy
```
Mode:
```text
ANY
PREFER_CURRENT
REQUIRE_CURRENT
REQUIRE_WITHIN_AGE
REQUIRE_VERSION_MATCH
LIVE_REQUIRED
```
FallbackPolicy:
```text
ALLOW_STALE_WITH_DISCLOSURE
USE_AS_HYPOTHESIS_ONLY
WAIT_FOR_SOURCE
ASK_OWNER
STOP_WITH_UNKNOWN
```
Это позволяет выразить пользовательский сценарий:
> «Свежая структура УНФ недоступна. Есть прошлогоднее знание. Могу использовать его как гипотезу с предупреждением или дождаться live-доступа.»
---
## 6.5 FreshnessAssessment
Freshness state вычисляется **для конкретной задачи**:
```text
FreshnessAssessment
SourceKnowledgeRef
TaskRef
State
Reason
AgeMillis
VersionMatchState
RevalidationAttemptRef?
AssessedAt
```
State:
```text
CURRENT
ACCEPTABLE
AGING
STALE
VERSION_MISMATCH
HISTORICAL_ONLY
UNKNOWN
```
По умолчанию FreshnessAssessment — derived runtime evidence. Если он важен для решения/аудита, его можно persist как Epistemics evidence, но он не заменяет TemporalApplicability.
---
## 6.6 Active revalidation
Если задача требует свежесть выше доступной памяти:
```text
retrieve old knowledge
-> detect freshness gap
-> request live/revalidation capability
-> obtain new evidence
-> new Claim/BeliefAssessment
-> continue decision
```
Если source недоступен, поведение определяется TaskFreshnessRequirement/FallbackPolicy.
Домовой не должен скрывать переход на stale memory.
---
# 7. Episode — derived episodic memory
Episode группирует связанные события/наблюдения, но не заменяет raw history.
```text
Episode
ID
PrincipalID
Revision
EpisodeKind
ContextScopeRef
StartAt
EndAt
ParticipantWorldRefs[]
ObservationRefs[]
UtteranceRefs[]
ArtifactRefs[]
GoalTaskRefs[]
Summary
GroupingEvidenceRefs[]
ConfidenceMillis
State
RecordedAt
```
EpisodeKind примеры:
```text
CONVERSATION
PHONE_CALL
WORK_SESSION
MEETING
INCIDENT
RESEARCH_SESSION
DEVICE_EVENT_SEQUENCE
```
State:
```text
PROVISIONAL
CONFIRMED
SUPERSEDED
```
Новая модель может пересобрать Episode из тех же raw observations и создать новую revision/supersession.
Raw call/audio не изменяется.
---
# 8. Experience — положительный и отрицательный опыт
Positive и Negative Experience не являются разными таблицами. Их различает Outcome/evaluation.
## 8.1 ExperienceRecord V2
Append-only:
```text
ExperienceRecord
ID
PrincipalID
SourceKind
OriginalIntentRef?
SourceUtteranceRef?
EpisodeRef?
ContextScopeRef?
GoalRef?
TaskRef?
ProblemStatement
MethodKind
MethodRef?
AttemptRef?
WhyAttempted?
ApplicabilityConditions[]
ExpectationRef?
ExpectedOutcome
ExpectedEffect?
ActualOutcome
OutcomeAssessmentRef?
OutcomeDetail
WhySucceededOrFailed?
SkillRef?
ReflexRef?
CapabilityImplementationRef?
AgentRunRef?
VerificationEvidenceRefs[]
HumanResponseRef?
CorrectionUtteranceRef?
ConfidenceMillis
RecordedAt
```
ActualOutcome сохраняет текущие классы и расширяется только отдельным contract revision.
Ключевые состояния:
```text
SUCCESS
PARTIAL_SUCCESS
FAILED
UNKNOWN
USER_CORRECTED
UNEXPECTED_OUTCOME
LOW_CONFIDENCE
OUT_OF_DISTRIBUTION
CONFLICT
STALE
```
---
## 8.2 Почему отрицательный опыт first-class
FAILED/USER_CORRECTED/CONFLICT/STALE experiences индексируются в отдельной retrieval lane.
При похожей задаче Context Compiler обязан иметь возможность запросить:
```text
what worked?
what failed?
what was corrected?
what became stale?
```
Negative experience не означает вечный запрет. `ApplicabilityConditions` и VersionBindings определяют, при каких условиях ошибка была ошибкой.
---
## 8.3 ReflectionCandidate
Сохраняется V1 смысл и расширяется context refs:
```text
ReflectionCandidate
ID
Trigger
State
SourceExperienceRef
ContextScopeRef?
Summary
EvidenceRefs[]
RequiresCognition
Revision
Lease fields
RecordedAt
```
Reflection не пишет Skills/SELF напрямую. Она создаёт evidence/proposal.
---
# 9. Source trust / reliability
Не вводится глобальный `source_trust = 0.87`.
## 9.1 SourceReliabilityObservation
Append-only Epistemics evidence:
```text
SourceReliabilityObservation
ID
PrincipalID
SourceRef
DomainScopeRef?
PropositionClass?
ComparedClaimRef?
VerificationEvidenceRef
Result
RecordedAt
```
Result:
```text
SUPPORTED
CONTRADICTED
PARTIAL
UNKNOWN
STALE
```
---
## 9.2 SourceReliabilityAssessment
Derived/versioned assessment:
```text
SourceReliabilityAssessment
ID
SourceRef
DomainMatcher
Revision
ReliabilityMillis
EvidenceRefs[]
Validity
AssessedAt
```
Один источник может иметь разные assessments по разным domains.
Например авиакомпания может быть сильным источником собственного рейса и нерелевантным источником структуры УНФ.
---
# 10. Outcome verification
Gen2 жёстко различает execution receipt и наблюдение мира.
## 10.1 ExecutionReceipt — Commit owner
Immutable:
```text
ExecutionReceipt
ID
ActionAttemptRef
ExecutorImplementationRef
ExternalOperationRef
ExternalRequestID?
RequestDigest
ResponseDigest?
DispatchAt
CompletedAt?
ExecutorResult
AmbiguityState
ReconciliationKey
RawArtifactRef?
```
ExecutorResult:
```text
ACCEPTED
REPORTED_SUCCESS
REPORTED_FAILURE
NO_RESPONSE
AMBIGUOUS
```
`REPORTED_SUCCESS` не равно verified world success.
---
## 10.2 WorldOutcomeAssessment — Epistemics owner
```text
WorldOutcomeAssessment
ID
PrincipalID
ActionAttemptRef
ExecutionReceiptRefs[]
ExpectedEffectRef
ObservationRefs[]
ClaimRefs[]
State
ConfidenceMillis
EvidenceRefs[]
AssessedAt
```
State:
```text
VERIFIED_SUCCESS
VERIFIED_PARTIAL
VERIFIED_FAILURE
UNVERIFIED
UNKNOWN
CONFLICTED
```
Пример:
```text
HTTP 200 from light API
!=
observed room light OFF
```
Continuity/Work могут удовлетворять обязательство только в соответствии с policy, которая явно говорит, достаточно ли executor receipt или требуется verified outcome.
---
# 11. Work Gen2 canonical data
Work остаётся владельцем «зачем/что делаем/как организована работа».
## 11.1 Goal V2
Сохраняется stable ID и source lineage V1.
```text
Goal
ID
PrincipalID
ActorID
SourceIntentRef
SourceUtteranceRef
AuthorityScopeRef
ContextScopeRef
DesiredOutcome
ConstraintRefs[]
State
Revision
CreatedAt
UpdatedAt
```
Project больше не обязательная колонка Goal. Project/activity определяется ContextScope binding.
---
## 11.2 Task V2
```text
Task
ID
GoalRef
PrincipalID
ContextScopeRef
ParentTaskRef?
DesiredOutcome
State
Revision
TaskRequirements
CreatedAt
UpdatedAt
```
TaskRequirements:
```text
FreshnessRequirement
QualityRequirement
LatencyBudget?
ExternalCostBudget?
ComputeBudget?
MaxAttempts?
ErrorCostClass
DataPolicyRequirement
VerificationRequirement
```
ErrorCostClass:
```text
TRIVIAL
LOW
MEDIUM
HIGH
CRITICAL
```
Эта классификация влияет на глубину проверки, но не предоставляет authority.
---
## 11.3 Work plan / graph
Сохраняются V1:
- PlanCandidate;
- WorkPlan;
- PlanStep;
- CapabilityRequirement;
- Delegation;
- AgentRun;
- AgentCheckpoint;
- AgentResult;
- Verification.
Gen2 требует, чтобы ContextScope/TaskRequirements передавались typed refs, а не только строковым summary.
Summaries остаются human/debug representation, не canonical machine semantics.
---
## 11.4 LongRunningWork / Investigation
```text
LongRunningWork
ID
PrincipalID
GoalRef
RootTaskRef
ContextScopeRef
Objective
State
Revision
Budget
CurrentCheckpointRef?
NextStep
BlockerRefs[]
CreatedAt
UpdatedAt
```
State:
```text
PLANNED
RUNNING
PAUSED
WAITING_EXTERNAL
WAITING_HUMAN
BLOCKED
COMPLETED
CANCELLED
EXHAUSTED
```
`EXHAUSTED` означает исчерпан выделенный budget, а не доказательство невозможности задачи.
### Budget
```text
WallClockBudget?
ComputeBudget?
ExternalCostMicros?
ModelCallBudget?
AttemptBudget?
Deadline?
```
Неиспользуемые поля отсутствуют, а не равны бесконечности.
---
## 11.5 InvestigationHypothesisRef
Work не создаёт собственную копию hypothesis text.
Hypothesis является Epistemics Claim/Proposition со статусом `UNVERIFIED/PROVISIONAL`.
LongRunningWork хранит:
```text
HypothesisRefs[]
FindingClaimRefs[]
ExperienceRefs[]
AttemptRefs[]
```
Это позволяет исследованию пережить смену модели.
---
## 11.6 PerspectiveSpec
Versioned Work value:
```text
PerspectiveSpec
ID
Revision
Key
ObjectiveLens
RetrievalProfileRef
EvaluationCriteria[]
CapabilityRequirements[]
OutputContractRef?
Lifecycle
```
Perspective не имеет Principal authority.
Generic presets могут быть system-defined; task-specific temporary perspective может существовать только внутри Work.
---
## 11.7 ConsequenceAssessment
Versioned Work record:
```text
ConsequenceAssessment
ID
PrincipalID
TaskRef
ProposedActionRef?
Revision
ErrorCostClass
Reversibility
AffectedRefs[]
ExpectedConsequences[]
Uncertainties[]
Mitigations[]
SimulationRequired
BackupRequired
SnapshotRequired
RecommendedConfirmationStrength
EvidenceRefs[]
RecordedAt
```
Reversibility:
```text
REVERSIBLE
REVERSIBLE_WITH_BACKUP
PARTIALLY_REVERSIBLE
IRREVERSIBLE
UNKNOWN
```
`ConsequenceAssessment` не запрещает действие и не заменяет Authority.
---
# 12. Continuity Gen2 canonical data
Continuity остаётся единственным owner future relevance.
## 12.1 Commitment
V1 уже имеет `CommitmentID`, но Gen2 делает semantic record явным.
```text
Commitment
ID
PrincipalID
AuthorityScopeRef
ContextScopeRef?
GoalRef?
TaskRef?
SourceIntentRef
SourceUtteranceRef
Summary
State
Revision
CreatedAt
SatisfiedAt?
SupersededBy?
```
State:
```text
OPEN
SATISFIED
CANCELLED
SUPERSEDED
EXPIRED
```
---
## 12.2 ProspectiveItem V2
```text
ProspectiveItem
ID
CommitmentRef?
PrincipalID
AuthorityScopeRef
ContextScopeRef?
GoalRef?
WorkRef?
SourceIntentRef
SourceUtteranceRef
Summary
TriggerSpec
State
Revision
```
### TriggerSpec algebra
Foundation должен уметь выразить не только absolute timestamp:
```text
ABSOLUTE_INSTANT
RECURRENCE
RELATIVE_TO_EVENT
CONDITION
COMPOSITE
```
Примеры:
```text
"завтра в 10"
"каждый понедельник"
"через три дня после письма"
"если ответа не будет"
"после работы, когда окажусь дома"
```
Полная event/condition engine может появиться позже, но canonical TriggerSpec уже не должен быть навсегда ограничен одной колонкой `trigger_at`.
---
## 12.3 AttentionItem / HumanResponse
Сохраняются текущие state machines.
Добавляются typed refs на ContextScope/Work where useful.
Attention не становится общей event queue.
---
# 13. Capability Gen2 — Skill, Reflex and intelligence data
## 13.1 Capability/Implementation
Существующие capability descriptor, implementation, health, binding, qualification и usage observation сохраняются.
Gen2 не объединяет Capability и Skill.
```text
Capability = что система способна выполнить
Skill = проверенный повторяемый способ решения
Reflex = оптимизированный дешёвый путь из Skill/experience
```
---
## 13.2 Skill stable identity + revisions
Вместо семантически перегруженного одного `SkillProfile` Gen2 рассматривает его как stable identity + immutable revisions.
```text
Skill
ID
PrincipalID? // system skill may be shared/system principal
Name
CreatedAt
```
```text
SkillRevision
SkillID
Revision
Description
ApplicabilitySpec
InputContractRef?
OutputContractRef?
ImplementationRef
ImplementationVersion
DependencyRefs[]
SupportingExperienceRefs[]
KnownFailureExperienceRefs[]
ValidationEvidenceRefs[]
QualityAssessmentRefs[]
EnvironmentVersionConstraints[]
LastValidatedAt
LifecycleState
SupersedesRevision?
RecordedAt
```
Lifecycle:
```text
CANDIDATE
EVALUATING
VALIDATED
DEGRADED
SUSPENDED
RETIRED
```
---
## 13.3 ApplicabilitySpec
Никаких `[]string` как основного механизма matching.
```text
ApplicabilitySpec
RequiredContextBindings[]
PreferredContextBindings[]
ExcludedContextBindings[]
RequiredWorldKinds[]
VersionConstraints[]
InputConditions[]
MinimumEvidenceFreshness?
```
InputConditions используют bounded typed condition vocabulary Skill contract, а не executable arbitrary expression из БД.
---
## 13.4 Reflex
```text
Reflex
ID
PrincipalID?
SourceSkillRef
CreatedAt
```
```text
ReflexRevision
ReflexID
Revision
SourceSkillRevision
ReflexKind
ApplicabilitySpec
ImplementationRef
ImplementationVersion
ArtifactDigest?
DependencyRefs[]
ValidationEvidenceRefs[]
KnownFailureExperienceRefs[]
ShadowPolicy
RevalidationPolicy
LastValidatedAt
LifecycleState
RecordedAt
```
ReflexKind:
```text
DETERMINISTIC_CODE
RULE
WORKFLOW
QUERY_TEMPLATE
SMALL_MODEL_CHAIN
BOUNDED_ADAPTER_OPERATION
```
Lifecycle:
```text
CANDIDATE
VALIDATING
ACTIVE
DEGRADED
STALE
SUSPENDED
RETIRED
```
---
## 13.5 ShadowPolicy
```text
ShadowPolicy
Enabled
SampleRateMillis // 0..1000
ComparatorRef
MaxShadowCostMicros?
EligibleErrorCostClasses[]
```
High-risk operations не экспериментируют на реальном mutation path. Для них shadow/replay работает на historical/sandbox data.
---
## 13.6 RevalidationPolicy
```text
RevalidationPolicy
MaxAgeMillis?
RevalidateOnDependencyRevisionChange
RevalidateOnWorldVersionChange
RevalidateAfterFailureCount?
RevalidateAfterCorrectionCount?
SampleAuditRateMillis?
```
Skill/Reflex может стать `STALE/DEGRADED`, не удаляясь.
---
## 13.7 Skill/Reflex promotion evidence
Promotion не определяется количеством удачных запусков одним условием.
Минимальный evidence bundle может включать:
- multiple ExperienceRefs;
- zero/acceptable correction rate;
- environment/version coverage;
- regression evidence;
- evaluator identity;
- comparison with previous path;
- cost/latency impact;
- rollback path для code-backed Reflex.
Exact threshold принадлежит evaluation policy, а не canonical schema.
---
# 14. Configuration Gen2 — динамические типизированные настройки
Configuration является новым canonical owner.
## 14.1 SettingDefinition stable identity
```text
SettingDefinition
ID
OwnerNamespace
StableKey
CreatedAt
```
```text
SettingDefinitionRevision
DefinitionID
Revision
DisplayName
Description
ValueTypeSpec
DefaultValue?
AllowedScopeSelectors[]
ResolutionMode
SensitivityClass
ValidationSpec
Lifecycle
SupersedesRevision?
RecordedAt
```
Lifecycle:
```text
ACTIVE
DEPRECATED
RETIRED
```
---
## 14.2 SettingAssignment
Assignments versioned/append-preserving:
```text
SettingAssignment
ID
PrincipalID
DefinitionRef + definition revision
Revision
ScopeSelector
TypedValue | SecretRef
EffectiveFrom
EffectiveUntil?
SourceKind
SourceRef
RecordedAt
Lifecycle
```
SourceKind:
```text
HUMAN_DIRECTIVE
MIGRATED_CONFIG
SKILL_DEFAULT
SYSTEM_DEFAULT
GOVERNED_CHANGE
```
Skill default не имеет приоритета над explicit human assignment.
---
## 14.3 ScopeSelector
Чтобы выразить «для Skill X в Company A использовать Y», selector должен поддерживать conjunctive context.
```text
ScopeSelector
PrincipalRef?
RequiredContextBindings[]
ActivityRef?
SkillRef?
TaskRef?
SessionRef?
TemporaryOverride bool
```
Это не arbitrary map: bindings используют ContextScope vocabulary и typed refs.
---
## 14.4 ResolutionMode
Foundation:
```text
MOST_SPECIFIC_WINS
FIRST_EXPLICIT_HUMAN_WINS
MERGE_LIST
```
Новый режим требует Configuration contract revision.
### Deterministic resolution
1. отфильтровать assignments по Principal/access;
2. исключить expired/incompatible definition revisions;
3. оставить selectors, совпадающие с current Focus/Task/Skill;
4. выбрать highest precedence tier;
5. выбрать наиболее специфичный conjunctive selector;
6. при равной специфичности и конфликте **не использовать last-write случайно** — вернуть configuration conflict;
7. explicit temporary override может победить только в разрешённом definition scope.
---
## 14.5 EffectiveConfiguration
Derived only:
```text
EffectiveSetting
DefinitionRef
Value
WinningAssignmentRef
ResolutionTrace
```
Effective config не записывается как второй source of truth.
---
## 14.6 ENV/bootstrap
После migration ENV разрешён только для bootstrap primitives:
```text
node identity bootstrap
control database locator / bootstrap locator
root secret resolver locator
minimal recovery/supervisor bootstrap
```
Ordinary provider URLs, models, project settings, skill parameters и user preferences не должны оставаться обязательными ENV config.
---
## 14.7 SecretRef
```text
SecretRef
ProviderKind
SecretID
VersionHint?
```
Secret value отсутствует в Configuration/Epistemics/Context projections.
Adapter получает разрешённый SecretRef через Secrets boundary только в момент использования.
---
# 15. SELF canonical data
SELF хранит evidence-backed модель Домового о себе, но не исполняет работу.
## 15.1 CompetenceAssessment
Append/versioned assessment:
```text
CompetenceAssessment
ID
PrincipalID
SubjectRef // Capability/Skill/Reflex/strategy
Revision
ContextMatcher
QualityMillis
ReliabilityMillis
ConfidenceMillis
CostProfileRef?
LatencyProfileRef?
EnvironmentConstraints[]
EvidenceRefs[]
LastValidatedAt
AssessedAt
SupersedesRef?
```
Score без evidence невалиден.
Компетентность context-dependent:
```text
"1C debugging with live IFCM"
!=
"1C debugging from stale memory only"
```
---
## 15.2 WeaknessPattern
```text
WeaknessPattern
ID
PrincipalID
Revision
PatternKey
ContextMatcher
FailureMode
DetectionEvidenceRefs[]
KnownTriggers[]
MitigationRefs[]
State
RecordedAt
```
State:
```text
CANDIDATE
CONFIRMED
MITIGATED
MONITORING
RESOLVED
SUPERSEDED
```
Пример:
> premature anchoring on first hypothesis for PostgreSQL numeric overflow diagnostics.
---
## 15.3 DependencyAssessment
SELF не копирует Capability dependency registry, а хранит interpreted self-view:
```text
DependencyAssessment
ID
SubjectRef
DependencyRef
ImpactClass
CurrentEffect
EvidenceRefs[]
AssessedAt
```
Это позволяет различать:
> «я не умею»
и
> «я умею, но зависимость IFCM сейчас недоступна».
---
## 15.4 ImprovementNeed
```text
ImprovementNeed
ID
PrincipalID
SubjectRef
ProblemSummary
EvidenceRefs[]
ExpectedBenefit
Priority
State
CreatedAt
```
State:
```text
OPEN
EVALUATING
PROPOSED
IN_PROGRESS
RESOLVED
REJECTED
SUPERSEDED
```
SELF не создаёт source patch напрямую; Work governed development принимает предложение.
---
## 15.5 LearningLedgerEntry
История значимых изменений интеллекта:
```text
LearningLedgerEntry
ID
PrincipalID
ImprovementNeedRef?
ObservedProblem
EvidenceRefs[]
Diagnosis
Hypothesis
ProposedChangeRef
ExpectedImprovement
EvaluationPlanRef?
ActualEvaluationRefs[]
DevelopmentGateRef?
BeforeVersionRefs[]
AfterVersionRefs[]
Decision
SideEffects[]
RollbackRef?
RecordedAt
```
Decision:
```text
PROPOSED
PROMOTED
REJECTED
ROLLED_BACK
SUPERSEDED
```
Это не заменяет git history или Work DevelopmentGate; ledger объясняет **почему интеллект изменился и стало ли лучше**.
---
## 15.6 SelfCompositionSnapshot
Durable snapshot для диагностики/version comparison:
```text
SelfCompositionSnapshot
ID
PrincipalID
RuntimeVersionRef
ActiveCapabilityBindingRefs[]
ActiveSkillRevisionRefs[]
ActiveReflexRevisionRefs[]
RetrievalPolicyVersionRef
ContextCompilerVersionRef
ConfigurationSnapshotDigest
RecordedAt
```
Это aggregate snapshot, а не owner активных versions.
---
# 16. Memory Retrieval Fabric — rebuildable projections
Memory Retrieval не владеет canonical meaning. Он строит несколько специализированных проекций.
## 16.1 RetrievalDocument
Общий projection envelope:
```text
RetrievalDocument
ProjectionID
ProjectionVersion
PrincipalID
SourceRef
ExactSourceRevision?
ContextScopeKeys[]
WorldObjectRefs[]
GoalTaskRefs[]
TemporalMetadata
VersionBindings[]
EvidenceState
ExperiencePolarity?
SensitivityClass
TextRepresentation
TokenEstimate
ContentDigest
EmbeddingRefs[]
IndexedAt
```
Это **не новая canonical memory record**.
Удаление всех RetrievalDocuments не должно уничтожить память; они перестраиваются из owners.
---
## 16.2 Независимые retrieval lanes
Минимально Gen2 проектирует отдельные lanes:
1. `RECENT_INTERACTION` — текущий разговор/соседние turns;
2. `EXACT_ENTITY` — exact WorldObject/aliases;
3. `ACTIVE_WORK` — Goal/Task/LongRunningWork;
4. `CONTINUITY` — обязательства и future relevance;
5. `VERIFIED_KNOWLEDGE` — epistemic assessments;
6. `EPISODIC` — past Episodes;
7. `POSITIVE_EXPERIENCE` — что сработало;
8. `NEGATIVE_EXPERIENCE` — ошибки, corrections, failed attempts;
9. `SKILL_REFLEX` — reusable approaches;
10. `CONTRADICTION` — evidence, меняющее/опровергающее найденное;
11. `SELF_WEAKNESS` — собственные известные failure patterns, если релевантно;
12. `CONFIGURATION` — effective settings только для task execution, не для general semantic similarity.
Нельзя заменить эти lanes одним `topK vector search`.
---
## 16.3 Ranking signals
Ranking policy versioned и заменяемый.
Возможные сигналы:
```text
hard scope compatibility
exact entity match
semantic similarity
task/goal relation
focus role match
freshness relative to task
subject-version match
source reliability
explicit human importance
recent successful usefulness
negative-experience relevance
contradiction value
episode proximity
current continuity relevance
context/token cost
```
Не требуется превращать их в одну вечную формулу.
Policy version обязательно попадает в ContextAssemblyTrace, чтобы позже понять, почему память была/не была выбрана.
---
## 16.4 Scope isolation
Алгоритм retrieval обязан выполнять:
```text
1. authenticated Principal/access filter
2. REQUIRED/EXCLUDED ContextBindings
3. explicit version constraints
4. data policy/sensitivity filter
5. candidate lane retrieval
6. ranking/rerank
```
Нельзя сначала получить top semantic hits из всех компаний и потом надеяться, что модель сама различит Company A и Company B.
---
## 16.5 Positive/Negative balanced retrieval
Для diagnostic/problem-solving tasks retrieval должен иметь budget reservation для negative experience.
Пример:
```text
Context budget 8k
verified/current facts 25%
task/current conversation 20%
skill/current method 20%
positive experience 10%
negative experience 10%
contradiction/verification 10%
reserve 5%
```
Это пример policy, не фиксированная формула.
Главное — отрицательный опыт не вытесняется автоматически более многочисленными positive similarity hits.
---
## 16.6 Contradiction pass
После предварительного выбора решения/knowledge candidate Context Compiler может выполнить отдельный pass:
```text
"что в памяти существенно противоречит выбранным сведениям?"
```
Contradiction retrieval использует proposition/entity refs и known correction/supersession relations, а не только negative cosine similarity.
---
# 17. Context Compiler V2 data contract
Context Compiler остаётся worker/service, не canonical owner.
## 17.1 ContextCompileRequest
```text
ContextCompileRequest
PrincipalID
ActorID
AuthorityScopeRef
FocusFrameRef + exact revision
ContextScopeRef + exact revision
GoalRef?
TaskRef?
TaskRequirementsRef?
IntelligenceStrategyHint?
ModelContextLimit
MaxInputTokens/Bytes
DataPolicy
Locale
RetrievalPolicyVersion
```
Model/provider выбирает Capability, поэтому compiler не принимает browser-selected provider.
---
## 17.2 Candidate contract
Каждый candidate приходит с metadata:
```text
ContextCandidate
SourceRef
SourceRevision?
Lane
ContextBindings
FreshnessMetadata
EvidenceState
Sensitivity
RelevanceSignals
Text/structured representation
EstimatedTokens
```
---
## 17.3 ContextBundle
```text
ContextBundle
BundleID? // runtime id
FocusRevision
RetrievalPolicyVersion
CompilerVersion
IncludedExcerpts[]
Omissions[]
CoverageSummary
FreshnessWarnings[]
ContradictionSummary?
RemainingBudget
```
ContextBundle не становится memory source of truth.
---
## 17.4 ContextAssemblyTrace
Чтобы Домовой мог учиться на retrieval mistakes, нужен диагностический trace.
По умолчанию он ephemeral/telemetry.
Если он стал evidence для Reflection/SELF, сохраняется как Artifact:
```text
ContextAssemblyTrace
CompilerVersion
RetrievalPolicyVersion
FocusRef
TaskRef
CandidateRefs + lane + score components
IncludedRefs
OmittedRefs + reasons
Freshness decisions
Context budget
Model strategy ref
```
Содержимое секретов в trace запрещено.
Это позволяет после фразы пользователя:
> «Я же уже говорил это раньше»
установить:
```text
memory missing?
projection missing?
scope filtered incorrectly?
retrieval ranked too low?
context budget evicted it?
model ignored included memory?
```
---
## 17.5 Iterative memory retrieval
Initial ContextBundle должен быть минимально достаточным.
Во время reasoning модель через typed capability может запросить:
```text
memory.search_failures(...)
memory.search_entity_history(...)
memory.search_commitments(...)
memory.search_old_versions(...)
```
Запрос проходит те же Principal/Scope/DataPolicy guards.
Это позволяет маленькой локальной модели работать с памятью значительно больше собственного context window.
---
# 18. Memory salience, forgetting and consolidation
## 18.1 Salience != truth
Высокая retrieval salience не делает Claim более истинным.
Salience — только вероятность быть полезным **сейчас**.
---
## 18.2 Salience signals
Derived projection может учитывать:
- freshness;
- explicit human «важно/запомни»;
- relation to active goals;
- entity proximity;
- use frequency;
- previous usefulness;
- unresolved commitment;
- failure/correction severity;
- uniqueness;
- cost of losing;
- current Focus.
Долгое неиспользование является только одним сигналом.
---
## 18.3 RetentionDirective
Если пользователь явно говорит «это обязательно запомни» или «это можно забыть», Interaction сохраняет исходную директиву, а Epistemics/Artifact может сформировать typed retention evidence/policy.
Foundation value:
```text
RetentionDirective
SourceUtteranceRef
TargetRefs[]
Class
EffectiveAt
```
Class:
```text
PINNED
LONG_TERM
NORMAL
SHORT_TERM
EPHEMERAL
FORGET_REQUESTED
```
`FORGET_REQUESTED` не означает мгновенный физический delete всех audit records. Реальная deletion/redaction policy должна учитывать operational/audit obligations и получить отдельный privacy ADR before implementation.
---
## 18.4 Consolidation
Memory может постепенно сжиматься:
```text
raw observations
-> Episodes
-> Claims/Beliefs
-> patterns
-> Experience
-> Skills
-> Reflexes
```
Consolidation **не удаляет evidence chain**, пока retention policy не разрешает archival/deletion.
Summary всегда хранит refs на source evidence.
---
## 18.5 Hot / Warm / Cold / Archive
Это storage/retrieval tier, а не epistemic status.
```text
HOT frequent/recent index
WARM normal indexed memory
COLD slow indexed/archive retrieval
ARCHIVE raw long-term evidence, may require explicit deep retrieval
```
Claim может быть VERIFIED и физически COLD.
Claim может быть STALE и физически HOT из-за текущего расследования.
---
# 19. Artifact Gen2 — raw durable memory substrate
Artifact остаётся owner больших immutable resources.
## 19.1 Artifact
```text
Artifact
ID
PrincipalID
MediaType
ContentDigest
SizeBytes
StorageLocatorRef
SensitivityClass
CreatedAt
CapturedAt?
SourceRef?
RetentionClass
```
`StorageLocatorRef` не должен раскрывать credential.
---
## 19.2 ArtifactVersion / lineage
Если содержимое изменилось — новый Artifact/version с lineage:
```text
DerivedFrom
TranscodedFrom
OCRFrom
TranscriptOf
ThumbnailOf
ReprocessedFrom
```
Новая speech/OCR/vision модель создаёт новый derived Artifact/Observation; original raw artifact не переписывается.
---
## 19.3 SegmentRef
Для audio/video/document:
```text
ArtifactSegmentRef
ArtifactID
TimeStart/TimeEnd OR Byte/Page range
Digest?
```
Это позволяет эпизоду/claim ссылаться на конкретные 20 секунд звонка вместо копирования целого часа аудио в prompt.
---
# 20. Commit and strict operational data
Gen2 сохраняет строгий V1 смысл и усиливает audit trail.
## 20.1 ActionProposal
Immutable semantic proposal.
После изменения recipient/amount/file/content/operation создаётся новая proposal identity/digest.
Подтверждение старой proposal не распространяется на новую.
---
## 20.2 AuthorizedAction
Immutable authorization evidence:
```text
AuthorizedAction
ID
ProposalRef
PrincipalID
GrantRef + exact revision
AuthorityScopeRef
AuthorizedAt
AuthorizationDigest
```
---
## 20.3 ActionAttempt
Operational aggregate:
```text
ActionAttempt
ID
AuthorizedActionRef
IdempotencyKey
ReconciliationKey
State
Revision
LatestExecutionReceiptRef?
StartedAt
UpdatedAt
```
Recommended Gen2 state semantics:
```text
CREATED
DISPATCHING
EXECUTOR_REPORTED_SUCCESS
EXECUTOR_REPORTED_FAILURE
UNKNOWN_OUTCOME
RECONCILING
CLOSED
```
Compatibility mapper может отображать V1 `SUCCEEDED/FAILED/EXECUTING` до перехода contracts.
`CLOSED` не обязано означать verified world success; closure reason должен ссылаться на policy/outcome assessment.
---
## 20.4 ActionAttemptTransition
Append-only:
```text
TransitionID
AttemptID
FromState
ToState
CauseRef
ReceiptRef?
RecordedAt
```
Blind retry после `UNKNOWN_OUTCOME` запрещён.
---
# 21. Identity and Authority data
Основные V1 types сохраняются.
## 21.1 PrincipalBinding
Identity остаётся единственным owner связи authenticated actor -> principal.
World alias на человека не даёт principal identity автоматически.
---
## 21.2 AuthorityScope
Authority Scope может быть coarse/fine-grained, но он не используется как ContextScope.
Data access и mutations проверяются against authenticated Principal/Grant/AuthorityScope.
Наличие WorldObject в Focus не предоставляет permission к нему.
---
# 22. Cross-owner access rules
## 22.1 No cross-owner DB FK
Каждый schema owner хранит внешние IDs как typed refs without FK.
Причины:
- bounded-context autonomy;
- independent migrations;
- no semantic ownership leakage;
- replay/rollback;
- no cross-owner SQL joins as business logic.
---
## 22.2 No cross-owner write
Work не UPDATE'ит Epistemics.
Epistemics не UPDATE'ит Capability.
SELF не UPDATE'ит Skill status.
Configuration не UPDATE'ит World.
Связь идёт через typed command/contracts.
---
## 22.3 Read models may combine refs
Memory/Context projections могут объединять data from multiple owners, но projection read-only/rebuildable.
Projection cannot be mutated to change canonical state.
---
# 23. Physical PostgreSQL layout target
Это logical target, не готовый migration script.
Recommended schemas:
```text
identity
authority
interaction
situation
world
epistemics
work
continuity
capability
configuration
self_model
commit
artifact
projection_* // rebuildable/read-only roles
```
Каждый canonical schema имеет отдельную DB role/write privilege, продолжая V1 ACL approach.
---
## 23.1 Version table pattern
Для definitions/skills/settings:
```text
<aggregate>_revisions
id
revision
... immutable revision fields
PRIMARY KEY(id, revision)
<aggregate>_heads
id PRIMARY KEY
revision
state
updated_at
```
Head не содержит единственную копию semantic fields.
---
## 23.2 Transition ledger pattern
Для operational state:
```text
<aggregate>
id
revision
current_state
... current operational fields
<aggregate>_transitions
transition_id
aggregate_id
from_revision
to_revision
from_state
to_state
cause_ref
recorded_at
```
---
## 23.3 TypedValue physical encoding
Допустимый вариант:
```text
schema_definition_id TEXT
schema_revision BIGINT
value_type_fingerprint TEXT
value_payload JSONB
```
но только при условиях:
- payload валидируется owner domain code against ValueTypeSpec;
- DB CHECK обеспечивает базовую форму envelope;
- arbitrary JSON mutation API отсутствует;
- schema revision immutable;
- migration/replay может снова проверить payload;
- index создаётся только для реально нужных fields/projections.
JSONB здесь **encoding**, а не semantics.
---
## 23.4 No giant universal values table
Запрещён дизайн:
```text
entities(id,type,data_json)
```
куда Identity, Commit, Goal, Skill и knowledge складываются как одинаковые records.
World extensibility ограничивается referents/definitions. Operational core остаётся собственными typed schemas.
---
# 24. Search/index physical design
Canonical data model не требует graph DB или vector DB.
Foundation должен поддерживать replaceable projections:
```text
exact ID/entity index
alias index
FTS lexical index
temporal index
context-scope inverted index
world adjacency projection
experience positive/negative index
vector embedding index
current-belief index
freshness candidate index
```
Если позже graph/vector technology меняется, canonical rows не мигрируют из-за смены index engine.
---
## 24.1 Embedding record
Projection only:
```text
EmbeddingRecord
ProjectionRef
SourceRef
ProjectionVersion
EmbeddingModelRef + exact version
VectorDigest
Vector
CreatedAt
```
Новая embedding model может перестроить весь index без изменения source knowledge.
---
# 25. Dynamic schema evolution
## 25.1 Definition registration
Новый World facet или SettingDefinition проходит:
```text
proposal
-> owner validation
-> namespace collision check
-> schema compatibility check
-> revision creation
-> head activation
```
Для обычного low-risk Skill-defined setting это может быть автоматизированный bounded flow.
Изменение core semantic definition требует architecture task/ADR.
---
## 25.2 Compatible schema changes
Примеры обычно compatible:
- add optional struct field with default/absence semantics;
- expand enum only when consumers declare unknown-value handling;
- add new applicable World kind;
- deprecate field without deleting history.
Potentially incompatible:
- change scalar type;
- redefine meaning of existing field;
- change units;
- change relation direction/cardinality;
- reuse key for new meaning.
Incompatible change создаёт новую schema revision/version migration, а не silent reinterpretation old payload.
---
## 25.3 Unit semantics
Numeric semantic field должен указывать unit where applicable.
Нельзя иметь:
```text
threshold = 10
```
без понимания, это секунды, проценты, рубли или байты.
`ValueTypeSpec DECIMAL/INTEGER` может содержать unit definition/ref.
---
# 26. Multi-person / family memory boundary
Gen2 foundation должен не смешивать людей даже до появления полного family mode.
## 26.1 Source person != Principal
`WorldObject Ivan` и `Identity Principal Ivan` — разные concepts.
Связывание требует Identity/World evidence and explicit binding process where applicable.
Распознавание голоса «похоже на Ивана» не создаёт authenticated PrincipalBinding.
---
## 26.2 Data ownership
User-specific evidence хранит PrincipalID data realm.
Shared family/work contexts позже могут использовать shared Principal или explicit authorized sharing, но не semantic similarity.
Memory retrieval никогда не смешивает records разных Principal realms без разрешённого cross-principal data access.
---
## 26.3 Ambient future compatibility
Для будущего microphone/camera ingestion source chain должна уметь хранить:
```text
Artifact
-> SourceSnapshot/segment
-> speaker/person candidate Observation
-> World identity hypothesis
-> speech transcript Observation
-> Claim/Episode/Experience
```
Но raw ambient media не обязано храниться бесконечно. Retention policy и consent/privacy для multi-person ambient collection требуют отдельного ADR до включения такой возможности.
---
# 27. Current Focus + Configuration + Skill resolution example
Пример:
Пользователь говорит:
> «Работаем с Company B, разберись почему в этой УНФ неправильно выбирается штрихкод.»
Situation создаёт:
```text
ContextScope
ORGANIZATION REQUIRED -> WorldObject CompanyB
SYSTEM REQUIRED -> WorldObject CompanyB_UNF
ACTIVITY PREFERRED -> barcode investigation
```
Configuration получает:
```text
SettingDefinition = onec.live_endpoint
Assignments:
CompanyA -> endpoint A
CompanyB -> endpoint B
```
EffectiveConfiguration выбирает B before Capability starts.
Memory retrieval hard-filters CompanyB primary knowledge.
Если CompanyB evidence недостаточно, расширенный analogical lane может вернуть:
```text
CompanyA similar experience
relationship = ANALOGY_ONLY
disclosure = not current CompanyB fact
```
Skill resolver может выбрать общий `1C barcode diagnosis Skill`, но его applicability/environment constraints проверяются против CompanyB context.
---
# 28. Freshness example: old UNF structure
Canonical data:
```text
Observation O1:
captured 2026-08-28 from live CompanyA UNF
Claim C1:
CompanyA_UNF.SomeObject structure = X
Belief B1:
VERIFIED at 2026-08-28
volatility = VERSION_BOUND
version = configuration snapshot 2026-08-28
```
Через год вопрос:
> «Как вообще раньше это было устроено?»
TaskFreshnessRequirement = ANY/HISTORICAL acceptable.
B1 используется напрямую как historical evidence.
Другой вопрос:
> «Исправь ошибку в текущей CompanyA UNF.»
TaskFreshnessRequirement = REQUIRE_VERSION_MATCH or LIVE_REQUIRED.
Если live source доступен:
```text
B1 -> revalidation request -> current snapshot -> B2
```
Если live source недоступен:
```text
B1 FreshnessAssessment = HISTORICAL_ONLY / VERSION_UNKNOWN
FallbackPolicy = USE_AS_HYPOTHESIS_ONLY
```
Пользователю сообщается, что решение строится по прошлому состоянию и требует live confirmation.
Никакой физический delete B1 не происходит.
---
# 29. Negative experience example
Первый раз задача решается так:
```text
Problem P
Attempt A1 -> failed
Reason: ignored characteristic/unit
Experience E1 = FAILED
Attempt A2 -> verified success
Experience E2 = SUCCESS
```
Skill S1 получает:
```text
SupportingExperienceRefs = [E2]
KnownFailureExperienceRefs = [E1]
```
Следующая похожая задача:
Context Compiler получает одновременно:
```text
S1
E2 positive
E1 negative
```
Если environment version изменился, S1/Reflex не применяются blindly; VersionConstraint вызывает revalidation/escalation.
---
# 30. Self-learning example
Пользователь говорит:
> «Мы уже это проверяли. Почему ты опять пошёл тем же путём?»
Interaction:
```text
SpeechAct = CORRECTION
relation CORRECTS previous response/utterance
```
Epistemics:
```text
Experience E = USER_CORRECTED
ReflectionCandidate R
```
ContextAssemblyTrace позволяет установить:
```text
negative memory existed
but retrieval omitted it due to ranking policy v17
```
SELF:
```text
WeaknessPattern candidate:
repeated omission of known failure experience
```
Work governed development:
```text
proposal retrieval policy v18
historical replay
milestone evaluation
shadow comparison
```
SELF LearningLedger фиксирует actual before/after.
Ни Correction, ни новая модель напрямую не UPDATE'ит Context Compiler production policy.
---
# 31. Migration mapping V1 -> Gen2
Migration выполняется owner-by-owner. V1 остаётся reference/rollback до promotion соответствующего Gen2 path.
## 31.1 Global migration laws
1. PRE-GEN2 baseline commit/tag обязателен.
2. V1 rows не уничтожаются до verified cutover.
3. Existing IDs сохраняются wherever semantic identity совпадает.
4. Backfill idempotent.
5. Один canonical writer в каждый момент времени.
6. Shadow read разрешён; indefinite dual canonical write запрещён.
7. Migration-generated records имеют provenance `MIGRATED_FROM_V1` + exact source ref.
8. Нельзя invent missing semantic facts during migration.
9. Если V1 не содержит scope/version/provenance — поле остаётся UNKNOWN, а не угадывается.
10. Secrets не копируются через logs/sql dump/task artifacts.
---
## 31.2 Interaction
V1:
```text
interaction.conversations
interaction.utterances
interaction.original_human_intents
interaction.relations
semantic candidates/interpretations
```
Gen2:
- сохраняются canonical;
- Channel enum расширяется только через contract revision;
- raw media `ContentRef` постепенно становится ArtifactRef lineage;
- existing utterance IDs/intents сохраняются;
- corrections/supersession relations backfill only from explicit V1 evidence.
Никакого копирования Interaction history в новую memory table.
---
## 31.3 PersonalMemory V1
Текущий `CompilePersonalMemory`/ContextText:
- **не мигрируется как canonical data**;
- используется как compatibility output during transition;
- новые projections строятся из HumanUtterance/Epistemics/World/Work;
- после equivalence/household milestone compatibility PersonalMemory retires.
Если V1 PersonalMemory contains only derived string summary, summary может быть сохранён как migration evidence Artifact, но не как verified knowledge.
---
## 31.4 Situation Focus
V1:
```text
FocusBinding
ActiveProjectFocus
ProjectDescriptor
ProjectReference
```
Migration:
```text
ProjectDescriptor
-> WorldObject kind ACTIVITY/PROJECT where identity is explicit
FocusBinding.ProjectID
-> ContextBinding role PROJECT/ACTIVITY
FocusBinding.ScopeID
-> AuthorityScopeRef, NOT ContextScope
GoalID
-> FocusFrame GoalRef
```
V1 ActiveProjectFocus становится compatibility projection from FocusFrame after cutover.
Unknown organization/system/database context не угадывается из project name.
---
## 31.5 World bootstrap
WorldObjects создаются только из evidence-backed existing concepts:
- explicit ProjectDescriptor;
- known repository identity;
- configured database/system with stable existing ID/locator;
- explicit authenticated human references where resolution is safe.
Не выполнять массовое LLM-based entity extraction и auto-merge как migration requirement.
Entity resolution может постепенно улучшаться после foundation.
---
## 31.6 Epistemics truth/research
V1:
```text
Source
SourceSnapshot
SourceExcerpt
Citation
Observation
Claim
Belief
TruthBundle
ExperienceRecord
ReflectionCandidate
```
Migration:
- preserve existing IDs/evidence chains;
- V1 Snapshot.Freshness переносится как historical `FreshnessAssessment` evidence if useful, not permanent property;
- add TemporalApplicability defaults only where explicitly known;
- missing volatility = UNKNOWN, not MEDIUM by guess;
- existing Belief becomes BeliefAssessment revision 1 with source evidence;
- existing free text Claim remains valid legacy proposition `TEXTUAL` until structured proposition is derived and linked;
- ExperienceRecord V1 maps field-by-field; missing new fields empty/unknown.
---
## 31.7 Work
V1 Goal/Plan/Delegation/AgentRun/Checkpoint сохраняются.
Migration:
- Project columns become compatibility fields/read projections after ContextScope cutover;
- create ContextScopeRef for existing unambiguous project focus;
- TaskRequirements default to explicit neutral policy, not guessed strictness;
- existing AgentCheckpoints seed LongRunningWork where semantics already represent durable job;
- do not duplicate current AgentRun as second new job if Work already owns it.
---
## 31.8 Continuity
V1 ProspectiveItem/Attention/HumanResponse сохраняют IDs/state/revisions.
Migration:
- create explicit Commitment only when source semantics prove a commitment;
- existing reminder without recoverable commitment may keep `CommitmentRef = null` with source intent refs;
- existing absolute `TriggerAt` maps to `TriggerSpec ABSOLUTE_INSTANT`;
- state transitions preserved.
No second scheduler introduced.
---
## 31.9 Capability Skill
V1 `capability.skill_profiles(id,revision,...)` уже близок к Gen2.
Migration:
- SkillProfileID -> SkillID;
- each V1 revision -> SkillRevision;
- ApplicableContext strings initially become legacy applicability clauses with explicit marker `LEGACY_STRING_MATCH`, not silently parsed into hard scope;
- existing supporting/failure experience refs preserved;
- implementation/version/status preserved;
- later governed migration replaces legacy applicability with typed ContextMatcher.
Existing FastPath is **not automatically promoted to Reflex**.
Candidate Reflex records require explicit validation evidence.
---
## 31.10 Capability models/evaluations
Existing provider/model/binding/TaskEvaluation evidence preserved.
SELF competence may be seeded from these evaluations, but only by creating evidence-backed CompetenceAssessment records.
Do not copy overall score into global `competence` without ContextMatcher/task profile.
---
## 31.11 Configuration / ENV
Migration stages:
```text
inventory consumers
-> create SettingDefinitions
-> import non-secret values as MIGRATED_CONFIG assignments
-> import secret values through Secret Resolver into SecretRefs
-> shadow EffectiveConfiguration against ENV
-> switch each consumer
-> leave ENV read-only fallback temporarily
-> remove non-bootstrap ENV dependency
```
Address/endpoint can become ordinary SettingAssignment.
Token/password/private key never become ordinary value payload.
For unknown legacy default semantics, migration must record explicit default definition instead of silently using process environment forever.
---
## 31.12 SELF
SELF starts empty except evidence-derived seed:
```text
Capability TaskEvaluations
UsageObservations
Skill outcomes
Experience corrections/failures
Development gates
```
No LLM bootstrap statement such as «I am good at 1C» becomes canonical competence without evidence.
---
## 31.13 Commit
V1 ActionProposal/AuthorizedAction/ActionAttempt IDs/states preserved.
Add ExecutionReceipt/Transition ledger from evidence available in existing execution logs/receipts.
If old action outcome cannot be proven, migrate as `UNKNOWN/UNVERIFIED`, not success by inference.
---
## 31.14 Artifact
Existing artifact IDs/attestations preserved.
Raw files/media currently referenced indirectly can be enrolled gradually.
Migration must not copy entire binaries into PostgreSQL by default; Artifact owns storage identity/lineage, not necessarily bytes in DB.
---
# 32. Cutover pattern per subsystem
Каждый Gen2 subsystem проходит одинаковую схему:
```text
1. contract/ADR accepted
2. new schema/tables exist
3. V1 backfill/rebuild
4. Gen2 read shadow
5. compare/evidence
6. switch canonical writer
7. V1 compatibility read projection
8. milestone validation
9. retire old writer
10. later remove old tables/code only after rollback horizon
```
Нельзя иметь два независимых canonical writers «временно на несколько месяцев».
---
# 33. Rebuild / replay requirements
## 33.1 Projection rebuild
Любой projection должен иметь:
```text
projection_version
source watermark/checkpoint
rebuild command
idempotent source traversal
result digest/count evidence
```
---
## 33.2 Reprocessing old evidence
Новая model/extractor может создать:
```text
new Observation
new Claim
new BeliefAssessment
new Episode revision
```
с `DerivedFrom` refs на старый Artifact/Snapshot.
Она не изменяет original SourceSnapshot.
---
## 33.3 Knowledge supersession
Если новая обработка обнаружила ошибку старого derived knowledge:
```text
old assessment -> SUPERSEDED/REJECTED
new assessment -> PROVISIONAL/VERIFIED
```
Обе версии доступны historical query/audit.
---
# 34. Data integrity constraints
Минимальные universal invariants:
1. stable IDs non-empty;
2. revision >= 1;
3. confidence 0..1000 where present;
4. validity interval ordered;
5. exact definition revision exists before TypedValue acceptance within same owner;
6. head revision points to existing immutable revision;
7. no secret payload in normal setting/context/epistemic value;
8. cross-owner ref syntax valid even without DB FK;
9. historical revision immutable;
10. `UNKNOWN_OUTCOME` cannot transition to retry without reconciliation/explicit new attempt policy;
11. World merge/split lineage cannot delete source refs;
12. ContextScope REQUIRED and EXCLUDED cannot contain same exact binding in one revision;
13. EffectiveConfiguration conflict must surface, not choose nondeterministically;
14. Belief VERIFIED requires supporting evidence refs;
15. CompetenceAssessment score requires evidence;
16. Skill/Reflex ACTIVE/VALIDATED requires evaluation evidence;
17. Focus inferred with confidence cannot be treated as Authority;
18. Context Compiler cannot include secret value;
19. projection record must identify source ref + projection version;
20. migration unknown stays unknown.
---
# 35. No-guess / Unknown representation
Gen2 avoids false precision.
Не использовать zero/default как скрытое «unknown», если zero является валидным значением.
Для optional/unknown:
- nullable/optional typed field;
- explicit UNKNOWN enum where state semantics require;
- evidence absence.
Примеры:
```text
LastVerifiedAt absent != 1970-01-01
VersionRef absent != "latest"
Confidence absent != 0 confidence
No price != price 0
```
---
# 36. Data model and model-context safety
## 36.1 No database dump to LLM
Cognitive provider never receives raw DB rows by default.
Context Compiler produces bounded ContextExcerpt/structured excerpts with source refs.
---
## 36.2 Secret isolation
SecretRef may appear in execution plan metadata only when runtime needs to resolve it.
Secret value cannot appear in:
- embeddings;
- ContextBundle;
- ContextAssemblyTrace;
- Experience summary;
- LearningLedger;
- task packet;
- source code/logs.
---
## 36.3 External model data policy
Before context leaves local boundary:
```text
Principal/access
-> ContextScope
-> Sensitivity
-> DataPolicy
-> minimization
-> egress acknowledgement/policy
```
Context selection for local model and external model can differ even for same task.
---
# 37. Minimal API contracts implied by data model
Это не final Go signatures, но owners должны иметь bounded operations, а не generic CRUD.
## Situation
```text
CreateFocusFrame
ReviseFocusFrame
ActivateFocus
SuspendFocus
ResumeFocus
ResolveCurrentFocus
```
## World
```text
RegisterWorldObject
RegisterKindDefinition
RegisterFacetDefinition
RegisterRelationDefinition
ProposeAlias
ResolveIdentity
ResolveCanonicalRef
```
## Epistemics
```text
RecordObservation
RecordClaim
AssessClaim
RecordEpisodeRevision
RecordExperience
AssessFreshness
QueryEvidence
```
## Capability
```text
RegisterSkillCandidate
ObserveSkillOutcome
Promote/Suspend/RetireSkill
RegisterReflexCandidate
ObserveReflexOutcome
ResolveStrategy
```
## Configuration
```text
RegisterSettingDefinition
AssignSettingValue
ResolveEffectiveSetting
DeprecateDefinition
```
## SELF
```text
RecordCompetenceAssessment
RecordWeaknessPattern
RecordImprovementNeed
AppendLearningLedger
BuildSelfSnapshot
```
Generic methods вроде `PutObject(any)`/`SaveMemory(any)` запрещены.
---
# 38. FAST / MILESTONE / FULL validation for data work
Чтобы Gen2 не снова превратился в двухсуточный test loop, data-model implementation follows target testing strategy.
## FAST
Для локальной data change:
- compile changed contracts/owner;
- validator unit tests changed type;
- migration SQL parse/basic role check where cheap;
- one targeted repository test;
- architecture/diff guard.
Не запускать `go test ./...` автоматически.
## MILESTONE
После Focus/World/Epistemics, Configuration или Skill/SELF block:
- owner schema/repository tests;
- backfill idempotency;
- migration read equivalence;
- projection rebuild;
- selected household regressions;
- relevant recovery check.
## FULL
Только перед крупным architecture phase merge, critical migration/cutover, production canary или final V1 retirement.
---
# 39. Required ADR decisions before schema implementation
Canonical Data Model concretizes Target Architecture, но следующие решения должны быть приняты отдельными ADR до соответствующих migrations:
1. Scope split physical/contract representation.
2. World typed definition/value algebra encoding.
3. Epistemics Proposition/Belief/Freshness V2.
4. Projection/retrieval storage ownership and rebuild protocol.
5. Configuration selector/precedence semantics.
6. Skill/Reflex versioning and promotion authority.
7. SELF evidence semantics.
8. TriggerSpec extension for Continuity.
9. ExecutionReceipt vs WorldOutcomeAssessment transition semantics.
10. Artifact retention/privacy for ambient multi-person data.
ADR не должен заново открывать уже принятый owner decision без явной Architecture Generation authority.
---
# 40. Concepts intentionally NOT canonical in Gen2
Не создавать canonical tables для:
```text
MemoryItem
ModelContext
ContextPrompt
EffectiveConfiguration
CurrentKnowledge
FreshnessScore universal
GlobalSourceTrustScore
AgentPersona
GenericEntityPayload
GenericEventBusMessage
EmbeddingAsKnowledge
LLMThought/ChainOfThought
```
Reasoning internals модели не нужны как canonical memory. Сохраняются только пользовательски/операционно полезные findings, evidence, decisions, attempts and outcomes.
---
# 41. Proposed table families
Имена предварительные; Master Plan/ADR может уточнить, но owner boundaries фиксированы.
## situation
```text
focus_frames
focus_frame_revisions
focus_transitions
context_scopes
context_scope_revisions
context_scope_bindings
focus_heads
```
## world
```text
objects
object_heads
kind_definitions
kind_definition_heads
aliases
facet_definitions
facet_definition_heads
relation_definitions
relation_definition_heads
identity_resolution_decisions
identity_lineage
```
## epistemics
```text
sources
source_snapshots
source_excerpts
observations
claims
belief_assessments
belief_heads
episodes
episode_heads
experience_records
reflection_candidates
source_reliability_observations
source_reliability_assessments
world_outcome_assessments
```
## work
```text
goals
tasks
long_running_work
long_running_work_transitions
perspective_specs
consequence_assessments
(existing plan/graph/delegation/run/checkpoint tables)
```
## continuity
```text
commitments
commitment_transitions
prospective_items
prospective_transitions
attention_items
human_responses
```
## capability
```text
skills
skill_revisions
skill_heads
reflexes
reflex_revisions
reflex_heads
(existing capability/provider/binding/usage/evaluation tables)
```
## configuration
```text
setting_definitions
setting_definition_revisions
setting_definition_heads
setting_assignments
setting_assignment_revisions
setting_assignment_heads
```
## self_model
```text
competence_assessments
weakness_patterns
weakness_pattern_revisions
improvement_needs
learning_ledger
self_composition_snapshots
```
## commit
```text
(existing proposals/authorized actions/attempts)
action_attempt_transitions
execution_receipts
```
## artifact
```text
artifacts
artifact_lineage
artifact_segments/segment_index where needed
attestations
```
## projection schemas
```text
retrieval_documents
entity_alias_index
temporal_index
experience_index
knowledge_current_index
embeddings
focus_stack_view
effective_config_cache
```
Projection schemas use read/write role of projection builder only and are never writable by domain owners as canonical state.
---
# 42. What should be implemented first
Canonical Data Model does **not** mean create all tables at once.
Recommended order for Master Plan:
```text
1. shared primitives + ADRs
2. ContextScope / Focus V2
3. World referents + typed definitions
4. Epistemics Proposition/Freshness/Episode/Experience
5. retrieval projections + Context Compiler V2
6. Configuration
7. Skill V2 + Reflex
8. SELF foundation
9. LongRunningWork extensions
10. Commit receipt/outcome clarification
11. migration/cutover by subsystem
```
Strict existing Authority/Commit/Continuity semantics remain available throughout.
---
# 43. Acceptance criteria for Canonical Data Model
Data Model считается достаточно определённой для Master Plan, если выполняются все условия:
1. ни один canonical concept не имеет двух proposed owners;
2. нет universal MemoryItem table;
3. World хранит referents/definitions, но не фактическую истину мира;
4. Epistemics может выразить structured claim + evidence + contradiction + historical truth;
5. freshness вычисляется относительно Task requirement, а не permanent stale bit;
6. volatility/last verification/version scope могут быть сохранены;
7. old knowledge остаётся historical/analogy candidate;
8. ContextScope поддерживает Company A/B isolation before similarity;
9. Focus Stack не требует project-only schema;
10. TypedValue extensible, но arbitrary JSON API запрещён;
11. Skill и Reflex имеют stable identity, revisions, applicability and evidence;
12. negative experience first-class;
13. Configuration supports typed scoped values without ENV explosion;
14. secrets существуют только как SecretRef outside normal memory;
15. SELF scores evidence-backed;
16. long-running work durable and model-independent;
17. execution receipt отделён от verified world outcome;
18. raw artifacts/evidence могут быть reprocessed future models;
19. embeddings/indexes rebuildable;
20. V1 migration не требует destructive big bang;
21. missing migration semantics remain UNKNOWN rather than guessed;
22. one canonical writer during cutover;
23. testing supports FAST/MILESTONE/FULL instead of constant full suite;
24. future devices/ambient/robots can add World kinds/facets without changing strict operational core;
25. future stronger model can rebuild derived memory without changing historical evidence.
---
# 44. Decisions carried into Master Plan
Master Plan должен считать уже принятыми следующие решения:
1. PRE-GEN2 commit/merge/push/tag baseline выполняется до Gen2 code.
2. Gen2 is migration, not greenfield rewrite.
3. `PersonalMemory` V1 retires as canonical-looking mechanism; no new Memory owner.
4. Situation owns Focus/ContextScope.
5. World is new narrow owner.
6. Epistemics owns knowledge/evidence/freshness/Experience/world outcome assessment.
7. Capability owns Skill/Reflex.
8. Configuration and SELF are new owners.
9. Continuity remains only owner future relevance.
10. Commit keeps mutation/idempotency/unknown-outcome boundary.
11. Context Compiler/Memory Retrieval are workers/projections, not canonical owners.
12. ENV shrinks to bootstrap.
13. Typed dynamic schemas are allowed only behind owner definitions/validation.
14. No generic `Entity(any)` / `MemoryItem(any)` / `Settings map[string]any`.
15. Full tests are milestone/full gates, not every Codex loop.
---
# 45. Следующий документ
После принятия Canonical Data Model следующий обязательный документ:
**`GEN2_MIGRATION_MAP.md`**
Он должен пройти по фактическим V1 packages/tables/functions и для каждого поставить:
```text
KEEP
EXTEND
REWORK
REPLACE
RETIRE
```
с указанием:
- current owner;
- Gen2 owner;
- exact V1 source paths/tables;
- compatibility strategy;
- backfill/cutover;
- rollback;
- FAST/MILESTONE gate;
- dependency on later tasks.
После Migration Map создаётся `GEN2_MASTER_PLAN.md` и конкретные Codex task packets.
---
# 46. Итоговая формула Gen2 Data
```text
RAW EVIDENCE IS PRESERVED
│
▼
STRUCTURED OBSERVATION
│
▼
CLAIM / PROPOSITION
│
▼
EVIDENCE-BACKED ASSESSMENT
│
├───────────── time / version / freshness
├───────────── context / scope
├───────────── source / provenance
└───────────── contradiction / supersession
│
▼
REBUILDABLE MEMORY PROJECTIONS
│
▼
MINIMAL TASK-SPECIFIC CONTEXT
│
▼
REASON / ACT / VERIFY
│
▼
EXPERIENCE
│
├── Skill
├── Reflex
└── SELF learning
```
Главная гарантия:
> **Домовой может менять способы понимания, поиска, обучения и даже собственный код, не теряя различия между тем, что действительно было наблюдено, тем, что он когда-то предположил, тем, что сегодня считает доказанным, и тем, что больше нельзя считать актуальным.**
Именно это делает память и модель данных пригодными не только для текущего Assistant, но и для системы, которая должна развиваться годами.