From 2e824b3c1f1b6c86d7eccb250677c2b4776affae Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 15:33:59 +0300 Subject: [PATCH 1/6] chore: start cognitive route remediation trace --- cmd/core-runtime/main.go | 4 ++ dev/ACTIVE_TASK.json | 2 +- ...02-restore-production-cognitive-route.json | 61 +++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json diff --git a/cmd/core-runtime/main.go b/cmd/core-runtime/main.go index 8f371e5..9083494 100644 --- a/cmd/core-runtime/main.go +++ b/cmd/core-runtime/main.go @@ -1483,6 +1483,10 @@ func main() { candidates, err = capabilityRepository.LoadCognitiveCandidates(r.Context(), requirement.CapabilityID, requirement.OwnerPrincipalID) } if err != nil { + // The resolver is an internal capability boundary. Keep request identity + // and content out of logs, but preserve the repository error so a 503 + // can be distinguished from a true empty/unsuitable binding set. + log.Printf("cognitive registry resolve unavailable: %v", err) http.Error(w, "cognitive registry unavailable", http.StatusServiceUnavailable) return } diff --git a/dev/ACTIVE_TASK.json b/dev/ACTIVE_TASK.json index 386c9a6..d7a3af1 100644 --- a/dev/ACTIVE_TASK.json +++ b/dev/ACTIVE_TASK.json @@ -1 +1 @@ -{"task_file":"dev/tasks/GEN2-DEPLOY-003-isolated-release-slots.json","task_id":"GEN2-DEPLOY-003","task_revision":1} +{"task_file":"dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json","task_id":"GEN2-COGNITIVE-002","task_revision":1} diff --git a/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json new file mode 100644 index 0000000..b95ba7f --- /dev/null +++ b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json @@ -0,0 +1,61 @@ +{ + "task_id": "GEN2-COGNITIVE-002", + "task_revision": 1, + "architecture_revision": "ARCH-GEN2-000", + "base_repo_revision": "gen2-integration", + "risk_tier": "E", + "intent": "Восстановить доказанно рабочий production cognitive route для обычного household и memory-recall запроса через существующие Capability и Cognitive Gateway boundaries, без подмены primary route Lifeboat-ом.", + "requirement_ids": ["REQ-GEN2-COGNITIVE-002-TRACE", "REQ-GEN2-COGNITIVE-002-ROUTING", "REQ-GEN2-COGNITIVE-002-RECOVERY"], + "allowed_change_scope": { + "modules": ["capability", "cognitive-worker", "core-runtime", "production deployment"], + "paths": [ + "cmd/cognitive-worker/**", + "cmd/core-runtime/**", + "contracts/capability/**", + "contracts/cognitive/**", + "modules/capability/**", + "adapters/models/**", + "adapters/postgres/capability_repository.go", + "deploy/run-production-canary.sh", + "deploy/docker-compose.candidate-slot.yml", + "tests/**", + "docs/evidence/**", + "docs/**", + "dev/ACTIVE_TASK.json", + "dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json" + ] + }, + "forbidden_change_scope": { + "paths": ["architecture/**", "security/**", "database/**", "go.mod", "go.sum", ".gitea/workflows/**", "GEN2-028", "GEN2-029", "GEN2-030"] + }, + "allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 1, "new_third_party_dependencies": 0, "new_database_owner_roles": 0}, + "contracts": { + "consume": ["existing Capability binding lifecycle", "existing cognitive gateway/advisory contracts", "existing Supervisor ReleaseSet control plane"], + "may_change": ["typed capability/provider selection and invocation wiring only within declared paths"] + }, + "semantic_owner": "Capability remains the sole owner of provider/model/binding lifecycle; cognitive-worker invokes providers through adapters; Core consumes the governed gateway; Supervisor alone controls traffic promotion and rollback.", + "canonical_state": ["existing Capability provider/model/binding/evaluation evidence", "no new canonical writer, owner, schema, role, or migration"], + "state_transitions": ["trace stable and candidate loaded binding heads -> correct stale/divergent lifecycle or invocation defect -> governed repair/qualification -> isolated candidate validation -> Supervisor canary -> promote or rollback"], + "side_effects_and_privileges": ["production candidate deployment and Supervisor canary/promotion are explicitly authorized", "adapters/models/** may change only after trace proves a model adapter, provider endpoint, injection, timeout, rate-limit, context budget, or invocation defect there", "cmd/core-runtime/** may change only after trace proves Core-to-worker request construction, route selection, or response handling is causal", "no direct SQL semantic mutation", "no credential, cookie, token, prompt, or user content read/emitted", "Lifeboat may be observed as fallback but cannot mask Local MEDIUM primary failure"], + "persistence_and_migrations": ["no schema/migration change is authorized", "adapters/postgres/capability_repository.go may change only after trace proves durable Capability head/state loading diverges from the correct persisted state; reuse its existing repository boundary"], + "failure_retry_restart": ["discovery health, invocation health, and availability remain distinct", "CPU/GPU gaps must not suppress a valid Local MEDIUM", "restart reloads a durable active/validated binding head", "failed candidate rolls traffic to Supervisor LKG without stable recreation"], + "assumptions": ["isolated candidate slot B and Supervisor controls from GEN2-DEPLOY-003 are available", "an existing authenticated production session may be used only through ordinary runtime interaction", "GEN2-COMPAT-OBS-001 remains paused and V1 paths remain unchanged"], + "acceptance_scenarios": [ + "COGNITIVE-002-SCN-01: factual stable/candidate trace records Core request, requirement, binding selection, loaded binding head, fleet availability, provider eligibility, invocation result, and response/error without sensitive content", + "COGNITIVE-002-SCN-02: Local MEDIUM is shown ACTIVE, VALIDATED, AVAILABLE, and actually invoked for bounded OK, Russian household, and prepared-context recall requests", + "COGNITIVE-002-SCN-03: health endpoint success alone is not used as inference proof; discovery and invocation failures are separately classified", + "COGNITIVE-002-SCN-04: candidate four-component health/revision check, real canary household request, memory write/multiple turns/recall, and candidate Core plus cognitive-worker restart/recovery pass", + "COGNITIVE-002-SCN-05: only after candidate success, Supervisor promotes it; evidence retains LKG and rollback readiness", + "COGNITIVE-002-EXIT: ordinary household and memory-recall response use Local MEDIUM through the governed route and remain usable after candidate restart" + ], + "required_tests": [ + "FAST: targeted go test ./cmd/cognitive-worker/... ./cmd/core-runtime/... ./modules/capability/... ./adapters/models/... ./adapters/postgres/... only for changed packages", + "FAST: targeted go vet for changed packages", + "FAST governance: go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json", + "FAST scope: go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json", + "FAST independent: go run ./cmd/devctl/independent", + "FAST whitespace: git diff --check gen2-integration --", + "production: stable/candidate trace, isolated candidate health/canary, Local MEDIUM invocation, restart recovery, and Supervisor promotion/rollback evidence" + ], + "terminal_gap_states": ["BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT", "REQUIRES_MIGRATION_DECISION"] +} From 185317ee6a34d1725ff904f4b4f6e55bff09039a Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 15:56:34 +0300 Subject: [PATCH 2/6] fix: revalidate stale cognitive binding health --- cmd/cognitive-worker/admission_test.go | 19 ++++- cmd/cognitive-worker/discovery.go | 27 ++++--- cmd/cognitive-worker/gateway.go | 40 +++++++++- cmd/cognitive-worker/gateway_registry_test.go | 73 +++++++++++++++++++ cmd/cognitive-worker/main.go | 9 ++- 5 files changed, 148 insertions(+), 20 deletions(-) diff --git a/cmd/cognitive-worker/admission_test.go b/cmd/cognitive-worker/admission_test.go index f58a104..307b42e 100644 --- a/cmd/cognitive-worker/admission_test.go +++ b/cmd/cognitive-worker/admission_test.go @@ -16,15 +16,17 @@ func (p *admissionTestProvider) Advise(context.Context, cognitive.AdvisoryReques } type admissionTestClient struct { - decision capability.AdmissionDecision - releases int + decision capability.AdmissionDecision + releases int + releaseContextErr error } func (c *admissionTestClient) Admit(context.Context, string, capability.AdmissionRequest) (capability.AdmissionDecision, capability.AdmissionLease, error) { return c.decision, capability.AdmissionLease{ID: "lease-1", PolicyID: "policy-1"}, nil } -func (c *admissionTestClient) Release(context.Context, capability.AdmissionLease) error { +func (c *admissionTestClient) Release(ctx context.Context, _ capability.AdmissionLease) error { c.releases++ + c.releaseContextErr = ctx.Err() return nil } @@ -47,3 +49,14 @@ func TestInvokeAdmittedReleasesDurableLeaseAfterProvider(t *testing.T) { t.Fatalf("admitted lease was not released: response=%#v err=%v calls=%d releases=%d", response, err, provider.calls, client.releases) } } + +func TestInvokeAdmittedReleasesLeaseAfterCallerCancellation(t *testing.T) { + provider := &admissionTestProvider{} + client := &admissionTestClient{decision: capability.AdmissionDecision{State: capability.AdmissionAdmitted, Reason: capability.AdmissionReasonNone, PolicyID: "policy-1"}} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, _ = (&cognitiveGateway{admission: client}).invokeAdmitted(ctx, "request-1", provider, cognitive.AdvisoryRequest{Message: "hello"}, 100) + if client.releases != 1 || client.releaseContextErr != nil { + t.Fatalf("cancelled caller leaked durable lease: releases=%d release_context_err=%v", client.releases, client.releaseContextErr) + } +} diff --git a/cmd/cognitive-worker/discovery.go b/cmd/cognitive-worker/discovery.go index c873e35..29ffafc 100644 --- a/cmd/cognitive-worker/discovery.go +++ b/cmd/cognitive-worker/discovery.go @@ -1,7 +1,9 @@ package main import ( + "context" "encoding/json" + "fmt" "net/http" "sort" "time" @@ -22,17 +24,7 @@ func (s discoveryService) handler(w http.ResponseWriter, r *http.Request) { s.statusHandler(w, r) return } - registration, ok := s.providers[r.PathValue("provider")] - if !ok || registration.Discovery == nil { - http.Error(w, "provider discovery not found", http.StatusNotFound) - return - } - discovered, probe := registration.Discovery.Discover(r.Context()) - snapshot := capability.CognitiveDiscoverySnapshot{ProviderInstanceID: registration.ProviderInstanceID, ProviderKind: registration.Kind, EndpointRef: registration.EndpointRef, CredentialRef: registration.CredentialRef, AuthMode: registration.AuthMode, BillingMode: registration.BillingMode, Enabled: true, OwnerPrincipalID: s.owner, CapabilityID: creatorAdvisoryCapabilityID, DataPolicy: registration.DataPolicy, LimitPolicyRef: "creator-advisory-local-v1", Health: probe.Health, FailureClass: capability.CognitiveFailureType(probe.Failure), ObservedAtUnixMillis: s.now().UnixMilli()} - for _, model := range discovered { - snapshot.Models = append(snapshot.Models, capability.DiscoveredModelSnapshot{ProviderModelID: model.ProviderModelID, Fingerprint: model.Fingerprint, MaxContextBytes: model.MaxContextBytes, Modalities: model.Modalities, Capabilities: model.Capabilities, Installed: capability.OperationalYes, Loaded: capability.OperationalNotObserved, Invokable: capability.OperationalNotObserved}) - } - result, err := s.resolver.RegisterDiscovery(r.Context(), snapshot) + result, err := s.register(r.Context(), r.PathValue("provider")) if err != nil { http.Error(w, "provider discovery registration unavailable", http.StatusBadGateway) return @@ -41,6 +33,19 @@ func (s discoveryService) handler(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(result) } +func (s discoveryService) register(ctx context.Context, provider string) (capability.CognitiveDiscoveryRegistration, error) { + registration, ok := s.providers[provider] + if !ok || registration.Discovery == nil { + return capability.CognitiveDiscoveryRegistration{}, fmt.Errorf("provider discovery not found") + } + discovered, probe := registration.Discovery.Discover(ctx) + snapshot := capability.CognitiveDiscoverySnapshot{ProviderInstanceID: registration.ProviderInstanceID, ProviderKind: registration.Kind, EndpointRef: registration.EndpointRef, CredentialRef: registration.CredentialRef, AuthMode: registration.AuthMode, BillingMode: registration.BillingMode, Enabled: true, OwnerPrincipalID: s.owner, CapabilityID: creatorAdvisoryCapabilityID, DataPolicy: registration.DataPolicy, LimitPolicyRef: "creator-advisory-local-v1", Health: probe.Health, FailureClass: capability.CognitiveFailureType(probe.Failure), ObservedAtUnixMillis: s.now().UnixMilli()} + for _, model := range discovered { + snapshot.Models = append(snapshot.Models, capability.DiscoveredModelSnapshot{ProviderModelID: model.ProviderModelID, Fingerprint: model.Fingerprint, MaxContextBytes: model.MaxContextBytes, Modalities: model.Modalities, Capabilities: model.Capabilities, Installed: capability.OperationalYes, Loaded: capability.OperationalNotObserved, Invokable: capability.OperationalNotObserved}) + } + return s.resolver.RegisterDiscovery(ctx, snapshot) +} + type discoveryStatus struct { Provider string `json:"provider"` ProviderKind capability.ProviderKind `json:"provider_kind"` diff --git a/cmd/cognitive-worker/gateway.go b/cmd/cognitive-worker/gateway.go index ddf409b..8f8715d 100644 --- a/cmd/cognitive-worker/gateway.go +++ b/cmd/cognitive-worker/gateway.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -20,6 +21,8 @@ import ( const creatorAdvisoryCapabilityID capability.CapabilityID = "creator-advisory" +var errNoInvocableCognitiveBinding = errors.New("no invocable cognitive binding") + type bindingResolver interface { Resolve(context.Context, capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) Observe(context.Context, capability.CognitiveUsageObservation) error @@ -56,6 +59,7 @@ type cognitiveGateway struct { allowCanary bool canaryMaxOutputBytes int admission admissionClient + revalidatePrimary func(context.Context) error } func (g cognitiveGateway) policyHandler(w http.ResponseWriter, r *http.Request) { @@ -89,7 +93,7 @@ func (g cognitiveGateway) advisoryHandler(w http.ResponseWriter, r *http.Request maxOutputBytes = g.canaryMaxOutputBytes } requirement := capability.CognitiveRequirement{CapabilityID: creatorAdvisoryCapabilityID, OwnerPrincipalID: request.PrincipalID, DataPolicy: request.DataPolicy, RequiredModalities: []capability.ModelModality{capability.ModalityText}, RequiredCapabilities: []capability.ModelCapability{capability.CapabilityAdvisory}, AllowCanary: g.allowCanary, InputBytes: int64(len(request.Message)), MaxOutputBytes: int64(maxOutputBytes), Objective: selectionObjectiveForMeaning(request.Meaning, request.Message)} - selected, err := g.resolver.Resolve(r.Context(), requirement) + selected, err := g.resolveWithRevalidation(r.Context(), requirement) if err != nil { writeGatewayResponse(w, g.invokeBuiltinAdvisory(r.Context(), request, maxOutputBytes)) return @@ -145,11 +149,33 @@ func (g cognitiveGateway) invokeAdmitted(ctx context.Context, leaseID string, pr return cognitive.AdvisoryResponse{Version: invocation.Version, RequestID: invocation.RequestID, ProviderBindingID: invocation.ProviderBindingID, ProviderBindingRevision: invocation.ProviderBindingRevision, FinishReason: cognitive.FinishRateLimited}, nil } lease = admittedLease - defer func() { _ = g.admission.Release(ctx, lease) }() + defer func() { + releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + _ = g.admission.Release(releaseCtx, lease) + }() } return provider.Advise(ctx, invocation) } +// resolveWithRevalidation makes one bounded recovery attempt when Capability +// has an active/validated binding but its durable health projection rejected it +// as non-invocable. Discovery remains the canonical Capability write path; the +// retry observes the configured primary local provider and re-runs selection +// once. Provider invocation, admission, and fallback remain governed elsewhere. +func (g cognitiveGateway) resolveWithRevalidation(ctx context.Context, requirement capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) { + selected, err := g.resolver.Resolve(ctx, requirement) + if err == nil || !errors.Is(err, errNoInvocableCognitiveBinding) || g.revalidatePrimary == nil { + return selected, err + } + revalidationCtx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + if revalidationErr := g.revalidatePrimary(revalidationCtx); revalidationErr != nil { + return selected, err + } + return g.resolver.Resolve(ctx, requirement) +} + func selectionObjectiveForMessage(message string) capability.SelectionObjective { lower := strings.ToLower(message) if strings.Contains(lower, "дешев") || strings.Contains(lower, "бесплат") || strings.Contains(lower, "эконом") || strings.Contains(lower, "cost") || strings.Contains(lower, "cheap") { @@ -374,6 +400,10 @@ type httpBindingResolver struct { client *http.Client } +type httpStatusError struct{ status int } + +func (e httpStatusError) Error() string { return fmt.Sprintf("registry status %d", e.status) } + func newHTTPBindingResolver(raw string, client *http.Client) (*httpBindingResolver, error) { base, err := url.Parse(raw) if err != nil || base.Scheme == "" || base.Host == "" { @@ -385,6 +415,10 @@ func newHTTPBindingResolver(raw string, client *http.Client) (*httpBindingResolv func (r *httpBindingResolver) Resolve(ctx context.Context, value capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) { var result capability.ResolvedCognitiveBinding err := r.post(ctx, "/v1/cognitive-bindings/resolve", value, &result) + var statusErr httpStatusError + if errors.As(err, &statusErr) && statusErr.status == http.StatusNotFound { + return result, errNoInvocableCognitiveBinding + } return result, err } @@ -437,7 +471,7 @@ func (r *httpBindingResolver) post(ctx context.Context, path string, value, dest defer response.Body.Close() if response.StatusCode < 200 || response.StatusCode >= 300 { _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) - return fmt.Errorf("registry status %d", response.StatusCode) + return httpStatusError{status: response.StatusCode} } if destination != nil { return json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(destination) diff --git a/cmd/cognitive-worker/gateway_registry_test.go b/cmd/cognitive-worker/gateway_registry_test.go index 911883e..a87c6f2 100644 --- a/cmd/cognitive-worker/gateway_registry_test.go +++ b/cmd/cognitive-worker/gateway_registry_test.go @@ -22,6 +22,26 @@ type registryStub struct { observation *capability.CognitiveUsageObservation } +type revalidatingRegistry struct { + selected capability.ResolvedCognitiveBinding + calls int + alwaysNo bool +} + +func (s *revalidatingRegistry) Resolve(context.Context, capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) { + s.calls++ + if s.alwaysNo || s.calls == 1 { + return capability.ResolvedCognitiveBinding{}, errNoInvocableCognitiveBinding + } + return s.selected, nil +} +func (*revalidatingRegistry) Observe(context.Context, capability.CognitiveUsageObservation) error { + return nil +} +func (*revalidatingRegistry) RegisterDiscovery(context.Context, capability.CognitiveDiscoverySnapshot) (capability.CognitiveDiscoveryRegistration, error) { + return capability.CognitiveDiscoveryRegistration{}, nil +} + type failoverRegistry struct { primary, fallback capability.ResolvedCognitiveBinding observations []capability.CognitiveUsageObservation @@ -88,6 +108,59 @@ func TestActiveRegistryBindingReachesProviderAdapter(t *testing.T) { } } +func TestStaleUnavailableBindingRevalidatesOnceBeforeInvocation(t *testing.T) { + selected := gatewaySelection() + selected.Binding.DataPolicy = capability.DataPolicyLocalOnly + registry := &revalidatingRegistry{selected: selected} + provider := &stubAdvisoryProvider{response: cognitive.AdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: "request-1", AdvisoryText: "ok", FinishReason: cognitive.FinishCompleted}} + revalidations := 0 + gateway := cognitiveGateway{resolver: registry, providers: map[capability.ProviderKind][]providerRegistration{"provider-kind-1": {{EndpointRef: "endpoint-1", CredentialRef: "credential-1", Provider: provider}}}, now: time.Now, revalidatePrimary: func(context.Context) error { revalidations++; return nil }} + response := httptest.NewRecorder() + gateway.advisoryHandler(response, httptest.NewRequest(http.MethodPost, "/v1/advisories", strings.NewReader(gatewayRequest()))) + if response.Code != http.StatusOK || !provider.called || revalidations != 1 || registry.calls != 2 { + t.Fatalf("status=%d provider_called=%t revalidations=%d resolves=%d", response.Code, provider.called, revalidations, registry.calls) + } +} + +func TestRevalidationFailureDoesNotMakeBindingInvocable(t *testing.T) { + registry := ®istryStub{err: errNoInvocableCognitiveBinding} + provider := &stubAdvisoryProvider{} + revalidations := 0 + gateway := cognitiveGateway{resolver: registry, providers: map[capability.ProviderKind][]providerRegistration{"provider-kind-1": {{Provider: provider}}}, now: time.Now, revalidatePrimary: func(context.Context) error { revalidations++; return errors.New("provider unavailable") }} + gateway.advisoryHandler(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/v1/advisories", strings.NewReader(gatewayRequest()))) + if provider.called || revalidations != 1 { + t.Fatalf("failed provider revalidation was treated as invocable: provider_called=%t revalidations=%d", provider.called, revalidations) + } +} + +func TestRevalidationIsNotRetriedInALoop(t *testing.T) { + registry := &revalidatingRegistry{alwaysNo: true} + revalidations := 0 + gateway := cognitiveGateway{resolver: registry, now: time.Now, revalidatePrimary: func(context.Context) error { revalidations++; return nil }} + gateway.advisoryHandler(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/v1/advisories", strings.NewReader(gatewayRequest()))) + if revalidations != 1 || registry.calls != 2 { + t.Fatalf("revalidation loop: revalidations=%d resolves=%d", revalidations, registry.calls) + } +} + +func TestHTTPResolverMarksNoInvocableBindingForSingleRevalidation(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/cognitive-bindings/resolve" { + t.Fatalf("path=%s", r.URL.Path) + } + http.Error(w, "no invocable cognitive binding", http.StatusNotFound) + })) + defer server.Close() + resolver, err := newHTTPBindingResolver(server.URL, server.Client()) + if err != nil { + t.Fatal(err) + } + _, err = resolver.Resolve(context.Background(), capability.CognitiveRequirement{CapabilityID: creatorAdvisoryCapabilityID, OwnerPrincipalID: "principal-1", MaxOutputBytes: 1}) + if !errors.Is(err, errNoInvocableCognitiveBinding) { + t.Fatalf("resolve error=%v, want no-invocable sentinel", err) + } +} + func TestProviderUsesStableInstanceWhenCredentialMetadataIsStale(t *testing.T) { provider := &stubAdvisoryProvider{} gateway := cognitiveGateway{providers: map[capability.ProviderKind][]providerRegistration{ diff --git a/cmd/cognitive-worker/main.go b/cmd/cognitive-worker/main.go index 4ddd25b..feb63ed 100644 --- a/cmd/cognitive-worker/main.go +++ b/cmd/cognitive-worker/main.go @@ -113,11 +113,15 @@ func main() { kind := capability.ProviderKind(envOr("OPENAI_PROVIDER_KIND", "openai-responses-v1")) providers[kind] = append(providers[kind], providerRegistration{ProviderInstanceID: "openai-bootstrap", Kind: kind, EndpointRef: capability.EndpointBindingRef(envOr("OPENAI_ENDPOINT_REF", "openai-responses-default")), CredentialRef: capability.CredentialRef(envOr("OPENAI_CREDENTIAL_REF", "openai-advisory-v1")), AuthMode: capability.AuthKey, BillingMode: capability.BillingPerInput, DataPolicy: capability.DataPolicyExternalMessageOnly, Provider: openAIProvider}) } - gateway := cognitiveGateway{resolver: resolver, providers: providers, builtinLocal: builtinLocal, externalRecovery: externalRecovery, now: time.Now, allowCanary: os.Getenv("COGNITIVE_ALLOW_CANARY") == "true", canaryMaxOutputBytes: 4096, admission: newHTTPAdmissionClient(envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"), &http.Client{Timeout: 5 * time.Second})} + discovery := discoveryService{resolver: resolver, providers: discoveries, owner: identity.PrincipalID(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), now: time.Now} + gateway := cognitiveGateway{resolver: resolver, providers: providers, builtinLocal: builtinLocal, externalRecovery: externalRecovery, now: time.Now, allowCanary: os.Getenv("COGNITIVE_ALLOW_CANARY") == "true", canaryMaxOutputBytes: 4096, admission: newHTTPAdmissionClient(envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"), &http.Client{Timeout: 5 * time.Second}), revalidatePrimary: func(ctx context.Context) error { + _, err := discovery.register(ctx, "medium") + return err + }} mux.Handle("/healthz", health.Handler{Runtime: "cognitive-worker", SemanticGeneration: 1, ArchitectureGeneration: 1}) readinessClient := &http.Client{Timeout: 2 * time.Second} cpuReadinessClient := &http.Client{Timeout: 10 * time.Second} - mediumReadinessTimeout := 120 * time.Second + mediumReadinessTimeout := 120 * time.Second mediumReadinessClient := &http.Client{Timeout: mediumReadinessTimeout} lifeboatURL := strings.TrimSuffix(strings.TrimRight(envOr("LOCAL_LIFEBOAT_PROVIDER_URL", "http://cognitive-lifeboat:8086/v1"), "/"), "/v1") + "/health" fleetClient := &http.Client{Timeout: 2 * time.Second} @@ -199,7 +203,6 @@ func main() { mux.HandleFunc("POST /v1/multimodal/ocr", multimodalGateway.handler(capability.MultimodalRecognizeOCR)) mux.HandleFunc("POST /v1/multimodal/video-understand", multimodalGateway.handler(capability.MultimodalUnderstandVideo)) mux.HandleFunc("POST /v1/multimodal/generate-image", multimodalGateway.handler(capability.MultimodalGenerateImage)) - discovery := discoveryService{resolver: resolver, providers: discoveries, owner: identity.PrincipalID(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), now: time.Now} mux.HandleFunc("POST /v1/provider-discovery/{provider}", discovery.handler) mux.Handle("POST /v1/provider-discovery/{provider}/qualify", modelQualificationHandler(discoveries, string(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), httpQualificationObserver{resolver: resolver})) mux.HandleFunc("GET /v1/provider-discovery/status", discovery.statusHandler) From 6204e14177b956beed6549683edebdeb9b227a45 Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 16:02:11 +0300 Subject: [PATCH 3/6] fix: isolate candidate core cognitive route --- deploy/docker-compose.candidate-slot.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/deploy/docker-compose.candidate-slot.yml b/deploy/docker-compose.candidate-slot.yml index 7a15d91..4d814cb 100644 --- a/deploy/docker-compose.candidate-slot.yml +++ b/deploy/docker-compose.candidate-slot.yml @@ -63,6 +63,7 @@ services: COGNITIVE_ADMISSION_MAX_ACCEPTED_PER_HOUR: ${COGNITIVE_ADMISSION_MAX_ACCEPTED_PER_HOUR:-60} COGNITIVE_ADMISSION_MAX_INPUT_BYTES: ${COGNITIVE_ADMISSION_MAX_INPUT_BYTES:-81920} COGNITIVE_ADMISSION_MAX_OUTPUT_BYTES: ${COGNITIVE_ADMISSION_MAX_OUTPUT_BYTES:-16384} + COGNITIVE_RUNTIME_URL: http://cognitive-worker-candidate:8083 RESEARCH_RUNTIME_URL: http://research-runtime-candidate:8087 volumes: - assistant_core_secrets:/run/secrets:ro From ce7000e78ea4f80aee7ce9e6c574eb19242e76de Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 18:47:58 +0300 Subject: [PATCH 4/6] chore: revise cognitive retrieval task scope --- dev/ACTIVE_TASK.json | 2 +- ...E-002-restore-production-cognitive-route.json | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/dev/ACTIVE_TASK.json b/dev/ACTIVE_TASK.json index d7a3af1..ce2cf40 100644 --- a/dev/ACTIVE_TASK.json +++ b/dev/ACTIVE_TASK.json @@ -1 +1 @@ -{"task_file":"dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json","task_id":"GEN2-COGNITIVE-002","task_revision":1} +{"task_file":"dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json","task_id":"GEN2-COGNITIVE-002","task_revision":2} diff --git a/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json index b95ba7f..2add252 100644 --- a/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json +++ b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json @@ -1,16 +1,18 @@ { "task_id": "GEN2-COGNITIVE-002", - "task_revision": 1, + "task_revision": 2, "architecture_revision": "ARCH-GEN2-000", "base_repo_revision": "gen2-integration", "risk_tier": "E", "intent": "Восстановить доказанно рабочий production cognitive route для обычного household и memory-recall запроса через существующие Capability и Cognitive Gateway boundaries, без подмены primary route Lifeboat-ом.", "requirement_ids": ["REQ-GEN2-COGNITIVE-002-TRACE", "REQ-GEN2-COGNITIVE-002-ROUTING", "REQ-GEN2-COGNITIVE-002-RECOVERY"], "allowed_change_scope": { - "modules": ["capability", "cognitive-worker", "core-runtime", "production deployment"], + "modules": ["capability", "cognitive-worker", "core-runtime", "interaction", "production deployment"], "paths": [ "cmd/cognitive-worker/**", "cmd/core-runtime/**", + "modules/interaction/domain/gen2_context.go", + "modules/interaction/domain/gen2_context_test.go", "contracts/capability/**", "contracts/cognitive/**", "modules/capability/**", @@ -31,12 +33,12 @@ "allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 1, "new_third_party_dependencies": 0, "new_database_owner_roles": 0}, "contracts": { "consume": ["existing Capability binding lifecycle", "existing cognitive gateway/advisory contracts", "existing Supervisor ReleaseSet control plane"], - "may_change": ["typed capability/provider selection and invocation wiring only within declared paths"] + "may_change": ["typed capability/provider selection and invocation wiring only within declared paths", "the existing Interaction Gen2 retrieval projection for bounded, scoped human assertions; no new Memory owner or reader"] }, "semantic_owner": "Capability remains the sole owner of provider/model/binding lifecycle; cognitive-worker invokes providers through adapters; Core consumes the governed gateway; Supervisor alone controls traffic promotion and rollback.", - "canonical_state": ["existing Capability provider/model/binding/evaluation evidence", "no new canonical writer, owner, schema, role, or migration"], - "state_transitions": ["trace stable and candidate loaded binding heads -> correct stale/divergent lifecycle or invocation defect -> governed repair/qualification -> isolated candidate validation -> Supervisor canary -> promote or rollback"], - "side_effects_and_privileges": ["production candidate deployment and Supervisor canary/promotion are explicitly authorized", "adapters/models/** may change only after trace proves a model adapter, provider endpoint, injection, timeout, rate-limit, context budget, or invocation defect there", "cmd/core-runtime/** may change only after trace proves Core-to-worker request construction, route selection, or response handling is causal", "no direct SQL semantic mutation", "no credential, cookie, token, prompt, or user content read/emitted", "Lifeboat may be observed as fallback but cannot mask Local MEDIUM primary failure"], + "canonical_state": ["existing Capability provider/model/binding/evaluation evidence", "canonical Interaction human utterance history read through the existing Gen2 retrieval projection", "no new canonical writer, owner, schema, role, or migration"], + "state_transitions": ["trace stable and candidate loaded binding heads -> correct stale/divergent lifecycle or invocation defect -> governed repair/qualification -> scoped Interaction projection selects bounded current human assertions -> isolated candidate validation -> Supervisor canary -> promote or rollback"], + "side_effects_and_privileges": ["production candidate deployment and Supervisor canary/promotion are explicitly authorized", "adapters/models/** may change only after trace proves a model adapter, provider endpoint, injection, timeout, rate-limit, context budget, or invocation defect there", "cmd/core-runtime/** may change only after trace proves Core-to-worker request construction, route selection, or response handling is causal", "modules/interaction/domain/gen2_context.go may change only to extend the existing bounded Gen2 read projection over canonical Interaction utterances with Principal hard filtering, current applicability and relevance selection; it must not write state, become a Memory owner, or promote PersonalMemory V1 to primary", "no direct SQL semantic mutation", "no credential, cookie, token, prompt, or user content read/emitted", "Lifeboat may be observed as fallback but cannot mask Local MEDIUM primary failure"], "persistence_and_migrations": ["no schema/migration change is authorized", "adapters/postgres/capability_repository.go may change only after trace proves durable Capability head/state loading diverges from the correct persisted state; reuse its existing repository boundary"], "failure_retry_restart": ["discovery health, invocation health, and availability remain distinct", "CPU/GPU gaps must not suppress a valid Local MEDIUM", "restart reloads a durable active/validated binding head", "failed candidate rolls traffic to Supervisor LKG without stable recreation"], "assumptions": ["isolated candidate slot B and Supervisor controls from GEN2-DEPLOY-003 are available", "an existing authenticated production session may be used only through ordinary runtime interaction", "GEN2-COMPAT-OBS-001 remains paused and V1 paths remain unchanged"], @@ -44,7 +46,7 @@ "COGNITIVE-002-SCN-01: factual stable/candidate trace records Core request, requirement, binding selection, loaded binding head, fleet availability, provider eligibility, invocation result, and response/error without sensitive content", "COGNITIVE-002-SCN-02: Local MEDIUM is shown ACTIVE, VALIDATED, AVAILABLE, and actually invoked for bounded OK, Russian household, and prepared-context recall requests", "COGNITIVE-002-SCN-03: health endpoint success alone is not used as inference proof; discovery and invocation failures are separately classified", - "COGNITIVE-002-SCN-04: candidate four-component health/revision check, real canary household request, memory write/multiple turns/recall, and candidate Core plus cognitive-worker restart/recovery pass", + "COGNITIVE-002-SCN-04: candidate four-component health/revision check, real canary household request, scoped bounded arbitrary-assertion memory write/multiple turns/recall, and candidate Core plus cognitive-worker restart/recovery pass", "COGNITIVE-002-SCN-05: only after candidate success, Supervisor promotes it; evidence retains LKG and rollback readiness", "COGNITIVE-002-EXIT: ordinary household and memory-recall response use Local MEDIUM through the governed route and remain usable after candidate restart" ], From 00af176a200142bd3de67ba914e542b2299f43d5 Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 19:12:52 +0300 Subject: [PATCH 5/6] fix: compile scoped interaction assertions --- adapters/postgres/interaction_repository.go | 65 ++++++ cmd/core-runtime/cognitive_interpretation.go | 29 +++ .../cognitive_interpretation_test.go | 10 + cmd/core-runtime/main.go | 21 +- dev/ACTIVE_TASK.json | 2 +- ...02-restore-production-cognitive-route.json | 7 +- modules/interaction/domain/gen2_context.go | 203 +++++++++++++++++- .../interaction/domain/gen2_context_test.go | 56 ++++- 8 files changed, 382 insertions(+), 11 deletions(-) diff --git a/adapters/postgres/interaction_repository.go b/adapters/postgres/interaction_repository.go index 25c7bc9..30c29ee 100644 --- a/adapters/postgres/interaction_repository.go +++ b/adapters/postgres/interaction_repository.go @@ -100,6 +100,22 @@ func (r *InteractionRepository) Utterances(ctx context.Context, id interaction.C return out, rows.Err() } +// UtterancesWithProjectReferences returns canonical utterances together with +// their already-persisted Interaction-owned project references. The caller +// uses the pair only as a read projection; this method does not infer or write +// scope membership. +func (r *InteractionRepository) UtterancesWithProjectReferences(ctx context.Context, id interaction.ConversationID) ([]interaction.HumanUtterance, []interaction.ProjectReference, error) { + utterances, err := r.Utterances(ctx, id) + if err != nil { + return nil, nil, err + } + references, err := r.projectReferencesForUtterances(ctx, utterances) + if err != nil { + return nil, nil, err + } + return utterances, references, nil +} + // RecentUtterancesForPrincipal provides durable conversational context when a // client starts a fresh conversation instead of carrying the previous ID. func (r *InteractionRepository) RecentUtterancesForPrincipal(ctx context.Context, principalID identity.PrincipalID, limit int) ([]interaction.HumanUtterance, error) { @@ -118,3 +134,52 @@ func (r *InteractionRepository) RecentUtterancesForPrincipal(ctx context.Context } return out, rows.Err() } + +// RecentUtterancesForPrincipalWithProjectReferences keeps a new conversation +// within the same durable Interaction read boundary as its scoped context. +func (r *InteractionRepository) RecentUtterancesForPrincipalWithProjectReferences(ctx context.Context, principalID identity.PrincipalID, limit int) ([]interaction.HumanUtterance, []interaction.ProjectReference, error) { + utterances, err := r.RecentUtterancesForPrincipal(ctx, principalID, limit) + if err != nil { + return nil, nil, err + } + references, err := r.projectReferencesForUtterances(ctx, utterances) + if err != nil { + return nil, nil, err + } + return utterances, references, nil +} + +func (r *InteractionRepository) projectReferencesForUtterances(ctx context.Context, utterances []interaction.HumanUtterance) ([]interaction.ProjectReference, error) { + if len(utterances) == 0 { + return nil, nil + } + ids := make([]string, 0, len(utterances)) + seen := make(map[interaction.HumanUtteranceID]struct{}, len(utterances)) + for _, utterance := range utterances { + if utterance.ID == "" { + continue + } + if _, exists := seen[utterance.ID]; exists { + continue + } + seen[utterance.ID] = struct{}{} + ids = append(ids, string(utterance.ID)) + } + if len(ids) == 0 { + return nil, nil + } + rows, err := r.pool.Query(ctx, `SELECT project_reference_id,utterance_id,project_id,project_display_name,role,provenance,confidence_millis,recorded_at_unix_millis FROM interaction.project_references WHERE utterance_id = ANY($1::text[]) ORDER BY recorded_at_unix_millis,project_reference_id`, ids) + if err != nil { + return nil, err + } + defer rows.Close() + refs := make([]interaction.ProjectReference, 0) + for rows.Next() { + var ref interaction.ProjectReference + if err := rows.Scan(&ref.ID, &ref.UtteranceID, &ref.ProjectID, &ref.ProjectDisplayName, &ref.Role, &ref.Provenance, &ref.ConfidenceMillis, &ref.RecordedAtUnixMillis); err != nil { + return nil, err + } + refs = append(refs, ref) + } + return refs, rows.Err() +} diff --git a/cmd/core-runtime/cognitive_interpretation.go b/cmd/core-runtime/cognitive_interpretation.go index 10fb842..2d24ea3 100644 --- a/cmd/core-runtime/cognitive_interpretation.go +++ b/cmd/core-runtime/cognitive_interpretation.go @@ -28,6 +28,35 @@ type cognitiveInterpretationClient struct { media *http.Client } +// compileInteractionContext is the Core-side handoff from the existing +// Interaction retrieval projection to the existing Context Compiler. The +// compiler receives only already-authorized, typed fragments and applies its +// scope and byte-budget guards before the cognitive gateway sees them. +func compileInteractionContext(projection interactiondomain.ContextProjection, focusProjectID string) (string, error) { + if len(projection.Fragments) == 0 { + return projection.Text, nil + } + candidates := make([]cognitive.ContextCandidate, 0, len(projection.Fragments)) + for _, fragment := range projection.Fragments { + candidates = append(candidates, cognitive.ContextCandidate{ + Excerpt: cognitive.ContextExcerpt{ID: cognitive.ContextExcerptID("interaction:" + string(fragment.UtteranceID)), SourceKind: "interaction-gen2-retrieval", SourceID: "interaction:utterances", Revision: 1, Sensitivity: cognitive.SensitivityPrivateAllowed, Text: fragment.Text}, + Relevance: fragment.Relevance, + Lane: "interaction", + ContextScopeRef: fragment.ScopeRef, + FreshnessState: "CURRENT", + }) + } + bundle, err := cognitive.CompileContext(cognitive.ContextCompileInput{Candidates: candidates, DataPolicy: capability.DataPolicyLocalOnly, MaxBytes: 2048, ContextScopeRef: focusProjectID, FreshnessRequirement: "conversation-current", RiskClass: "low"}) + if err != nil { + return "", err + } + parts := make([]string, 0, len(bundle.Excerpts)) + for _, excerpt := range bundle.Excerpts { + parts = append(parts, excerpt.Text) + } + return strings.Join(parts, "\n"), nil +} + const ( // Household interpretation and response review are intentionally compact // calls. Keeping their output bounded prevents a loaded local model from diff --git a/cmd/core-runtime/cognitive_interpretation_test.go b/cmd/core-runtime/cognitive_interpretation_test.go index 0c9fb13..938e3c6 100644 --- a/cmd/core-runtime/cognitive_interpretation_test.go +++ b/cmd/core-runtime/cognitive_interpretation_test.go @@ -70,6 +70,16 @@ func TestAnswerStableKnowledgeUsesLocalOnlyCognitiveRoute(t *testing.T) { } } +func TestCompileInteractionContextAppliesTypedScopeBeforeGateway(t *testing.T) { + context, err := compileInteractionContext(interactiondomain.ContextProjection{Fragments: []interactiondomain.ContextFragment{ + {UtteranceID: "a", Text: "контрольный код = ALPHA", ScopeRef: "company-a", Relevance: 2}, + {UtteranceID: "b", Text: "контрольный код = BETA", ScopeRef: "company-b", Relevance: 3}, + }}, "company-a") + if err != nil || context != "контрольный код = ALPHA" { + t.Fatalf("context=%q err=%v", context, err) + } +} + func TestGenerateImageUsesDedicatedCognitiveMediaRoute(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != "/v1/multimodal/generate-image" { diff --git a/cmd/core-runtime/main.go b/cmd/core-runtime/main.go index 9083494..bf3e92d 100644 --- a/cmd/core-runtime/main.go +++ b/cmd/core-runtime/main.go @@ -571,9 +571,10 @@ func main() { travelContinuation := false var previousTask *interaction.HumanUtterance var conversationHistory []interaction.HumanUtterance + var contextProjectReferences []interaction.ProjectReference if request.ConversationID != "" { var historyErr error - conversationHistory, historyErr = interactionRepository.Utterances(r.Context(), conversation.ID) + conversationHistory, contextProjectReferences, historyErr = interactionRepository.UtterancesWithProjectReferences(r.Context(), conversation.ID) if historyErr != nil { log.Printf("interaction conversation history unavailable: %v", historyErr) } @@ -581,14 +582,24 @@ func main() { // Keep durable user context available even when the web client carries a // conversation ID; a new or rotated conversation must not erase learned // preferences. - recentUserHistory, historyErr := interactionRepository.RecentUtterancesForPrincipal(r.Context(), session.PrincipalID, 64) + recentUserHistory, recentProjectReferences, historyErr := interactionRepository.RecentUtterancesForPrincipalWithProjectReferences(r.Context(), session.PrincipalID, 64) if historyErr != nil { log.Printf("interaction principal history unavailable: %v", historyErr) } else { log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory)) } conversationHistory = append(conversationHistory, recentUserHistory...) - gen2Context := interactiondomain.BuildScopedGen2Context(conversationHistory, string(session.PrincipalID)) + contextProjectReferences = append(contextProjectReferences, recentProjectReferences...) + focusProjectID := "" + if previousFocus != nil { + focusProjectID = string(previousFocus.ProjectID) + } + gen2Context := interactiondomain.BuildScopedGen2ContextForQuery(conversationHistory, contextProjectReferences, string(session.PrincipalID), focusProjectID, effectiveTaskMessage) + if compiledContext, contextErr := compileInteractionContext(gen2Context, focusProjectID); contextErr != nil { + log.Printf("interaction context compilation unavailable: %v", contextErr) + } else { + gen2Context.Text = compiledContext + } if gen2Context.UsedPersonalMemoryFallback { telemetry.RecordCompatibility("personal-memory-fallback", "core-runtime", "read", "gen2-context-empty", true, true, false, "USED", utterance.CorrelationID, string(session.PrincipalID), now) } @@ -887,7 +898,7 @@ func main() { planningReply = retrievedMemoryReply needsCognition = false } - if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired && shouldRunGeneralResearch(semantic.InformationRequestKind) { + if hasChatRoute(routePlan, chatRouteResearch) && len(gen2Context.Fragments) == 0 && semantic.Interpretation.Clarification != interaction.ClarificationRequired && shouldRunGeneralResearch(semantic.InformationRequestKind) { researchAttempted = true if planID, idErr := ids.New(); idErr == nil { parts := interactiondomain.IndependentRequestParts(effectiveTaskMessage) @@ -954,7 +965,7 @@ func main() { } } canGenerateTextReply := shouldGenerateNonMutatingTextDirective(semantic, routePlan, helpPath, creativeRequest) && planningReply == deterministicReply - if (planningReply == "" && needsCognition && semantic.Interpretation.SpeechAct == interaction.SpeechActQuestion || canGenerateTextReply) && !hasChatRoute(routePlan, chatRouteResearch) && !creativeRequest { + if (planningReply == "" && needsCognition && semantic.Interpretation.SpeechAct == interaction.SpeechActQuestion || canGenerateTextReply) && (!hasChatRoute(routePlan, chatRouteResearch) || len(gen2Context.Fragments) > 0) && !creativeRequest { answerCtx, cancelAnswer := context.WithTimeout(r.Context(), 12*time.Second) answer, answerErr := cognitiveClient.AnswerStableKnowledge(answerCtx, session, effectiveTaskMessage, gen2Context.Text, cognitive.TaskMeaning{ SpeechAct: string(semantic.Interpretation.SpeechAct), CapabilityHints: toCapabilityKinds(semantic.CapabilityHints), RequestedOutcome: semantic.Interpretation.RequestedOutcome, InformationRequestKind: semantic.InformationRequestKind, ConfidenceMillis: semantic.Interpretation.ConfidenceMillis, diff --git a/dev/ACTIVE_TASK.json b/dev/ACTIVE_TASK.json index ce2cf40..7ad23c8 100644 --- a/dev/ACTIVE_TASK.json +++ b/dev/ACTIVE_TASK.json @@ -1 +1 @@ -{"task_file":"dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json","task_id":"GEN2-COGNITIVE-002","task_revision":2} +{"task_file":"dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json","task_id":"GEN2-COGNITIVE-002","task_revision":3} diff --git a/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json index 2add252..d6f2c73 100644 --- a/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json +++ b/dev/tasks/GEN2-COGNITIVE-002-restore-production-cognitive-route.json @@ -1,6 +1,6 @@ { "task_id": "GEN2-COGNITIVE-002", - "task_revision": 2, + "task_revision": 3, "architecture_revision": "ARCH-GEN2-000", "base_repo_revision": "gen2-integration", "risk_tier": "E", @@ -13,6 +13,7 @@ "cmd/core-runtime/**", "modules/interaction/domain/gen2_context.go", "modules/interaction/domain/gen2_context_test.go", + "adapters/postgres/interaction_repository.go", "contracts/capability/**", "contracts/cognitive/**", "modules/capability/**", @@ -36,9 +37,9 @@ "may_change": ["typed capability/provider selection and invocation wiring only within declared paths", "the existing Interaction Gen2 retrieval projection for bounded, scoped human assertions; no new Memory owner or reader"] }, "semantic_owner": "Capability remains the sole owner of provider/model/binding lifecycle; cognitive-worker invokes providers through adapters; Core consumes the governed gateway; Supervisor alone controls traffic promotion and rollback.", - "canonical_state": ["existing Capability provider/model/binding/evaluation evidence", "canonical Interaction human utterance history read through the existing Gen2 retrieval projection", "no new canonical writer, owner, schema, role, or migration"], + "canonical_state": ["existing Capability provider/model/binding/evaluation evidence", "canonical Interaction human utterance history and existing typed ProjectReference read through the existing Gen2 retrieval projection", "no new canonical writer, owner, schema, role, or migration"], "state_transitions": ["trace stable and candidate loaded binding heads -> correct stale/divergent lifecycle or invocation defect -> governed repair/qualification -> scoped Interaction projection selects bounded current human assertions -> isolated candidate validation -> Supervisor canary -> promote or rollback"], - "side_effects_and_privileges": ["production candidate deployment and Supervisor canary/promotion are explicitly authorized", "adapters/models/** may change only after trace proves a model adapter, provider endpoint, injection, timeout, rate-limit, context budget, or invocation defect there", "cmd/core-runtime/** may change only after trace proves Core-to-worker request construction, route selection, or response handling is causal", "modules/interaction/domain/gen2_context.go may change only to extend the existing bounded Gen2 read projection over canonical Interaction utterances with Principal hard filtering, current applicability and relevance selection; it must not write state, become a Memory owner, or promote PersonalMemory V1 to primary", "no direct SQL semantic mutation", "no credential, cookie, token, prompt, or user content read/emitted", "Lifeboat may be observed as fallback but cannot mask Local MEDIUM primary failure"], + "side_effects_and_privileges": ["production candidate deployment and Supervisor canary/promotion are explicitly authorized", "adapters/models/** may change only after trace proves a model adapter, provider endpoint, injection, timeout, rate-limit, context budget, or invocation defect there", "cmd/core-runtime/** may change only after trace proves Core-to-worker request construction, route selection, or response handling is causal", "modules/interaction/domain/gen2_context.go may change only to extend the existing bounded Gen2 read projection over canonical Interaction utterances with Principal hard filtering, current applicability and relevance selection; it must not write state, become a Memory owner, or promote PersonalMemory V1 to primary", "adapters/postgres/interaction_repository.go may only read the already-persisted typed interaction.ProjectReference records for the selected canonical Interaction utterances; it may not create schema, write state, or bypass Interaction ownership", "no direct SQL semantic mutation", "no credential, cookie, token, prompt, or user content read/emitted", "Lifeboat may be observed as fallback but cannot mask Local MEDIUM primary failure"], "persistence_and_migrations": ["no schema/migration change is authorized", "adapters/postgres/capability_repository.go may change only after trace proves durable Capability head/state loading diverges from the correct persisted state; reuse its existing repository boundary"], "failure_retry_restart": ["discovery health, invocation health, and availability remain distinct", "CPU/GPU gaps must not suppress a valid Local MEDIUM", "restart reloads a durable active/validated binding head", "failed candidate rolls traffic to Supervisor LKG without stable recreation"], "assumptions": ["isolated candidate slot B and Supervisor controls from GEN2-DEPLOY-003 are available", "an existing authenticated production session may be used only through ordinary runtime interaction", "GEN2-COMPAT-OBS-001 remains paused and V1 paths remain unchanged"], diff --git a/modules/interaction/domain/gen2_context.go b/modules/interaction/domain/gen2_context.go index 21a6e50..d7172ec 100644 --- a/modules/interaction/domain/gen2_context.go +++ b/modules/interaction/domain/gen2_context.go @@ -1,11 +1,31 @@ package domain -import "git.cin.su/m/Assistant/contracts/interaction" +import ( + "sort" + "strings" + + "git.cin.su/m/Assistant/contracts/interaction" +) + +const ( + gen2ContextMaxCandidates = 4 + gen2ContextMaxBytes = 2048 +) + +type ContextFragment struct { + UtteranceID interaction.HumanUtteranceID + Text string + ScopeRef string + Relevance int + Historical bool +} type ContextProjection struct { Text string Source string UsedPersonalMemoryFallback bool + Fragments []ContextFragment + Historical []ContextFragment } // BuildGen2Context is a read-side projection over canonical utterance history. @@ -19,6 +39,14 @@ func BuildGen2Context(history []interaction.HumanUtterance) ContextProjection { // filter prevents accidental cross-principal projection when a mixed source // is passed during degraded operation. func BuildScopedGen2Context(history []interaction.HumanUtterance, principalID string) ContextProjection { + return BuildScopedGen2ContextForQuery(history, nil, principalID, "", "") +} + +// BuildScopedGen2ContextForQuery projects bounded, explicit human assertions +// from the canonical Interaction history. Principal and typed project refs are +// hard filters before relevance ranking. Older values remain lineage in +// Historical and are never represented as the current value. +func BuildScopedGen2ContextForQuery(history []interaction.HumanUtterance, references []interaction.ProjectReference, principalID, focusProjectID, query string) ContextProjection { if principalID != "" { scoped := make([]interaction.HumanUtterance, 0, len(history)) for _, item := range history { @@ -28,9 +56,182 @@ func BuildScopedGen2Context(history []interaction.HumanUtterance, principalID st } history = scoped } + projectRefs := make(map[interaction.HumanUtteranceID][]interaction.ProjectReference, len(references)) + for _, ref := range references { + projectRefs[ref.UtteranceID] = append(projectRefs[ref.UtteranceID], ref) + } + assertions := explicitAssertionCandidates(history, projectRefs, focusProjectID, query) + if len(assertions) > 0 { + current, historical := selectCurrentAssertions(assertions) + return contextProjectionFromAssertions(current, historical) + } text := CompilePersonalMemory(history).ContextText() if text != "" { return ContextProjection{Text: text, Source: "retrieval:interaction-utterances"} } return ContextProjection{Text: text, Source: "personal-memory-v1-fallback", UsedPersonalMemoryFallback: true} } + +type assertionCandidate struct { + fragment ContextFragment + subject string + observed int64 +} + +func explicitAssertionCandidates(history []interaction.HumanUtterance, projectRefs map[interaction.HumanUtteranceID][]interaction.ProjectReference, focusProjectID, query string) []assertionCandidate { + queryTokens := significantContextTokens(query) + result := make([]assertionCandidate, 0) + for _, utterance := range history { + subject, value, ok := explicitAssertion(utterance.Content) + if !ok { + continue + } + refs := projectRefs[utterance.ID] + scopeRef := "" + if focusProjectID != "" { + matched := false + for _, ref := range refs { + if string(ref.ProjectID) == focusProjectID { + matched = true + scopeRef = focusProjectID + break + } + } + if !matched { + continue + } + } else if len(refs) == 1 { + scopeRef = string(refs[0].ProjectID) + } + relevance := contextRelevance(subject, queryTokens) + if len(queryTokens) > 0 && relevance == 0 { + continue + } + result = append(result, assertionCandidate{ + fragment: ContextFragment{UtteranceID: utterance.ID, Text: subject + " = " + value, ScopeRef: scopeRef, Relevance: relevance}, + subject: normalizedContextSubject(subject), + observed: utterance.ReceivedAtUnixMillis, + }) + } + return result +} + +func selectCurrentAssertions(candidates []assertionCandidate) ([]ContextFragment, []ContextFragment) { + latest := make(map[string]assertionCandidate) + for _, candidate := range candidates { + current, exists := latest[candidate.subject] + if !exists || candidate.observed > current.observed || candidate.observed == current.observed && candidate.fragment.UtteranceID > current.fragment.UtteranceID { + latest[candidate.subject] = candidate + } + } + current := make([]ContextFragment, 0, len(latest)) + historical := make([]ContextFragment, 0, len(candidates)-len(latest)) + for _, candidate := range candidates { + selected := latest[candidate.subject] + if candidate.fragment.UtteranceID == selected.fragment.UtteranceID { + current = append(current, candidate.fragment) + continue + } + candidate.fragment.Historical = true + historical = append(historical, candidate.fragment) + } + sort.SliceStable(current, func(i, j int) bool { + if current[i].Relevance != current[j].Relevance { + return current[i].Relevance > current[j].Relevance + } + return current[i].UtteranceID > current[j].UtteranceID + }) + return current, historical +} + +func contextProjectionFromAssertions(current, historical []ContextFragment) ContextProjection { + selected := make([]ContextFragment, 0, len(current)) + text := make([]string, 0, len(current)) + usedBytes := 0 + for _, candidate := range current { + if len(selected) == gen2ContextMaxCandidates { + break + } + bytes := len([]byte(candidate.Text)) + if bytes == 0 || usedBytes+bytes > gen2ContextMaxBytes { + continue + } + usedBytes += bytes + selected = append(selected, candidate) + text = append(text, candidate.Text) + } + if len(selected) == 0 { + return ContextProjection{Source: "retrieval:interaction-assertions", Historical: historical} + } + return ContextProjection{Text: strings.Join(text, "\n"), Source: "retrieval:interaction-assertions", Fragments: selected, Historical: historical} +} + +func explicitAssertion(message string) (string, string, bool) { + text := strings.TrimSpace(StripAssistantVocative(message)) + if text == "" || strings.Contains(text, "?") { + return "", "", false + } + lower := strings.ToLower(text) + if index := strings.Index(lower, "запомни:"); index >= 0 { + text = strings.TrimSpace(text[index+len("запомни:"):]) + lower = strings.ToLower(text) + } + for _, prefix := range []string{"запомни:", "запомни", "помни:"} { + if strings.HasPrefix(lower, prefix) { + text = strings.TrimSpace(text[len(prefix):]) + break + } + } + for _, separator := range []string{"=", "—"} { + subject, value, found := strings.Cut(text, separator) + if !found { + continue + } + subject, value = strings.TrimSpace(subject), strings.TrimSpace(value) + if subject != "" && value != "" && len([]rune(subject)) <= 160 && len([]rune(value)) <= 512 { + return subject, value, true + } + } + return "", "", false +} + +func normalizedContextSubject(subject string) string { + return strings.Join(significantContextTokens(subject), " ") +} + +func significantContextTokens(value string) []string { + ignored := map[string]struct{}{"какой": {}, "какая": {}, "какое": {}, "какие": {}, "текущий": {}, "текущая": {}, "текущее": {}, "я": {}, "ты": {}, "назвал": {}, "назвала": {}, "сообщил": {}, "сообщила": {}} + result := make([]string, 0) + seen := make(map[string]struct{}) + for _, token := range semanticTokens(value) { + if len([]rune(token)) < 3 { + continue + } + if _, skip := ignored[token]; skip { + continue + } + if _, duplicate := seen[token]; duplicate { + continue + } + seen[token] = struct{}{} + result = append(result, token) + } + return result +} + +func contextRelevance(subject string, queryTokens []string) int { + if len(queryTokens) == 0 { + return 1 + } + subjectTokens := significantContextTokens(subject) + matched := 0 + for _, query := range queryTokens { + for _, token := range subjectTokens { + if query == token { + matched++ + break + } + } + } + return matched +} diff --git a/modules/interaction/domain/gen2_context_test.go b/modules/interaction/domain/gen2_context_test.go index 937df92..6d741d7 100644 --- a/modules/interaction/domain/gen2_context_test.go +++ b/modules/interaction/domain/gen2_context_test.go @@ -32,7 +32,61 @@ func TestGen2ContextProjectsExplicitRememberedAssertion(t *testing.T) { got := domain.BuildScopedGen2Context([]interaction.HumanUtterance{ {ID: "assertion", PrincipalID: "principal-1", Content: "Для этого разговора запомни: мой тестовый цвет — синий.", ReceivedAtUnixMillis: 1}, }, "principal-1") - if got.Source != "retrieval:interaction-utterances" || got.UsedPersonalMemoryFallback || !strings.Contains(got.Text, "тестовый цвет — синий") { + if got.Source != "retrieval:interaction-assertions" || got.UsedPersonalMemoryFallback || !strings.Contains(got.Text, "тестовый цвет = синий") { t.Fatalf("remembered assertion was not projected: %#v", got) } } + +func TestGen2ContextSelectsArbitraryRelevantCurrentAssertion(t *testing.T) { + history := []interaction.HumanUtterance{ + {ID: "assertion", PrincipalID: "principal-1", Content: "контрольный код = ORBIT-731", ReceivedAtUnixMillis: 1}, + {ID: "turn-1", PrincipalID: "principal-1", Content: "Спасибо", ReceivedAtUnixMillis: 2}, + {ID: "turn-2", PrincipalID: "principal-1", Content: "Продолжим", ReceivedAtUnixMillis: 3}, + } + got := domain.BuildScopedGen2ContextForQuery(history, nil, "principal-1", "", "Какой контрольный код я назвал?") + if got.Source != "retrieval:interaction-assertions" || !strings.Contains(got.Text, "ORBIT-731") || len(got.Fragments) != 1 { + t.Fatalf("arbitrary assertion was not selected: %#v", got) + } +} + +func TestGen2ContextKeepsHistoricalAssertionOutOfCurrentProjection(t *testing.T) { + history := []interaction.HumanUtterance{ + {ID: "old", PrincipalID: "principal-1", Content: "контрольный код = OLD-111", ReceivedAtUnixMillis: 1}, + {ID: "new", PrincipalID: "principal-1", Content: "контрольный код = NEW-222", ReceivedAtUnixMillis: 2}, + } + got := domain.BuildScopedGen2ContextForQuery(history, nil, "principal-1", "", "Какой контрольный код?") + if strings.Contains(got.Text, "OLD-111") || !strings.Contains(got.Text, "NEW-222") || len(got.Historical) != 1 || !strings.Contains(got.Historical[0].Text, "OLD-111") { + t.Fatalf("current/historical assertion separation failed: %#v", got) + } +} + +func TestGen2ContextHardFiltersProjectReferencesBeforeRanking(t *testing.T) { + history := []interaction.HumanUtterance{ + {ID: "a", PrincipalID: "principal-1", Content: "контрольный код = ALPHA", ReceivedAtUnixMillis: 1}, + {ID: "b", PrincipalID: "principal-1", Content: "контрольный код = BETA", ReceivedAtUnixMillis: 2}, + } + references := []interaction.ProjectReference{ + {ID: "ref-a", UtteranceID: "a", ProjectID: "company-a"}, + {ID: "ref-b", UtteranceID: "b", ProjectID: "company-b"}, + } + for projectID, expected := range map[string]struct{ want, absent string }{ + "company-a": {want: "ALPHA", absent: "BETA"}, + "company-b": {want: "BETA", absent: "ALPHA"}, + } { + got := domain.BuildScopedGen2ContextForQuery(history, references, "principal-1", projectID, "Какой контрольный код?") + if !strings.Contains(got.Text, expected.want) || strings.Contains(got.Text, expected.absent) || len(got.Fragments) != 1 || got.Fragments[0].ScopeRef != projectID { + t.Fatalf("scope %s leaked context: %#v", projectID, got) + } + } +} + +func TestGen2ContextExcludesIrrelevantAssertionsFromBoundedProjection(t *testing.T) { + history := []interaction.HumanUtterance{ + {ID: "code", PrincipalID: "principal-1", Content: "контрольный код = ORBIT-731", ReceivedAtUnixMillis: 1}, + {ID: "city", PrincipalID: "principal-1", Content: "город встречи = Казань", ReceivedAtUnixMillis: 2}, + } + got := domain.BuildScopedGen2ContextForQuery(history, nil, "principal-1", "", "Какой контрольный код?") + if strings.Contains(got.Text, "Казань") || len(got.Fragments) != 1 { + t.Fatalf("irrelevant assertion entered bounded projection: %#v", got) + } +} From e1b9c7ca849a2e0cbac31921d9104d2a51d14785 Mon Sep 17 00:00:00 2001 From: Mikhail Date: Sun, 30 Aug 2026 19:54:48 +0300 Subject: [PATCH 6/6] docs: record cognitive core verification amendment --- docs/PROJECT_STATUS.md | 5 ++- ...ognitive-002-core-verified-2026-08-30.json | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 docs/evidence/gen2-cognitive-002-core-verified-2026-08-30.json diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index b4fb76f..4126fc7 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -9,8 +9,9 @@ - `PROVIDER_GAPS = CPU_FAST_UNAVAILABLE; GPU_UNAVAILABLE`; Local MEDIUM remains the primary route and Lifeboat remains fallback per existing M5 evidence. - `GEN2_M6_FINAL_STATUS = NOT_FINAL_PASS_RETIREMENT_GAP_REMAINS`; FULL_FINAL technical checks passed, but no final M6 baseline tag is created because active V1 compatibility callers were not proven safe to retire. - `GEN2_M6_FINAL_EVIDENCE = docs/evidence/gen2-030-final-acceptance-2026-08-30.json`. -- `GEN2_FINAL_STATUS = GEN2_CORE_ACCEPTED / V1_COMPATIBILITY_RETAINED / UI_DEFERRED`. -- `GEN2-COMPAT-OBS-001 = INSTRUMENTATION_COMMITTED; PRODUCTION_OBSERVATION_BLOCKED_BY_MISSING_CAPABILITY`; evidence: `docs/evidence/gen2-compat-obs-001-blocked-2026-08-30.json`. No V1 path is `SAFE_TO_RETIRE`; no retirement task was created. +- `GEN2-COGNITIVE-002 = IMPLEMENTED / CORE_VERIFIED / BROWSER_ACCEPTANCE_DEFERRED_BY_OWNER`; non-browser evidence: `docs/evidence/gen2-cognitive-002-core-verified-2026-08-30.json`. +- `GEN2-COMPAT-OBS-001 = OBSERVATION_DEFERRED_BY_OWNER`; instrumentation remains committed, but no production observation window or retirement decision is claimed. No V1 path is `SAFE_TO_RETIRE`; no retirement task was created. +- `GEN2_FINAL_STATUS = GEN2_CORE_ACCEPTED / V1_COMPATIBILITY_RETAINED / BROWSER_ACCEPTANCE_DEFERRED / COMPAT_OBSERVATION_DEFERRED`. - `NEXT_EVOLUTION_QUEUE = instrument bounded compatibility usage, observe, then retire only individually proven paths under a future FULL_RETIREMENT gate; no Gen3 or new feature work is started. ## Current audit delta — 2026-08-24 diff --git a/docs/evidence/gen2-cognitive-002-core-verified-2026-08-30.json b/docs/evidence/gen2-cognitive-002-core-verified-2026-08-30.json new file mode 100644 index 0000000..f265aa7 --- /dev/null +++ b/docs/evidence/gen2-cognitive-002-core-verified-2026-08-30.json @@ -0,0 +1,43 @@ +{ + "evidence_id": "gen2-cognitive-002-core-verified-2026-08-30", + "task_id": "GEN2-COGNITIVE-002", + "task_revision": 3, + "commit": "00af176a200142bd3de67ba914e542b2299f43d5", + "status": "IMPLEMENTED / CORE_VERIFIED / BROWSER_ACCEPTANCE_DEFERRED_BY_OWNER", + "owner_amendment": { + "browser_authenticated_acceptance": "DEFERRED_BY_OWNER", + "compatibility_observation": "DEFERRED_BY_OWNER", + "v1_retirement": "NOT_AUTHORIZED" + }, + "non_browser_acceptance": { + "targeted_tests": "PASS: cmd/cognitive-worker, cmd/core-runtime, modules/interaction/domain, adapters/postgres", + "targeted_vet": "PASS: same packages", + "governance": ["preflight PASS", "check-diff PASS", "independent PASS", "git diff --check PASS"], + "scoped_retrieval": [ + "arbitrary assertion retrieval", + "current value selected while historical value is retained", + "ProjectReference hard scope isolation before relevance ranking", + "irrelevant assertions excluded from bounded context" + ], + "context_compiler": "PASS: bounded typed Interaction fragments are compiled before the cognitive gateway request", + "candidate_slot_b": { + "components": "creator-web, core-runtime, cognitive-worker, research-runtime healthy", + "restart": "candidate core-runtime and cognitive-worker restarted; both health and ready endpoints recovered", + "local_medium": "governed gateway advisory completed after restart" + } + }, + "preserved_invariants": [ + "Capability remains canonical owner of binding lifecycle", + "Interaction remains canonical owner of utterances and ProjectReference", + "no direct semantic SQL update", + "PersonalMemory V1 is not restored as primary retrieval", + "Lifeboat is fallback, not proof of Local MEDIUM" + ], + "not_claimed": [ + "browser/authenticated production acceptance", + "production promotion", + "compatibility telemetry observation", + "V1 retirement readiness" + ], + "rollback": "Supervisor release rollback returns traffic to the stable last-known-good ReleaseSet; stable containers are not recreated." +}