Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b52920ab | ||
|
|
57fb572d5b | ||
|
|
0849e9c4aa | ||
|
|
51fa9ea506 | ||
|
|
2cf1fb5c5e | ||
|
|
4f06720e3f | ||
|
|
cdc8eea1a7 | ||
|
|
9f717d720e | ||
|
|
3b5c0ff56d | ||
|
|
9cbf6c7536 | ||
|
|
9650eefcb4 | ||
|
|
1ed28ef77a | ||
|
|
c56610fa75 | ||
|
|
3d7836d37c | ||
|
|
0482e6ac14 | ||
|
|
526368be7e | ||
|
|
3c2d8a38d7 | ||
|
|
cabf386203 | ||
|
|
f9bd267c04 | ||
|
|
b041a94f71 | ||
|
|
814c9e1d32 | ||
|
|
b93715867d | ||
|
|
009314e930 | ||
|
|
0954c8f4ef | ||
|
|
0a2599cfa6 | ||
|
|
ae9933ee84 | ||
|
|
7a59abc608 | ||
|
|
6e0cf3cd1d | ||
|
|
d7e77ea3dd | ||
|
|
47fd0c4b02 | ||
|
|
df9181ef6a | ||
|
|
b0d31012da | ||
|
|
8d149b2b9d | ||
|
|
0d10e6fd82 | ||
|
|
9aa5771f55 | ||
|
|
75abfb204b | ||
|
|
b0ee54153b | ||
|
|
26cf85108a | ||
|
|
7eb2f5f313 | ||
|
|
39a27102c9 | ||
|
|
7ac9a2697c | ||
|
|
f2e8ec08c5 | ||
|
|
1cfbb4ae66 | ||
|
|
7618a0bcbe | ||
|
|
dcdc9a2e64 | ||
|
|
5783faf9dc | ||
|
|
9a968fe2f6 | ||
|
|
41d4d7202f | ||
|
|
ed3932c57a | ||
|
|
3367361483 | ||
|
|
51638d6e8c | ||
|
|
0a1ad9f7d5 | ||
|
|
4d51e65226 | ||
|
|
11a6a23f6e | ||
|
|
ce666bbc43 | ||
|
|
64870798b9 |
@@ -322,18 +322,18 @@ func (r *CapabilityRepository) LoadActiveBinding(ctx context.Context, capability
|
|||||||
|
|
||||||
func (r *CapabilityRepository) SaveProviderInstance(ctx context.Context, value capability.ProviderInstance) error {
|
func (r *CapabilityRepository) SaveProviderInstance(ctx context.Context, value capability.ProviderInstance) error {
|
||||||
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances
|
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances
|
||||||
(provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis)
|
(provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis,billing_mode,auth_mode,input_cost_micros,output_cost_micros,request_cost_micros)
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT DO NOTHING`, value.ID, value.Revision, value.Kind,
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) ON CONFLICT DO NOTHING`, value.ID, value.Revision, value.Kind,
|
||||||
value.EndpointRef, value.CredentialRef, value.Enabled, value.Qualification, value.Health, value.ObservedAtUnixMillis)
|
value.EndpointRef, value.CredentialRef, value.Enabled, value.Qualification, value.Health, value.ObservedAtUnixMillis, value.BillingMode, value.AuthMode, value.InputCostMicros, value.OutputCostMicros, value.RequestCostMicros)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *CapabilityRepository) SaveModelDescriptor(ctx context.Context, value capability.ModelDescriptor) error {
|
func (r *CapabilityRepository) SaveModelDescriptor(ctx context.Context, value capability.ModelDescriptor) error {
|
||||||
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors
|
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors
|
||||||
(model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis)
|
(model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis,intelligence_score_millis)
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT DO NOTHING`, value.ID, value.Revision,
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT DO NOTHING`, value.ID, value.Revision,
|
||||||
value.ProviderInstanceID, value.ProviderModelID, value.Fingerprint, value.MaxContextBytes, value.Modalities,
|
value.ProviderInstanceID, value.ProviderModelID, value.Fingerprint, value.MaxContextBytes, value.Modalities,
|
||||||
value.Capabilities, value.Qualification, value.Health, value.ObservedAtUnixMillis)
|
value.Capabilities, value.Qualification, value.Health, value.ObservedAtUnixMillis, value.IntelligenceScoreMillis)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,8 +349,8 @@ func (r *CapabilityRepository) SaveCognitiveBinding(ctx context.Context, value c
|
|||||||
func (r *CapabilityRepository) LoadCognitiveCandidates(ctx context.Context, capabilityID capability.CapabilityID, owner identity.PrincipalID) ([]capability.ResolvedCognitiveBinding, error) {
|
func (r *CapabilityRepository) LoadCognitiveCandidates(ctx context.Context, capabilityID capability.CapabilityID, owner identity.PrincipalID) ([]capability.ResolvedCognitiveBinding, error) {
|
||||||
rows, err := r.pool.Query(ctx, `SELECT
|
rows, err := r.pool.Query(ctx, `SELECT
|
||||||
b.binding_id,b.revision,b.capability_id,b.owner_principal_id,b.provider_instance_id,b.provider_revision,b.model_descriptor_id,b.model_revision,b.data_policy,b.qualification,b.activation,b.health,b.limit_policy_ref,
|
b.binding_id,b.revision,b.capability_id,b.owner_principal_id,b.provider_instance_id,b.provider_revision,b.model_descriptor_id,b.model_revision,b.data_policy,b.qualification,b.activation,b.health,b.limit_policy_ref,
|
||||||
p.provider_instance_id,p.revision,p.provider_kind,p.endpoint_ref,COALESCE(p.credential_ref,''),p.enabled,p.qualification,COALESCE(ph.health,p.health),GREATEST(p.observed_at_unix_millis,COALESCE(ph.observed_at_unix_millis,0)),
|
p.provider_instance_id,p.revision,p.provider_kind,p.endpoint_ref,COALESCE(p.credential_ref,''),p.enabled,p.qualification,COALESCE(ph.health,p.health),GREATEST(p.observed_at_unix_millis,COALESCE(ph.observed_at_unix_millis,0)),p.billing_mode,p.auth_mode,p.input_cost_micros,p.output_cost_micros,p.request_cost_micros,
|
||||||
m.model_descriptor_id,m.revision,m.provider_instance_id,m.provider_model_id,m.fingerprint,m.max_context_bytes,m.modalities,m.capabilities,m.qualification,COALESCE(ma.health,m.health),GREATEST(m.observed_at_unix_millis,COALESCE(ma.observed_at_unix_millis,0))
|
m.model_descriptor_id,m.revision,m.provider_instance_id,m.provider_model_id,m.fingerprint,m.max_context_bytes,m.modalities,m.capabilities,m.qualification,COALESCE(ma.health,m.health),GREATEST(m.observed_at_unix_millis,COALESCE(ma.observed_at_unix_millis,0)),m.intelligence_score_millis
|
||||||
FROM capability.cognitive_binding_revision_heads bh
|
FROM capability.cognitive_binding_revision_heads bh
|
||||||
JOIN capability.cognitive_bindings b ON b.binding_id=bh.binding_id AND b.revision=bh.revision
|
JOIN capability.cognitive_bindings b ON b.binding_id=bh.binding_id AND b.revision=bh.revision
|
||||||
JOIN capability.cognitive_provider_instances p ON p.provider_instance_id=b.provider_instance_id AND p.revision=b.provider_revision
|
JOIN capability.cognitive_provider_instances p ON p.provider_instance_id=b.provider_instance_id AND p.revision=b.provider_revision
|
||||||
@@ -366,8 +366,8 @@ func (r *CapabilityRepository) LoadCognitiveCandidates(ctx context.Context, capa
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var value capability.ResolvedCognitiveBinding
|
var value capability.ResolvedCognitiveBinding
|
||||||
err = rows.Scan(&value.Binding.ID, &value.Binding.Revision, &value.Binding.CapabilityID, &value.Binding.OwnerPrincipalID, &value.Binding.ProviderInstanceID, &value.Binding.ProviderRevision, &value.Binding.ModelDescriptorID, &value.Binding.ModelRevision, &value.Binding.DataPolicy, &value.Binding.Qualification, &value.Binding.Activation, &value.Binding.Health, &value.Binding.LimitPolicyRef,
|
err = rows.Scan(&value.Binding.ID, &value.Binding.Revision, &value.Binding.CapabilityID, &value.Binding.OwnerPrincipalID, &value.Binding.ProviderInstanceID, &value.Binding.ProviderRevision, &value.Binding.ModelDescriptorID, &value.Binding.ModelRevision, &value.Binding.DataPolicy, &value.Binding.Qualification, &value.Binding.Activation, &value.Binding.Health, &value.Binding.LimitPolicyRef,
|
||||||
&value.Provider.ID, &value.Provider.Revision, &value.Provider.Kind, &value.Provider.EndpointRef, &value.Provider.CredentialRef, &value.Provider.Enabled, &value.Provider.Qualification, &value.Provider.Health, &value.Provider.ObservedAtUnixMillis,
|
&value.Provider.ID, &value.Provider.Revision, &value.Provider.Kind, &value.Provider.EndpointRef, &value.Provider.CredentialRef, &value.Provider.Enabled, &value.Provider.Qualification, &value.Provider.Health, &value.Provider.ObservedAtUnixMillis, &value.Provider.BillingMode, &value.Provider.AuthMode, &value.Provider.InputCostMicros, &value.Provider.OutputCostMicros, &value.Provider.RequestCostMicros,
|
||||||
&value.Model.ID, &value.Model.Revision, &value.Model.ProviderInstanceID, &value.Model.ProviderModelID, &value.Model.Fingerprint, &value.Model.MaxContextBytes, &value.Model.Modalities, &value.Model.Capabilities, &value.Model.Qualification, &value.Model.Health, &value.Model.ObservedAtUnixMillis)
|
&value.Model.ID, &value.Model.Revision, &value.Model.ProviderInstanceID, &value.Model.ProviderModelID, &value.Model.Fingerprint, &value.Model.MaxContextBytes, &value.Model.Modalities, &value.Model.Capabilities, &value.Model.Qualification, &value.Model.Health, &value.Model.ObservedAtUnixMillis, &value.Model.IntelligenceScoreMillis)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -414,7 +414,7 @@ func (r *CapabilityRepository) SaveCognitiveDiscovery(ctx context.Context, value
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances (provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis) VALUES ($1,$2,$3,$4,NULLIF($5,''),$6,$7,$8,$9) ON CONFLICT DO NOTHING`, value.Provider.ID, value.Provider.Revision, value.Provider.Kind, value.Provider.EndpointRef, value.Provider.CredentialRef, value.Provider.Enabled, value.Provider.Qualification, value.Provider.Health, value.Provider.ObservedAtUnixMillis)
|
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances (provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis,billing_mode,auth_mode,input_cost_micros,output_cost_micros,request_cost_micros) VALUES ($1,$2,$3,$4,NULLIF($5,''),$6,$7,$8,$9,$10,$11,$12,$13,$14) ON CONFLICT (provider_instance_id,revision) DO UPDATE SET health=EXCLUDED.health,observed_at_unix_millis=EXCLUDED.observed_at_unix_millis,billing_mode=EXCLUDED.billing_mode,auth_mode=EXCLUDED.auth_mode,input_cost_micros=EXCLUDED.input_cost_micros,output_cost_micros=EXCLUDED.output_cost_micros,request_cost_micros=EXCLUDED.request_cost_micros WHERE capability.cognitive_provider_instances.observed_at_unix_millis <= EXCLUDED.observed_at_unix_millis`, value.Provider.ID, value.Provider.Revision, value.Provider.Kind, value.Provider.EndpointRef, value.Provider.CredentialRef, value.Provider.Enabled, value.Provider.Qualification, value.Provider.Health, value.Provider.ObservedAtUnixMillis, value.Provider.BillingMode, value.Provider.AuthMode, value.Provider.InputCostMicros, value.Provider.OutputCostMicros, value.Provider.RequestCostMicros)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -423,7 +423,7 @@ func (r *CapabilityRepository) SaveCognitiveDiscovery(ctx context.Context, value
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for index, model := range value.Models {
|
for index, model := range value.Models {
|
||||||
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors (model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT DO NOTHING`, model.ID, model.Revision, model.ProviderInstanceID, model.ProviderModelID, model.Fingerprint, model.MaxContextBytes, model.Modalities, model.Capabilities, model.Qualification, model.Health, model.ObservedAtUnixMillis)
|
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors (model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis,intelligence_score_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT (model_descriptor_id,revision) DO UPDATE SET health=EXCLUDED.health,observed_at_unix_millis=EXCLUDED.observed_at_unix_millis,intelligence_score_millis=EXCLUDED.intelligence_score_millis WHERE capability.cognitive_model_descriptors.observed_at_unix_millis <= EXCLUDED.observed_at_unix_millis`, model.ID, model.Revision, model.ProviderInstanceID, model.ProviderModelID, model.Fingerprint, model.MaxContextBytes, model.Modalities, model.Capabilities, model.Qualification, model.Health, model.ObservedAtUnixMillis, model.IntelligenceScoreMillis)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -433,7 +433,11 @@ func (r *CapabilityRepository) SaveCognitiveDiscovery(ctx context.Context, value
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
binding := value.Bindings[index]
|
binding := value.Bindings[index]
|
||||||
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_bindings (binding_id,revision,capability_id,owner_principal_id,provider_instance_id,provider_revision,model_descriptor_id,model_revision,data_policy,qualification,activation,health,limit_policy_ref) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT DO NOTHING`, binding.ID, binding.Revision, binding.CapabilityID, binding.OwnerPrincipalID, binding.ProviderInstanceID, binding.ProviderRevision, binding.ModelDescriptorID, binding.ModelRevision, binding.DataPolicy, binding.Qualification, binding.Activation, binding.Health, binding.LimitPolicyRef)
|
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_bindings (binding_id,revision,capability_id,owner_principal_id,provider_instance_id,provider_revision,model_descriptor_id,model_revision,data_policy,qualification,activation,health,limit_policy_ref) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT (binding_id,revision) DO UPDATE SET health=EXCLUDED.health WHERE capability.cognitive_bindings.health <> EXCLUDED.health`, binding.ID, binding.Revision, binding.CapabilityID, binding.OwnerPrincipalID, binding.ProviderInstanceID, binding.ProviderRevision, binding.ModelDescriptorID, binding.ModelRevision, binding.DataPolicy, binding.Qualification, binding.Activation, binding.Health, binding.LimitPolicyRef)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_binding_revision_heads (binding_id,revision) VALUES ($1,$2) ON CONFLICT DO NOTHING`, binding.ID, binding.Revision)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -453,10 +457,10 @@ func (r *CapabilityRepository) SaveCognitiveCanaryPromotion(ctx context.Context,
|
|||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
p, m, b, e := value.Provider, value.Model, value.Binding, value.Evaluation
|
p, m, b, e := value.Provider, value.Model, value.Binding, value.Evaluation
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances (provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis) VALUES ($1,$2,$3,$4,NULLIF($5,''),$6,$7,$8,$9) ON CONFLICT DO NOTHING`, p.ID, p.Revision, p.Kind, p.EndpointRef, p.CredentialRef, p.Enabled, p.Qualification, p.Health, p.ObservedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_provider_instances (provider_instance_id,revision,provider_kind,endpoint_ref,credential_ref,enabled,qualification,health,observed_at_unix_millis,billing_mode,auth_mode,input_cost_micros,output_cost_micros,request_cost_micros) VALUES ($1,$2,$3,$4,NULLIF($5,''),$6,$7,$8,$9,$10,$11,$12,$13,$14) ON CONFLICT DO NOTHING`, p.ID, p.Revision, p.Kind, p.EndpointRef, p.CredentialRef, p.Enabled, p.Qualification, p.Health, p.ObservedAtUnixMillis, p.BillingMode, p.AuthMode, p.InputCostMicros, p.OutputCostMicros, p.RequestCostMicros); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors (model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT DO NOTHING`, m.ID, m.Revision, m.ProviderInstanceID, m.ProviderModelID, m.Fingerprint, m.MaxContextBytes, m.Modalities, m.Capabilities, m.Qualification, m.Health, m.ObservedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_model_descriptors (model_descriptor_id,revision,provider_instance_id,provider_model_id,fingerprint,max_context_bytes,modalities,capabilities,qualification,health,observed_at_unix_millis,intelligence_score_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT DO NOTHING`, m.ID, m.Revision, m.ProviderInstanceID, m.ProviderModelID, m.Fingerprint, m.MaxContextBytes, m.Modalities, m.Capabilities, m.Qualification, m.Health, m.ObservedAtUnixMillis, m.IntelligenceScoreMillis); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_bindings (binding_id,revision,capability_id,owner_principal_id,provider_instance_id,provider_revision,model_descriptor_id,model_revision,data_policy,qualification,activation,health,limit_policy_ref) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT DO NOTHING`, b.ID, b.Revision, b.CapabilityID, b.OwnerPrincipalID, b.ProviderInstanceID, b.ProviderRevision, b.ModelDescriptorID, b.ModelRevision, b.DataPolicy, b.Qualification, b.Activation, b.Health, b.LimitPolicyRef); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_bindings (binding_id,revision,capability_id,owner_principal_id,provider_instance_id,provider_revision,model_descriptor_id,model_revision,data_policy,qualification,activation,health,limit_policy_ref) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT DO NOTHING`, b.ID, b.Revision, b.CapabilityID, b.OwnerPrincipalID, b.ProviderInstanceID, b.ProviderRevision, b.ModelDescriptorID, b.ModelRevision, b.DataPolicy, b.Qualification, b.Activation, b.Health, b.LimitPolicyRef); err != nil {
|
||||||
@@ -475,6 +479,32 @@ func (r *CapabilityRepository) SaveCognitiveCanaryPromotion(ctx context.Context,
|
|||||||
return tx.Commit(ctx)
|
return tx.Commit(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *CapabilityRepository) SaveCognitiveActivationPromotion(ctx context.Context, value capability.CognitiveActivationPromotion) error {
|
||||||
|
tx, err := r.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
|
b, e := value.Binding, value.Evaluation
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_bindings (binding_id,revision,capability_id,owner_principal_id,provider_instance_id,provider_revision,model_descriptor_id,model_revision,data_policy,qualification,activation,health,limit_policy_ref) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT DO NOTHING`, b.ID, b.Revision, b.CapabilityID, b.OwnerPrincipalID, b.ProviderInstanceID, b.ProviderRevision, b.ModelDescriptorID, b.ModelRevision, b.DataPolicy, b.Qualification, b.Activation, b.Health, b.LimitPolicyRef); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO capability.cognitive_evaluated_capabilities (evaluation_id,binding_id,binding_revision,capability_id,result,quality_score_millis,critical_failure_millis,benchmark_version,artifact_id,observed_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT DO NOTHING`, e.ID, e.BindingID, e.BindingRevision, e.CapabilityID, e.Result, e.QualityScoreMillis, e.CriticalFailureMillis, e.BenchmarkVersion, e.ArtifactID, e.ObservedAtUnixMillis); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `UPDATE capability.cognitive_bindings SET activation='DEPRECATED' WHERE capability_id=$1 AND owner_principal_id=$2 AND activation='ACTIVE' AND NOT (binding_id=$3 AND revision=$4)`, b.CapabilityID, b.OwnerPrincipalID, b.ID, b.Revision); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(ctx, `UPDATE capability.cognitive_binding_revision_heads SET revision=$1,updated_at=CURRENT_TIMESTAMP WHERE binding_id=$2 AND revision=$3`, b.Revision, b.ID, value.ExpectedBindingRevision)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() != 1 {
|
||||||
|
return ErrCapabilityBindingConflict
|
||||||
|
}
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
func (r *CapabilityRepository) SavePerformanceEvidence(ctx context.Context, value capability.PerformanceEvidence) error {
|
func (r *CapabilityRepository) SavePerformanceEvidence(ctx context.Context, value capability.PerformanceEvidence) error {
|
||||||
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_performance_evidence (evidence_id,binding_id,binding_revision,model_descriptor_id,model_revision,hardware_profile,runtime,quantization,context_units,thinking_enabled,generation_tps_millis,prompt_tps_millis,ttft_micros,latency_micros,memory_bytes,reliability_millis,benchmark_version,artifact_id,observed_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) ON CONFLICT DO NOTHING`, value.ID, value.BindingID, value.BindingRevision, value.ModelDescriptorID, value.ModelRevision, value.HardwareProfile, value.Runtime, value.Quantization, value.ContextUnits, value.ThinkingEnabled, value.GenerationTPSMillis, value.PromptTPSMillis, value.TTFTMicros, value.LatencyMicros, value.MemoryBytes, value.ReliabilityMillis, value.BenchmarkVersion, value.ArtifactID, value.ObservedAtUnixMillis)
|
_, err := r.pool.Exec(ctx, `INSERT INTO capability.cognitive_performance_evidence (evidence_id,binding_id,binding_revision,model_descriptor_id,model_revision,hardware_profile,runtime,quantization,context_units,thinking_enabled,generation_tps_millis,prompt_tps_millis,ttft_micros,latency_micros,memory_bytes,reliability_millis,benchmark_version,artifact_id,observed_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) ON CONFLICT DO NOTHING`, value.ID, value.BindingID, value.BindingRevision, value.ModelDescriptorID, value.ModelRevision, value.HardwareProfile, value.Runtime, value.Quantization, value.ContextUnits, value.ThinkingEnabled, value.GenerationTPSMillis, value.PromptTPSMillis, value.TTFTMicros, value.LatencyMicros, value.MemoryBytes, value.ReliabilityMillis, value.BenchmarkVersion, value.ArtifactID, value.ObservedAtUnixMillis)
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -43,15 +43,25 @@ func (r *InteractionRepository) AppendUtterance(ctx context.Context, c interacti
|
|||||||
return tx.Commit(ctx)
|
return tx.Commit(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *InteractionRepository) SaveSemanticResult(ctx context.Context, interpretation interaction.UtteranceInterpretation, projects []interaction.ProjectReference, relations []interaction.InteractionRelation) error {
|
func (r *InteractionRepository) SaveSemanticResult(ctx context.Context, interpretation interaction.UtteranceInterpretation, candidates []interaction.SemanticCandidate, projects []interaction.ProjectReference, relations []interaction.InteractionRelation) error {
|
||||||
tx, err := r.pool.Begin(ctx)
|
tx, err := r.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer tx.Rollback(ctx)
|
defer tx.Rollback(ctx)
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO interaction.utterance_interpretations(interpretation_id,utterance_id,speech_act,confidence_millis,source,assertion_verification,requested_outcome,clarification,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, interpretation.ID, interpretation.UtteranceID, interpretation.SpeechAct, interpretation.ConfidenceMillis, interpretation.Source, interpretation.AssertionVerification, interpretation.RequestedOutcome, interpretation.Clarification, interpretation.RecordedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.utterance_interpretations(interpretation_id,utterance_id,speech_act,secondary_speech_act,confidence_millis,source,assertion_verification,requested_outcome,clarification,needs_cognition,applicability,selection_reason,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`, interpretation.ID, interpretation.UtteranceID, interpretation.SpeechAct, interpretation.SecondarySpeechAct, interpretation.ConfidenceMillis, interpretation.Source, interpretation.AssertionVerification, interpretation.RequestedOutcome, interpretation.Clarification, interpretation.NeedsCognition, interpretation.Applicability, interpretation.SelectionReason, interpretation.RecordedAtUnixMillis); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.semantic_candidates(candidate_id,utterance_id,source,selection_state,primary_speech_act,secondary_speech_act,confidence_millis,applicability,requested_outcome,clarification,needs_cognition,selection_reason,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT(candidate_id) DO UPDATE SET selection_state=EXCLUDED.selection_state,primary_speech_act=EXCLUDED.primary_speech_act,secondary_speech_act=EXCLUDED.secondary_speech_act,confidence_millis=EXCLUDED.confidence_millis,applicability=EXCLUDED.applicability,requested_outcome=EXCLUDED.requested_outcome,clarification=EXCLUDED.clarification,needs_cognition=EXCLUDED.needs_cognition,selection_reason=EXCLUDED.selection_reason,recorded_at_unix_millis=EXCLUDED.recorded_at_unix_millis`, candidate.ID, candidate.UtteranceID, candidate.Source, candidate.SelectionState, candidate.PrimarySpeechAct, candidate.SecondarySpeechAct, candidate.ConfidenceMillis, candidate.Applicability, candidate.RequestedOutcome, candidate.Clarification, candidate.NeedsCognition, candidate.SelectionReason, candidate.RecordedAtUnixMillis); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, hint := range candidate.CapabilityHints {
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.semantic_candidate_capability_hints(candidate_id,capability_kind) VALUES($1,$2) ON CONFLICT DO NOTHING`, candidate.ID, hint); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, project := range projects {
|
for _, project := range projects {
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO interaction.project_references(project_reference_id,utterance_id,project_id,project_display_name,role,provenance,confidence_millis,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, project.ID, project.UtteranceID, project.ProjectID, project.ProjectDisplayName, project.Role, project.Provenance, project.ConfidenceMillis, project.RecordedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.project_references(project_reference_id,utterance_id,project_id,project_display_name,role,provenance,confidence_millis,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, project.ID, project.UtteranceID, project.ProjectID, project.ProjectDisplayName, project.Role, project.Provenance, project.ConfidenceMillis, project.RecordedAtUnixMillis); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func (s discoveryService) handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
discovered, probe := registration.Discovery.Discover(r.Context())
|
discovered, probe := registration.Discovery.Discover(r.Context())
|
||||||
snapshot := capability.CognitiveDiscoverySnapshot{ProviderInstanceID: registration.ProviderInstanceID, ProviderKind: registration.Kind, EndpointRef: registration.EndpointRef, CredentialRef: registration.CredentialRef, Enabled: true, OwnerPrincipalID: s.owner, CapabilityID: creatorAdvisoryCapabilityID, DataPolicy: capability.DataPolicyLocalOnly, LimitPolicyRef: "creator-advisory-local-v1", Health: probe.Health, FailureClass: capability.CognitiveFailureType(probe.Failure), ObservedAtUnixMillis: s.now().UnixMilli()}
|
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 {
|
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})
|
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})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/adapters/models"
|
"git.cin.su/m/Assistant/adapters/models"
|
||||||
@@ -29,6 +30,9 @@ type providerRegistration struct {
|
|||||||
Kind capability.ProviderKind
|
Kind capability.ProviderKind
|
||||||
EndpointRef capability.EndpointBindingRef
|
EndpointRef capability.EndpointBindingRef
|
||||||
CredentialRef capability.CredentialRef
|
CredentialRef capability.CredentialRef
|
||||||
|
AuthMode capability.AuthMode
|
||||||
|
BillingMode capability.BillingMode
|
||||||
|
DataPolicy capability.DataPolicy
|
||||||
Provider advisoryProvider
|
Provider advisoryProvider
|
||||||
Discovery models.LocalProvider
|
Discovery models.LocalProvider
|
||||||
}
|
}
|
||||||
@@ -36,6 +40,8 @@ type providerRegistration struct {
|
|||||||
type cognitiveGateway struct {
|
type cognitiveGateway struct {
|
||||||
resolver bindingResolver
|
resolver bindingResolver
|
||||||
providers map[capability.ProviderKind][]providerRegistration
|
providers map[capability.ProviderKind][]providerRegistration
|
||||||
|
builtinLocal *providerRegistration
|
||||||
|
externalRecovery []providerRegistration
|
||||||
now func() time.Time
|
now func() time.Time
|
||||||
allowCanary bool
|
allowCanary bool
|
||||||
canaryMaxOutputBytes int
|
canaryMaxOutputBytes int
|
||||||
@@ -71,10 +77,10 @@ func (g cognitiveGateway) advisoryHandler(w http.ResponseWriter, r *http.Request
|
|||||||
if g.allowCanary && g.canaryMaxOutputBytes > 0 && maxOutputBytes > g.canaryMaxOutputBytes {
|
if g.allowCanary && g.canaryMaxOutputBytes > 0 && maxOutputBytes > g.canaryMaxOutputBytes {
|
||||||
maxOutputBytes = g.canaryMaxOutputBytes
|
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)}
|
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.resolver.Resolve(r.Context(), requirement)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeGatewayResponse(w, cognitive.GatewayAdvisoryResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable})
|
writeGatewayResponse(w, g.invokeBuiltinAdvisory(r.Context(), request, maxOutputBytes))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if selected.Binding.DataPolicy != capability.DataPolicyLocalOnly && !request.EgressAcknowledged {
|
if selected.Binding.DataPolicy != capability.DataPolicyLocalOnly && !request.EgressAcknowledged {
|
||||||
@@ -83,7 +89,7 @@ func (g cognitiveGateway) advisoryHandler(w http.ResponseWriter, r *http.Request
|
|||||||
}
|
}
|
||||||
provider := g.provider(selected)
|
provider := g.provider(selected)
|
||||||
if provider == nil {
|
if provider == nil {
|
||||||
writeGatewayResponse(w, cognitive.GatewayAdvisoryResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable})
|
writeGatewayResponse(w, g.invokeBuiltinAdvisory(r.Context(), request, maxOutputBytes))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
invocation := cognitive.AdvisoryRequest{Version: request.Version, RequestID: request.RequestID, ActorID: request.ActorID, PrincipalID: request.PrincipalID, ScopeID: request.ScopeID, Message: request.Message, Context: request.Context, Locale: request.Locale, MaxOutputBytes: maxOutputBytes, ProviderBindingID: selected.Binding.ID, ProviderBindingRevision: selected.Binding.Revision, ProviderInstanceID: selected.Provider.ID, ModelDescriptorID: selected.Model.ID, ProviderModelID: selected.Model.ProviderModelID}
|
invocation := cognitive.AdvisoryRequest{Version: request.Version, RequestID: request.RequestID, ActorID: request.ActorID, PrincipalID: request.PrincipalID, ScopeID: request.ScopeID, Message: request.Message, Context: request.Context, Locale: request.Locale, MaxOutputBytes: maxOutputBytes, ProviderBindingID: selected.Binding.ID, ProviderBindingRevision: selected.Binding.Revision, ProviderInstanceID: selected.Provider.ID, ModelDescriptorID: selected.Model.ID, ProviderModelID: selected.Model.ProviderModelID}
|
||||||
@@ -110,9 +116,94 @@ func (g cognitiveGateway) advisoryHandler(w http.ResponseWriter, r *http.Request
|
|||||||
response = fallbackResponse
|
response = fallbackResponse
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if response.FinishReason != cognitive.FinishCompleted && fallbackEligible(response.FinishReason) {
|
||||||
|
writeGatewayResponse(w, g.invokeBuiltinAdvisory(r.Context(), request, maxOutputBytes))
|
||||||
|
return
|
||||||
|
}
|
||||||
writeGatewayResponse(w, cognitive.GatewayAdvisoryResponse{Version: response.Version, RequestID: response.RequestID, AdvisoryText: response.AdvisoryText, ReferencedExcerptIDs: response.ReferencedExcerptIDs, FinishReason: response.FinishReason, Usage: response.Usage})
|
writeGatewayResponse(w, cognitive.GatewayAdvisoryResponse{Version: response.Version, RequestID: response.RequestID, AdvisoryText: response.AdvisoryText, ReferencedExcerptIDs: response.ReferencedExcerptIDs, FinishReason: response.FinishReason, Usage: response.Usage})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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") {
|
||||||
|
return capability.SelectionEconomy
|
||||||
|
}
|
||||||
|
if strings.Contains(lower, "быстр") || strings.Contains(lower, "срочно") || strings.Contains(lower, "статус") || strings.Contains(lower, "quick") || strings.Contains(lower, "fast") {
|
||||||
|
return capability.SelectionSpeed
|
||||||
|
}
|
||||||
|
if strings.Contains(lower, "сложн") || strings.Contains(lower, "анализ") || strings.Contains(lower, "код") || strings.Contains(lower, "план") || strings.Contains(lower, "глубок") || strings.Contains(lower, "reason") || strings.Contains(lower, "code") {
|
||||||
|
return capability.SelectionQuality
|
||||||
|
}
|
||||||
|
return capability.SelectionBalanced
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectionObjectiveForMeaning(meaning cognitive.TaskMeaning, message string) capability.SelectionObjective {
|
||||||
|
if meaning.CapabilityKind != "" || len(meaning.CapabilityHints) > 0 || meaning.SpeechAct != "" || meaning.RequestedOutcome != "" {
|
||||||
|
kinds := append([]capability.CapabilityKind{meaning.CapabilityKind}, meaning.CapabilityHints...)
|
||||||
|
for _, kind := range kinds {
|
||||||
|
switch kind {
|
||||||
|
case capability.CapabilityKindModifyCode, capability.CapabilityKindRunTests, capability.CapabilityKindVerifyFact, capability.CapabilityKindInspectProject, capability.CapabilityKindReadDatabase, capability.CapabilityKindQueryLogs:
|
||||||
|
return capability.SelectionQuality
|
||||||
|
case capability.CapabilityKindScheduleReminder:
|
||||||
|
return capability.SelectionSpeed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if meaning.RequestedOutcome != "" || meaning.SpeechAct == "REQUEST_TO_INVESTIGATE" || meaning.SpeechAct == "DIRECTIVE" {
|
||||||
|
return capability.SelectionQuality
|
||||||
|
}
|
||||||
|
if meaning.ConfidenceMillis > 0 {
|
||||||
|
return capability.SelectionBalanced
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return selectionObjectiveForMessage(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func builtinAdvisory(request cognitive.GatewayAdvisoryRequest) cognitive.GatewayAdvisoryResponse {
|
||||||
|
message := strings.ToLower(strings.TrimSpace(request.Message))
|
||||||
|
text := "Я рядом и продолжаю работу во встроенном режиме Домового. Подключённые модели сейчас недоступны; могу помочь проверить канал, сравнить доступные модели и подготовить безопасное переключение."
|
||||||
|
if strings.Contains(message, "модел") || strings.Contains(message, "канал") || strings.Contains(message, "ии") || strings.Contains(message, "ai") {
|
||||||
|
text = "Встроенный режим Домового доступен. Я могу проверить подключённые модели по назначению, качеству, скорости и стоимости, после чего предложить подходящую; ключи и пароли в разговор не нужны."
|
||||||
|
}
|
||||||
|
return cognitive.GatewayAdvisoryResponse{Version: request.Version, RequestID: request.RequestID, AdvisoryText: text, FinishReason: cognitive.FinishCompleted}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g cognitiveGateway) invokeBuiltinAdvisory(ctx context.Context, request cognitive.GatewayAdvisoryRequest, maxOutputBytes int) cognitive.GatewayAdvisoryResponse {
|
||||||
|
if g.builtinLocal != nil && g.builtinLocal.Provider != nil {
|
||||||
|
invocation := cognitive.AdvisoryRequest{Version: request.Version, RequestID: request.RequestID, ActorID: request.ActorID, PrincipalID: request.PrincipalID, ScopeID: request.ScopeID, Message: request.Message, Context: request.Context, Locale: request.Locale, MaxOutputBytes: maxOutputBytes, ProviderBindingID: "builtin-local-binding-v1", ProviderBindingRevision: 1, ProviderInstanceID: "builtin-local-lifeboat-v1", ModelDescriptorID: "builtin-local-model-v1", ProviderModelID: "domovoy-lifeboat"}
|
||||||
|
response, err := g.builtinLocal.Provider.Advise(ctx, invocation)
|
||||||
|
if err == nil && response.FinishReason == cognitive.FinishCompleted && strings.TrimSpace(response.AdvisoryText) != "" {
|
||||||
|
return cognitive.GatewayAdvisoryResponse{Version: request.Version, RequestID: request.RequestID, AdvisoryText: response.AdvisoryText, ReferencedExcerptIDs: response.ReferencedExcerptIDs, FinishReason: response.FinishReason, Usage: response.Usage}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if request.EgressAcknowledged {
|
||||||
|
if response, ok := g.recoverExternalAdvisory(ctx, request, maxOutputBytes); ok {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return builtinAdvisory(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g cognitiveGateway) recoverExternalAdvisory(ctx context.Context, request cognitive.GatewayAdvisoryRequest, maxOutputBytes int) (cognitive.GatewayAdvisoryResponse, bool) {
|
||||||
|
for _, candidate := range g.externalRecovery {
|
||||||
|
if candidate.Provider == nil || candidate.Discovery == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
probeCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||||
|
modelsFound, probe := candidate.Discovery.Discover(probeCtx)
|
||||||
|
cancel()
|
||||||
|
if probe.Health != capability.HealthAvailable || len(modelsFound) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
model := modelsFound[0]
|
||||||
|
invocation := cognitive.AdvisoryRequest{Version: request.Version, RequestID: request.RequestID, ActorID: request.ActorID, PrincipalID: request.PrincipalID, ScopeID: request.ScopeID, Message: request.Message, Context: request.Context, Locale: request.Locale, MaxOutputBytes: maxOutputBytes, ProviderBindingID: "recovery-external-binding-v1", ProviderBindingRevision: 1, ProviderInstanceID: capability.ProviderInstanceID("recovery-" + string(candidate.ProviderInstanceID)), ModelDescriptorID: capability.ModelDescriptorID("recovery-model-" + string(model.ProviderModelID)), ProviderModelID: model.ProviderModelID}
|
||||||
|
response, err := candidate.Provider.Advise(ctx, invocation)
|
||||||
|
if err == nil && response.FinishReason == cognitive.FinishCompleted && strings.TrimSpace(response.AdvisoryText) != "" {
|
||||||
|
return cognitive.GatewayAdvisoryResponse{Version: request.Version, RequestID: request.RequestID, AdvisoryText: response.AdvisoryText, ReferencedExcerptIDs: response.ReferencedExcerptIDs, FinishReason: response.FinishReason, Usage: response.Usage}, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cognitive.GatewayAdvisoryResponse{}, false
|
||||||
|
}
|
||||||
|
|
||||||
func (g cognitiveGateway) observe(ctx context.Context, selected capability.ResolvedCognitiveBinding, response cognitive.AdvisoryResponse, started time.Time) {
|
func (g cognitiveGateway) observe(ctx context.Context, selected capability.ResolvedCognitiveBinding, response cognitive.AdvisoryResponse, started time.Time) {
|
||||||
usage := response.Usage
|
usage := response.Usage
|
||||||
observationID, idErr := ids.New()
|
observationID, idErr := ids.New()
|
||||||
|
|||||||
@@ -114,7 +114,45 @@ func TestCanaryOutputLimitIsClamped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNoActiveBindingKeepsGatewayAvailableWithoutInvocation(t *testing.T) {
|
func TestSelectionObjectiveForMessage(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
message string
|
||||||
|
objective capability.SelectionObjective
|
||||||
|
}{
|
||||||
|
{"Сделай глубокий анализ кода", capability.SelectionQuality},
|
||||||
|
{"Нужен быстрый статус", capability.SelectionSpeed},
|
||||||
|
{"Выбери бесплатную модель", capability.SelectionEconomy},
|
||||||
|
{"Помоги сформулировать ответ", capability.SelectionBalanced},
|
||||||
|
}
|
||||||
|
for _, test := range cases {
|
||||||
|
if actual := selectionObjectiveForMessage(test.message); actual != test.objective {
|
||||||
|
t.Errorf("message=%q objective=%q, want %q", test.message, actual, test.objective)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectionObjectiveUsesTrustedMeaningBeforeText(t *testing.T) {
|
||||||
|
meaning := cognitive.TaskMeaning{CapabilityKind: capability.CapabilityKindModifyCode, SpeechAct: "DIRECTIVE"}
|
||||||
|
if actual := selectionObjectiveForMeaning(meaning, "сделай быстро и дёшево"); actual != capability.SelectionQuality {
|
||||||
|
t.Fatalf("objective=%q, want quality", actual)
|
||||||
|
}
|
||||||
|
if actual := selectionObjectiveForMeaning(cognitive.TaskMeaning{}, "сделай быстро"); actual != capability.SelectionSpeed {
|
||||||
|
t.Fatalf("fallback objective=%q, want speed", actual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectionObjectiveForInterpretationUsesSemanticSignals(t *testing.T) {
|
||||||
|
request := cognitive.GatewayInterpretationRequest{RequestedOutcome: "сравнить варианты", DeterministicApplicability: cognitive.InterpretationApplicable, DeterministicConfidence: 900, DeterministicSpeechAct: "QUESTION"}
|
||||||
|
if actual := selectionObjectiveForInterpretation(request); actual != capability.SelectionQuality {
|
||||||
|
t.Fatalf("objective=%q, want quality", actual)
|
||||||
|
}
|
||||||
|
request = cognitive.GatewayInterpretationRequest{DeterministicApplicability: cognitive.InterpretationApplicable, DeterministicConfidence: 900, DeterministicSpeechAct: "ASSERTION"}
|
||||||
|
if actual := selectionObjectiveForInterpretation(request); actual != capability.SelectionSpeed {
|
||||||
|
t.Fatalf("objective=%q, want speed", actual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNoActiveBindingUsesBuiltInProviderWithoutInvocation(t *testing.T) {
|
||||||
registry := ®istryStub{err: errors.New("no active binding")}
|
registry := ®istryStub{err: errors.New("no active binding")}
|
||||||
provider := &stubAdvisoryProvider{}
|
provider := &stubAdvisoryProvider{}
|
||||||
gateway := cognitiveGateway{resolver: registry, providers: map[capability.ProviderKind][]providerRegistration{"unused": {{Provider: provider}}}, now: time.Now}
|
gateway := cognitiveGateway{resolver: registry, providers: map[capability.ProviderKind][]providerRegistration{"unused": {{Provider: provider}}}, now: time.Now}
|
||||||
@@ -125,11 +163,24 @@ func TestNoActiveBindingKeepsGatewayAvailableWithoutInvocation(t *testing.T) {
|
|||||||
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if response.Code != http.StatusOK || result.FinishReason != cognitive.FinishProviderUnavailable || provider.called {
|
if response.Code != http.StatusOK || result.FinishReason != cognitive.FinishCompleted || result.AdvisoryText == "" || provider.called {
|
||||||
t.Fatalf("status=%d result=%+v provider_called=%t", response.Code, result, provider.called)
|
t.Fatalf("status=%d result=%+v provider_called=%t", response.Code, result, provider.called)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNoActiveBindingInvokesBuiltInLocalProvider(t *testing.T) {
|
||||||
|
registry := ®istryStub{err: errors.New("no active binding")}
|
||||||
|
provider := &stubAdvisoryProvider{response: cognitive.AdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: "request-1", AdvisoryText: "локальный ответ", FinishReason: cognitive.FinishCompleted}}
|
||||||
|
builtin := providerRegistration{ProviderInstanceID: "local-lifeboat", Kind: "openai-compatible-chat-v1", EndpointRef: "local-lifeboat-v1", Provider: provider}
|
||||||
|
gateway := cognitiveGateway{resolver: registry, builtinLocal: &builtin, now: time.Now}
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/v1/advisories", strings.NewReader(gatewayRequest()))
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
gateway.advisoryHandler(response, request)
|
||||||
|
if response.Code != http.StatusOK || !provider.called || !strings.Contains(response.Body.String(), "локальный ответ") {
|
||||||
|
t.Fatalf("status=%d provider_called=%t body=%s", response.Code, provider.called, response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestProviderLossBetweenRoutingAndInvocationFallsBackOnce(t *testing.T) {
|
func TestProviderLossBetweenRoutingAndInvocationFallsBackOnce(t *testing.T) {
|
||||||
primary := gatewaySelection()
|
primary := gatewaySelection()
|
||||||
primary.Binding.ID = "gpu-binding"
|
primary.Binding.ID = "gpu-binding"
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (g cognitiveGateway) interpretationHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request cognitive.GatewayInterpretationRequest
|
||||||
|
if !decodeJSON(w, r, 80<<10, &request) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Version != cognitive.CreatorAdvisoryV1 || request.RequestID == "" || request.ActorID == "" || request.PrincipalID == "" || request.ScopeID == "" || strings.TrimSpace(request.Message) == "" || request.MaxOutputBytes < 1 {
|
||||||
|
http.Error(w, "invalid interpretation request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxOutputBytes := request.MaxOutputBytes
|
||||||
|
if g.allowCanary && g.canaryMaxOutputBytes > 0 && maxOutputBytes > g.canaryMaxOutputBytes {
|
||||||
|
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: selectionObjectiveForInterpretation(request),
|
||||||
|
}
|
||||||
|
selected, err := g.resolver.Resolve(r.Context(), requirement)
|
||||||
|
if err != nil {
|
||||||
|
writeInterpretationResponse(w, g.interpretWithBuiltin(r.Context(), request, maxOutputBytes))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
provider := g.provider(selected)
|
||||||
|
if provider == nil {
|
||||||
|
writeInterpretationResponse(w, g.interpretWithBuiltin(r.Context(), request, maxOutputBytes))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
invocation := cognitive.AdvisoryRequest{
|
||||||
|
Version: request.Version,
|
||||||
|
RequestID: request.RequestID,
|
||||||
|
ActorID: request.ActorID,
|
||||||
|
PrincipalID: request.PrincipalID,
|
||||||
|
ScopeID: request.ScopeID,
|
||||||
|
Message: interpretationPrompt(request),
|
||||||
|
Locale: request.Locale,
|
||||||
|
MaxOutputBytes: maxOutputBytes,
|
||||||
|
ProviderBindingID: selected.Binding.ID,
|
||||||
|
ProviderBindingRevision: selected.Binding.Revision,
|
||||||
|
ProviderInstanceID: selected.Provider.ID,
|
||||||
|
ModelDescriptorID: selected.Model.ID,
|
||||||
|
ProviderModelID: selected.Model.ProviderModelID,
|
||||||
|
}
|
||||||
|
started := g.now()
|
||||||
|
response, invokeErr := provider.Advise(r.Context(), invocation)
|
||||||
|
if invokeErr != nil {
|
||||||
|
response = cognitive.AdvisoryResponse{Version: request.Version, RequestID: request.RequestID, ProviderBindingID: selected.Binding.ID, ProviderBindingRevision: selected.Binding.Revision, FinishReason: cognitive.FinishInvalidProviderResponse}
|
||||||
|
}
|
||||||
|
g.observe(r.Context(), selected, response, started)
|
||||||
|
if response.FinishReason != cognitive.FinishCompleted {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: response.FinishReason, Usage: response.Usage})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
candidate, ok := parseInterpretationCandidate(response.AdvisoryText)
|
||||||
|
if !ok {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishInvalidStructuredOutput, Usage: response.Usage})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, Candidate: candidate, FinishReason: cognitive.FinishCompleted, Usage: response.Usage})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g cognitiveGateway) interpretWithBuiltin(ctx context.Context, request cognitive.GatewayInterpretationRequest, maxOutputBytes int) cognitive.GatewayInterpretationResponse {
|
||||||
|
if g.builtinLocal == nil || g.builtinLocal.Provider == nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable}
|
||||||
|
}
|
||||||
|
invocation := cognitive.AdvisoryRequest{Version: request.Version, RequestID: request.RequestID, ActorID: request.ActorID, PrincipalID: request.PrincipalID, ScopeID: request.ScopeID, Message: interpretationPrompt(request), Locale: request.Locale, MaxOutputBytes: maxOutputBytes, ProviderBindingID: "builtin-local-binding-v1", ProviderBindingRevision: 1, ProviderInstanceID: "builtin-local-lifeboat-v1", ModelDescriptorID: "builtin-local-model-v1", ProviderModelID: "domovoy-lifeboat"}
|
||||||
|
response, err := g.builtinLocal.Provider.Advise(ctx, invocation)
|
||||||
|
if err != nil || response.FinishReason != cognitive.FinishCompleted {
|
||||||
|
return cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable}
|
||||||
|
}
|
||||||
|
candidate, ok := parseInterpretationCandidate(response.AdvisoryText)
|
||||||
|
if !ok {
|
||||||
|
return cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishInvalidStructuredOutput, Usage: response.Usage}
|
||||||
|
}
|
||||||
|
return cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, Candidate: candidate, FinishReason: cognitive.FinishCompleted, Usage: response.Usage}
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectionObjectiveForInterpretation(request cognitive.GatewayInterpretationRequest) capability.SelectionObjective {
|
||||||
|
if request.RequestedOutcome != "" || request.DeterministicApplicability == cognitive.InterpretationNeedsBroader || request.DeterministicApplicability == cognitive.InterpretationMixedIntent || request.DeterministicApplicability == cognitive.InterpretationLowConfidence {
|
||||||
|
return capability.SelectionQuality
|
||||||
|
}
|
||||||
|
if request.DeterministicConfidence >= 800 && request.DeterministicSpeechAct != "QUESTION" {
|
||||||
|
return capability.SelectionSpeed
|
||||||
|
}
|
||||||
|
return capability.SelectionBalanced
|
||||||
|
}
|
||||||
|
|
||||||
|
func interpretationPrompt(request cognitive.GatewayInterpretationRequest) string {
|
||||||
|
projects := "none"
|
||||||
|
if len(request.ProjectNames) > 0 {
|
||||||
|
projects = strings.Join(request.ProjectNames, ", ")
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(`Return only strict JSON with keys primary_speech_act, secondary_speech_act, confidence_millis, applicability, requested_outcome, needs_cognition, clarification, selection_reason, capability_hints.
|
||||||
|
Allowed speech acts: DIRECTIVE, ASSERTION, DECISION, PREFERENCE, QUESTION, HYPOTHESIS, CORRECTION, REQUEST_TO_INVESTIGATE, CONFIRMATION, REJECTION, CANCELLATION, CONVERSATIONAL, UNKNOWN.
|
||||||
|
Allowed applicability: APPLICABLE, LOW_CONFIDENCE, MIXED_INTENT, NEEDS_BROADER_INTERPRETATION, CLARIFICATION_REQUIRED.
|
||||||
|
Allowed clarification: NOT_REQUIRED or REQUIRED.
|
||||||
|
Capability hints may only contain known capability kinds like COGNITIVE_REASONING, MODIFY_CODE, RUN_TESTS, SEND_EMAIL, SCHEDULE_REMINDER, VERIFY_FACT, INSPECT_PROJECT, READ_DATABASE, QUERY_LOGS.
|
||||||
|
Interpret the human utterance semantically. Do not claim action execution. Do not treat punctuation alone as decisive. If uncertain, set applicability accordingly.
|
||||||
|
Message: %q
|
||||||
|
Deterministic primary: %s
|
||||||
|
Deterministic secondary: %s
|
||||||
|
Deterministic confidence: %d
|
||||||
|
Deterministic applicability: %s
|
||||||
|
Deterministic requested outcome: %q
|
||||||
|
Relevant project names: %s`, request.Message, request.DeterministicSpeechAct, request.DeterministicSecondary, request.DeterministicConfidence, request.DeterministicApplicability, request.RequestedOutcome, projects)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseInterpretationCandidate(text string) (cognitive.GatewayInterpretationCandidate, bool) {
|
||||||
|
start := strings.Index(text, "{")
|
||||||
|
end := strings.LastIndex(text, "}")
|
||||||
|
if start < 0 || end <= start {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
var candidate cognitive.GatewayInterpretationCandidate
|
||||||
|
if err := json.Unmarshal([]byte(text[start:end+1]), &candidate); err != nil {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if !validSpeechAct(candidate.PrimarySpeechAct) || candidate.ConfidenceMillis < 0 || candidate.ConfidenceMillis > 1000 {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if candidate.SecondarySpeechAct != "" && !validSpeechAct(candidate.SecondarySpeechAct) {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
switch candidate.Applicability {
|
||||||
|
case cognitive.InterpretationApplicable, cognitive.InterpretationLowConfidence, cognitive.InterpretationMixedIntent, cognitive.InterpretationNeedsBroader, cognitive.InterpretationClarificationRequired:
|
||||||
|
default:
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if candidate.Clarification != "NOT_REQUIRED" && candidate.Clarification != "REQUIRED" {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
return candidate, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSpeechAct(value string) bool {
|
||||||
|
switch value {
|
||||||
|
case "DIRECTIVE", "ASSERTION", "DECISION", "PREFERENCE", "QUESTION", "HYPOTHESIS", "CORRECTION", "REQUEST_TO_INVESTIGATE", "CONFIRMATION", "REJECTION", "CANCELLATION", "CONVERSATIONAL", "UNKNOWN":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInterpretationResponse(w http.ResponseWriter, response cognitive.GatewayInterpretationResponse) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(response)
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/adapters/models"
|
||||||
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
|
"git.cin.su/m/Assistant/contracts/identity"
|
||||||
|
"git.cin.su/m/Assistant/contracts/interaction"
|
||||||
|
"git.cin.su/m/Assistant/contracts/situation"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLiveInterpretationTrace(t *testing.T) {
|
||||||
|
if os.Getenv("ASSISTANT_LIVE_SEMANTIC_TRACE") != "1" {
|
||||||
|
t.Skip("set ASSISTANT_LIVE_SEMANTIC_TRACE=1 for live semantic/gateway/raw trace")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
rawBase := envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1")
|
||||||
|
rawModelID, err := firstRawModel(ctx, rawBase)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cpuAdapter, err := models.NewOpenAICompatibleLocalAdapter(rawBase, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
discovered, probe := cpuAdapter.Discover(ctx)
|
||||||
|
if probe.Health != capability.HealthAvailable || len(discovered) == 0 {
|
||||||
|
t.Fatalf("cpu discovery unavailable: probe=%+v models=%+v", probe, discovered)
|
||||||
|
}
|
||||||
|
selected := capability.ResolvedCognitiveBinding{
|
||||||
|
Binding: capability.CognitiveBinding{
|
||||||
|
ID: "trace-binding",
|
||||||
|
Revision: 1,
|
||||||
|
CapabilityID: "creator-advisory",
|
||||||
|
OwnerPrincipalID: "domovoy-creator-principal",
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
},
|
||||||
|
Provider: capability.ProviderInstance{
|
||||||
|
ID: "local-cpu-primary",
|
||||||
|
Revision: 1,
|
||||||
|
Kind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-cpu-primary-v1",
|
||||||
|
},
|
||||||
|
Model: capability.ModelDescriptor{
|
||||||
|
ID: capability.ModelDescriptorID("trace-model"),
|
||||||
|
Revision: 1,
|
||||||
|
ProviderModelID: discovered[0].ProviderModelID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
gateway := cognitiveGateway{
|
||||||
|
resolver: traceResolver{selected: selected},
|
||||||
|
providers: map[capability.ProviderKind][]providerRegistration{
|
||||||
|
"openai-compatible-chat-v1": {{
|
||||||
|
ProviderInstanceID: "local-cpu-primary",
|
||||||
|
Kind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-cpu-primary-v1",
|
||||||
|
Provider: cpuAdapter,
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
now: time.Now,
|
||||||
|
allowCanary: true,
|
||||||
|
}
|
||||||
|
for _, message := range []string{"ты кто", "можешь расказать об утре"} {
|
||||||
|
conversation := interaction.Conversation{ID: "trace-conversation", ActorID: "trace-actor", PrincipalID: "domovoy-creator-principal", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||||
|
utterance, _, _, err := interactiondomain.NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: message}, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
semantic, err := interactiondomain.InterpretUtterance(utterance, []situation.ProjectDescriptor{{ID: "assistant", DisplayName: "Assistant"}}, nil, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rawResponse, err := rawCompletion(ctx, rawBase, rawModelID, message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := cognitive.GatewayInterpretationRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1,
|
||||||
|
RequestID: "trace-request",
|
||||||
|
ActorID: identity.ActorID("trace-actor"),
|
||||||
|
PrincipalID: identity.PrincipalID("domovoy-creator-principal"),
|
||||||
|
ScopeID: authority.ScopeID("domovoy-global-scope"),
|
||||||
|
Message: message,
|
||||||
|
Locale: "ru",
|
||||||
|
MaxOutputBytes: 4096,
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
DeterministicSpeechAct: string(semantic.Interpretation.SpeechAct),
|
||||||
|
DeterministicSecondary: string(semantic.Interpretation.SecondarySpeechAct),
|
||||||
|
DeterministicConfidence: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
DeterministicApplicability: cognitive.InterpretationApplicability(semantic.Interpretation.Applicability),
|
||||||
|
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
|
||||||
|
}
|
||||||
|
payload, _ := json.Marshal(request)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
httpRequest := httptest.NewRequest(http.MethodPost, "/v1/interpretations", bytes.NewReader(payload))
|
||||||
|
gateway.interpretationHandler(recorder, httpRequest.WithContext(ctx))
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("message=%q gateway status=%d body=%s", message, recorder.Code, recorder.Body.String())
|
||||||
|
}
|
||||||
|
var gatewayResponse cognitive.GatewayInterpretationResponse
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &gatewayResponse); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gatewayResponse.FinishReason != cognitive.FinishCompleted {
|
||||||
|
t.Fatalf("message=%q gateway finish=%s body=%s", message, gatewayResponse.FinishReason, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if rawResponse == "" {
|
||||||
|
t.Fatalf("message=%q raw response is empty", message)
|
||||||
|
}
|
||||||
|
if message == "ты кто" {
|
||||||
|
if semantic.Interpretation.SpeechAct != interaction.SpeechActQuestion || !semantic.NeedsCognition {
|
||||||
|
t.Fatalf("semantic path still fails punctuation-free identity question: %+v", semantic.Interpretation)
|
||||||
|
}
|
||||||
|
if gatewayResponse.Candidate.PrimarySpeechAct != "QUESTION" {
|
||||||
|
t.Fatalf("gateway did not preserve question semantics: %+v", gatewayResponse.Candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("TRACE message=%q deterministic=%s/%s needs_cognition=%t raw=%q gateway_candidate=%+v", message, semantic.Interpretation.SpeechAct, semantic.Interpretation.Applicability, semantic.NeedsCognition, truncate(rawResponse, 180), gatewayResponse.Candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type traceResolver struct {
|
||||||
|
selected capability.ResolvedCognitiveBinding
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) Resolve(context.Context, capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) {
|
||||||
|
return r.selected, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) Observe(context.Context, capability.CognitiveUsageObservation) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) RegisterDiscovery(context.Context, capability.CognitiveDiscoverySnapshot) (capability.CognitiveDiscoveryRegistration, error) {
|
||||||
|
return capability.CognitiveDiscoveryRegistration{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstRawModel(ctx context.Context, base string) (string, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var payload struct {
|
||||||
|
Data []struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(&payload); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(payload.Data) == 0 || payload.Data[0].ID == "" {
|
||||||
|
return "", io.EOF
|
||||||
|
}
|
||||||
|
return payload.Data[0].ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func rawCompletion(ctx context.Context, base, model, message string) (string, error) {
|
||||||
|
payload, err := json.Marshal(map[string]any{
|
||||||
|
"model": model,
|
||||||
|
"max_tokens": 128,
|
||||||
|
"messages": []map[string]string{
|
||||||
|
{"role": "user", "content": message},
|
||||||
|
},
|
||||||
|
"stream": false,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/chat/completions", bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var result struct {
|
||||||
|
Choices []struct {
|
||||||
|
Message struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
} `json:"message"`
|
||||||
|
} `json:"choices"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&result); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(result.Choices) == 0 {
|
||||||
|
return "", io.EOF
|
||||||
|
}
|
||||||
|
return result.Choices[0].Message.Content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncate(value string, max int) string {
|
||||||
|
if len(value) <= max {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return value[:max] + "..."
|
||||||
|
}
|
||||||
@@ -40,37 +40,94 @@ func main() {
|
|||||||
}
|
}
|
||||||
providers := map[capability.ProviderKind][]providerRegistration{}
|
providers := map[capability.ProviderKind][]providerRegistration{}
|
||||||
discoveries := map[string]providerRegistration{}
|
discoveries := map[string]providerRegistration{}
|
||||||
|
var builtinLocal *providerRegistration
|
||||||
|
externalRecovery := []providerRegistration{}
|
||||||
cpuAdapter, err := models.NewOpenAICompatibleLocalAdapter(envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1"), nil)
|
cpuAdapter, err := models.NewOpenAICompatibleLocalAdapter(envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1"), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
cpu := providerRegistration{ProviderInstanceID: "local-cpu-primary", Kind: "openai-compatible-chat-v1", EndpointRef: "local-cpu-primary-v1", Provider: cpuAdapter, Discovery: cpuAdapter}
|
cpu := providerRegistration{ProviderInstanceID: "local-cpu-primary", Kind: "openai-compatible-chat-v1", EndpointRef: "local-cpu-primary-v1", AuthMode: capability.AuthNone, BillingMode: capability.BillingFree, DataPolicy: capability.DataPolicyLocalOnly, Provider: cpuAdapter, Discovery: cpuAdapter}
|
||||||
providers[cpu.Kind] = append(providers[cpu.Kind], cpu)
|
providers[cpu.Kind] = append(providers[cpu.Kind], cpu)
|
||||||
discoveries["cpu"] = cpu
|
discoveries["cpu"] = cpu
|
||||||
|
if lifeboat, enabled, lifeboatErr := newLifeboatProvider(os.Getenv("LOCAL_LIFEBOAT_PROVIDER_URL")); lifeboatErr != nil {
|
||||||
|
log.Fatal(lifeboatErr)
|
||||||
|
} else if enabled {
|
||||||
|
lifeboat.DataPolicy = capability.DataPolicyLocalOnly
|
||||||
|
providers[lifeboat.Kind] = append(providers[lifeboat.Kind], lifeboat)
|
||||||
|
discoveries["lifeboat"] = lifeboat
|
||||||
|
builtinLocal = &lifeboat
|
||||||
|
}
|
||||||
gpuAdapter, err := models.NewOllamaAdapter(envOr("LOCAL_GPU_PROVIDER_URL", "http://192.168.220.91:11434"), nil)
|
gpuAdapter, err := models.NewOllamaAdapter(envOr("LOCAL_GPU_PROVIDER_URL", "http://192.168.220.91:11434"), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
gpu := providerRegistration{ProviderInstanceID: "local-gpu-opportunistic", Kind: "ollama-v1", EndpointRef: "local-gpu-opportunistic-v1", Provider: gpuAdapter, Discovery: gpuAdapter}
|
gpu := providerRegistration{ProviderInstanceID: "local-gpu-opportunistic", Kind: "ollama-v1", EndpointRef: "local-gpu-opportunistic-v1", AuthMode: capability.AuthNone, BillingMode: capability.BillingFree, DataPolicy: capability.DataPolicyExternalMessageOnly, Provider: gpuAdapter, Discovery: gpuAdapter}
|
||||||
providers[gpu.Kind] = append(providers[gpu.Kind], gpu)
|
providers[gpu.Kind] = append(providers[gpu.Kind], gpu)
|
||||||
discoveries["gpu"] = gpu
|
discoveries["gpu"] = gpu
|
||||||
|
externalRecovery = append(externalRecovery, gpu)
|
||||||
if openAIProvider != nil {
|
if openAIProvider != nil {
|
||||||
kind := capability.ProviderKind(envOr("OPENAI_PROVIDER_KIND", "openai-responses-v1"))
|
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")), Provider: openAIProvider})
|
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, now: time.Now, allowCanary: os.Getenv("COGNITIVE_ALLOW_CANARY") == "true", canaryMaxOutputBytes: 4096}
|
gateway := cognitiveGateway{resolver: resolver, providers: providers, builtinLocal: builtinLocal, externalRecovery: externalRecovery, now: time.Now, allowCanary: os.Getenv("COGNITIVE_ALLOW_CANARY") == "true", canaryMaxOutputBytes: 4096}
|
||||||
mux.Handle("/healthz", health.Handler{Runtime: "cognitive-worker", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
mux.Handle("/healthz", health.Handler{Runtime: "cognitive-worker", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||||
mux.HandleFunc("POST /v1/proposals/deterministic", deterministicProposal)
|
mux.HandleFunc("POST /v1/proposals/deterministic", deterministicProposal)
|
||||||
mux.HandleFunc("POST /v1/advisory-policy", gateway.policyHandler)
|
mux.HandleFunc("POST /v1/advisory-policy", gateway.policyHandler)
|
||||||
mux.HandleFunc("POST /v1/advisories", gateway.advisoryHandler)
|
mux.HandleFunc("POST /v1/advisories", gateway.advisoryHandler)
|
||||||
|
mux.HandleFunc("POST /v1/interpretations", gateway.interpretationHandler)
|
||||||
discovery := discoveryService{resolver: resolver, providers: discoveries, owner: identity.PrincipalID(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), now: time.Now}
|
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.HandleFunc("POST /v1/provider-discovery/{provider}", discovery.handler)
|
||||||
|
refreshProviderDiscoveries(resolver, discovery)
|
||||||
log.Printf("cognitive-worker listening on %s", addr)
|
log.Printf("cognitive-worker listening on %s", addr)
|
||||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func refreshProviderDiscoveries(resolver bindingResolver, service discoveryService) {
|
||||||
|
for name := range service.providers {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||||
|
registration, ok := service.providers[name]
|
||||||
|
if !ok || registration.Discovery == nil {
|
||||||
|
cancel()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
discovered, probe := registration.Discovery.Discover(ctx)
|
||||||
|
cancel()
|
||||||
|
snapshot := capability.CognitiveDiscoverySnapshot{
|
||||||
|
ProviderInstanceID: registration.ProviderInstanceID,
|
||||||
|
ProviderKind: registration.Kind,
|
||||||
|
EndpointRef: registration.EndpointRef,
|
||||||
|
CredentialRef: registration.CredentialRef,
|
||||||
|
AuthMode: registration.AuthMode,
|
||||||
|
BillingMode: registration.BillingMode,
|
||||||
|
Enabled: true,
|
||||||
|
OwnerPrincipalID: service.owner,
|
||||||
|
CapabilityID: creatorAdvisoryCapabilityID,
|
||||||
|
DataPolicy: registration.DataPolicy,
|
||||||
|
LimitPolicyRef: "creator-advisory-local-v1",
|
||||||
|
Health: probe.Health,
|
||||||
|
FailureClass: capability.CognitiveFailureType(probe.Failure),
|
||||||
|
ObservedAtUnixMillis: time.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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if _, err := resolver.RegisterDiscovery(context.Background(), snapshot); err != nil {
|
||||||
|
log.Printf("startup cognitive discovery refresh failed for %s: %v", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func deterministicAdvisory(w http.ResponseWriter, r *http.Request) {
|
func deterministicAdvisory(w http.ResponseWriter, r *http.Request) {
|
||||||
request, ok := decodeAdvisoryRequest(w, r)
|
request, ok := decodeAdvisoryRequest(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -173,3 +230,22 @@ func envOr(name, fallback string) string {
|
|||||||
}
|
}
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newLifeboatProvider(rawURL string) (providerRegistration, bool, error) {
|
||||||
|
if rawURL == "" {
|
||||||
|
return providerRegistration{}, false, nil
|
||||||
|
}
|
||||||
|
adapter, err := models.NewOpenAICompatibleLocalAdapter(rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return providerRegistration{}, false, err
|
||||||
|
}
|
||||||
|
return providerRegistration{
|
||||||
|
ProviderInstanceID: "local-lifeboat",
|
||||||
|
Kind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-lifeboat-v1",
|
||||||
|
AuthMode: capability.AuthNone,
|
||||||
|
BillingMode: capability.BillingFree,
|
||||||
|
Provider: adapter,
|
||||||
|
Discovery: adapter,
|
||||||
|
}, true, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestLifeboatProviderIsOptionalAndLocalAdapterBacked(t *testing.T) {
|
||||||
|
if _, enabled, err := newLifeboatProvider(""); err != nil || enabled {
|
||||||
|
t.Fatalf("empty lifeboat URL should disable provider: enabled=%v err=%v", enabled, err)
|
||||||
|
}
|
||||||
|
provider, enabled, err := newLifeboatProvider("http://lifeboat:8080/v1")
|
||||||
|
if err != nil || !enabled {
|
||||||
|
t.Fatalf("configured lifeboat should be enabled: enabled=%v err=%v", enabled, err)
|
||||||
|
}
|
||||||
|
if provider.ProviderInstanceID != "local-lifeboat" || provider.EndpointRef != "local-lifeboat-v1" || provider.Provider == nil {
|
||||||
|
t.Fatalf("unexpected lifeboat registration: %+v", provider)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
|
"git.cin.su/m/Assistant/contracts/identity"
|
||||||
|
"git.cin.su/m/Assistant/contracts/interaction"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
"git.cin.su/m/Assistant/platform/ids"
|
||||||
|
)
|
||||||
|
|
||||||
|
type cognitiveInterpretationClient struct {
|
||||||
|
baseURL *url.URL
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCognitiveInterpretationClient(rawURL string, client *http.Client) (cognitiveInterpretationClient, error) {
|
||||||
|
base, err := url.Parse(rawURL)
|
||||||
|
if err != nil || base.Scheme == "" || base.Host == "" {
|
||||||
|
return cognitiveInterpretationClient{}, fmt.Errorf("invalid Cognitive Runtime URL")
|
||||||
|
}
|
||||||
|
if client == nil {
|
||||||
|
client = http.DefaultClient
|
||||||
|
}
|
||||||
|
return cognitiveInterpretationClient{baseURL: base, client: client}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cognitiveInterpretationClient) Interpret(ctx context.Context, request cognitive.GatewayInterpretationRequest) (cognitive.GatewayInterpretationResponse, error) {
|
||||||
|
target := *c.baseURL
|
||||||
|
target.Path = "/v1/interpretations"
|
||||||
|
payload, err := json.Marshal(request)
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
upstream, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
upstream.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := c.client.Do(upstream)
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, fmt.Errorf("cognitive interpretation status %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
var result cognitive.GatewayInterpretationResponse
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldRequestBroaderInterpretation(result interactiondomain.SemanticResult) bool {
|
||||||
|
switch result.Interpretation.Applicability {
|
||||||
|
case interaction.SemanticNeedsBroaderInterpret, interaction.SemanticLowConfidence, interaction.SemanticMixedIntent:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildGatewayInterpretationRequest(session identity.CreatorSession, utterance interaction.HumanUtterance, semantic interactiondomain.SemanticResult, projectNames []string) cognitive.GatewayInterpretationRequest {
|
||||||
|
requestID, _ := ids.New()
|
||||||
|
return cognitive.GatewayInterpretationRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1,
|
||||||
|
RequestID: cognitive.RequestID(requestID),
|
||||||
|
ActorID: session.ActorID,
|
||||||
|
PrincipalID: session.PrincipalID,
|
||||||
|
ScopeID: authority.ScopeID("domovoy-global-scope"),
|
||||||
|
Message: utterance.Content,
|
||||||
|
Locale: "ru",
|
||||||
|
MaxOutputBytes: 4096,
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
DeterministicSpeechAct: string(semantic.Interpretation.SpeechAct),
|
||||||
|
DeterministicSecondary: string(semantic.Interpretation.SecondarySpeechAct),
|
||||||
|
DeterministicConfidence: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
DeterministicApplicability: cognitive.InterpretationApplicability(semantic.Interpretation.Applicability),
|
||||||
|
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
|
||||||
|
ProjectNames: projectNames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func interactionCandidateFromGateway(utteranceID interaction.HumanUtteranceID, candidate cognitive.GatewayInterpretationCandidate, now interface{ UnixMilli() int64 }) (interaction.SemanticCandidate, error) {
|
||||||
|
id, err := ids.New()
|
||||||
|
if err != nil {
|
||||||
|
return interaction.SemanticCandidate{}, err
|
||||||
|
}
|
||||||
|
return interaction.SemanticCandidate{
|
||||||
|
ID: interaction.SemanticCandidateID(id),
|
||||||
|
UtteranceID: utteranceID,
|
||||||
|
Source: interaction.CandidateSourceCognitive,
|
||||||
|
SelectionState: interaction.CandidateSelected,
|
||||||
|
PrimarySpeechAct: interaction.SpeechAct(candidate.PrimarySpeechAct),
|
||||||
|
SecondarySpeechAct: interaction.SpeechAct(candidate.SecondarySpeechAct),
|
||||||
|
ConfidenceMillis: candidate.ConfidenceMillis,
|
||||||
|
Applicability: interaction.SemanticApplicability(candidate.Applicability),
|
||||||
|
RequestedOutcome: candidate.RequestedOutcome,
|
||||||
|
Clarification: interaction.ClarificationState(candidate.Clarification),
|
||||||
|
NeedsCognition: candidate.NeedsCognition,
|
||||||
|
SelectionReason: candidate.SelectionReason,
|
||||||
|
CapabilityHints: capabilityHintStrings(candidate.CapabilityHints),
|
||||||
|
RecordedAtUnixMillis: now.UnixMilli(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func capabilityHintStrings(values []capability.CapabilityKind) []string {
|
||||||
|
result := make([]string, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, string(value))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
+161
-19
@@ -8,6 +8,7 @@ import (
|
|||||||
"git.cin.su/m/Assistant/adapters/postgres"
|
"git.cin.su/m/Assistant/adapters/postgres"
|
||||||
"git.cin.su/m/Assistant/contracts/authority"
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
"git.cin.su/m/Assistant/contracts/continuity"
|
"git.cin.su/m/Assistant/contracts/continuity"
|
||||||
"git.cin.su/m/Assistant/contracts/epistemics"
|
"git.cin.su/m/Assistant/contracts/epistemics"
|
||||||
"git.cin.su/m/Assistant/contracts/identity"
|
"git.cin.su/m/Assistant/contracts/identity"
|
||||||
@@ -111,6 +112,10 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
cognitiveClient, err := newCognitiveInterpretationClient(envOr("COGNITIVE_RUNTIME_URL", "http://cognitive-worker:8083"), &http.Client{Timeout: 20 * time.Second})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
learning := learningRecorder{epistemics: epistemicsRepository, capability: capabilityRepository}
|
learning := learningRecorder{epistemics: epistemicsRepository, capability: capabilityRepository}
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
authenticateCreator := func(w http.ResponseWriter, r *http.Request) (identity.CreatorSession, bool) {
|
authenticateCreator := func(w http.ResponseWriter, r *http.Request) (identity.CreatorSession, bool) {
|
||||||
@@ -288,11 +293,31 @@ func main() {
|
|||||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
cognitiveAttempted := false
|
||||||
|
cognitiveAvailable := true
|
||||||
|
if shouldRequestBroaderInterpretation(semantic) {
|
||||||
|
cognitiveAttempted = true
|
||||||
|
projectNames := make([]string, 0, len(semantic.Projects))
|
||||||
|
for _, ref := range semantic.Projects {
|
||||||
|
if ref.ProjectDisplayName != "" {
|
||||||
|
projectNames = append(projectNames, ref.ProjectDisplayName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if response, interpretationErr := cognitiveClient.Interpret(r.Context(), buildGatewayInterpretationRequest(session, utterance, semantic, projectNames)); interpretationErr == nil && response.FinishReason == cognitive.FinishCompleted {
|
||||||
|
if candidate, candidateErr := interactionCandidateFromGateway(utterance.ID, response.Candidate, now); candidateErr == nil {
|
||||||
|
semantic = interactiondomain.ApplyCognitiveCandidate(semantic, utterance.Content, candidate, previousFocus)
|
||||||
|
} else {
|
||||||
|
cognitiveAvailable = false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cognitiveAvailable = false
|
||||||
|
}
|
||||||
|
}
|
||||||
if err := interactionRepository.AppendUtterance(r.Context(), conversation, utterance, intent, relations); err != nil {
|
if err := interactionRepository.AppendUtterance(r.Context(), conversation, utterance, intent, relations); err != nil {
|
||||||
http.Error(w, "save chat message", http.StatusInternalServerError)
|
http.Error(w, "save chat message", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := interactionRepository.SaveSemanticResult(r.Context(), semantic.Interpretation, semantic.Projects, semantic.Relations); err != nil {
|
if err := interactionRepository.SaveSemanticResult(r.Context(), semantic.Interpretation, semantic.Candidates, semantic.Projects, semantic.Relations); err != nil {
|
||||||
http.Error(w, "save chat semantics", http.StatusInternalServerError)
|
http.Error(w, "save chat semantics", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -349,7 +374,11 @@ func main() {
|
|||||||
ProjectProvenance: work.ProjectProvenanceRef(activeFocusProvenance),
|
ProjectProvenance: work.ProjectProvenanceRef(activeFocusProvenance),
|
||||||
Message: utterance.Content,
|
Message: utterance.Content,
|
||||||
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
||||||
|
SecondarySpeechAct: work.SpeechActRef(semantic.Interpretation.SecondarySpeechAct),
|
||||||
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
||||||
|
CapabilityHints: toCapabilityKinds(semantic.CapabilityHints),
|
||||||
|
NeedsCognition: semantic.NeedsCognition,
|
||||||
|
RequiresClarification: semantic.Interpretation.Clarification == interaction.ClarificationRequired,
|
||||||
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
||||||
}
|
}
|
||||||
helpPath := workdomain.DetermineHelpPath(planningInput)
|
helpPath := workdomain.DetermineHelpPath(planningInput)
|
||||||
@@ -365,10 +394,19 @@ func main() {
|
|||||||
}
|
}
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
|
if isCognitiveChannelQuestion(utterance.Content) {
|
||||||
|
health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal"))
|
||||||
|
planningReply = humanCognitiveChannelReply(utterance.Content, health, healthErr)
|
||||||
|
needsCognition = false
|
||||||
|
}
|
||||||
if helpPath.Reply != "" {
|
if helpPath.Reply != "" {
|
||||||
planningReply = helpPath.Reply
|
planningReply = helpPath.Reply
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
|
if planningReply == "" && needsCognition && cognitiveAttempted && !cognitiveAvailable {
|
||||||
|
planningReply = humanCognitiveDegradedReply(utterance.Content)
|
||||||
|
needsCognition = false
|
||||||
|
}
|
||||||
var capabilityStatus capability.CapabilityResolutionStatus
|
var capabilityStatus capability.CapabilityResolutionStatus
|
||||||
var capabilityKind capability.CapabilityKind
|
var capabilityKind capability.CapabilityKind
|
||||||
var capabilityGapID capability.CapabilityGapID
|
var capabilityGapID capability.CapabilityGapID
|
||||||
@@ -446,24 +484,27 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
response := interaction.ChatMessageResponse{
|
response := interaction.ChatMessageResponse{
|
||||||
ConversationID: conversation.ID,
|
ConversationID: conversation.ID,
|
||||||
UtteranceID: utterance.ID,
|
UtteranceID: utterance.ID,
|
||||||
OriginalIntentID: intent.ID,
|
OriginalIntentID: intent.ID,
|
||||||
SpeechAct: semantic.Interpretation.SpeechAct,
|
SpeechAct: semantic.Interpretation.SpeechAct,
|
||||||
InterpretationState: utterance.InterpretationState,
|
InterpretationState: utterance.InterpretationState,
|
||||||
NeedsCognition: needsCognition,
|
NeedsCognition: needsCognition,
|
||||||
FallbackText: semantic.Reply,
|
FallbackText: semantic.Reply,
|
||||||
ActiveProjectName: activeFocusName,
|
ActiveProjectName: activeFocusName,
|
||||||
ProjectProvenance: activeFocusProvenance,
|
ProjectProvenance: activeFocusProvenance,
|
||||||
Clarification: semantic.Interpretation.Clarification,
|
Clarification: semantic.Interpretation.Clarification,
|
||||||
WorkPlanned: workPlanned,
|
WorkPlanned: workPlanned,
|
||||||
PlanningReply: planningReply,
|
PlanningReply: planningReply,
|
||||||
CapabilityStatus: capabilityStatus,
|
CapabilityStatus: capabilityStatus,
|
||||||
CapabilityKind: capabilityKind,
|
CapabilityKind: capabilityKind,
|
||||||
CapabilityGapID: capabilityGapID,
|
CapabilityHints: toCapabilityKinds(semantic.CapabilityHints),
|
||||||
DelegationID: string(delegationID),
|
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
|
||||||
DelegationState: string(delegationState),
|
InterpretationConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
|
||||||
Reminder: reminder,
|
CapabilityGapID: capabilityGapID,
|
||||||
|
DelegationID: string(delegationID),
|
||||||
|
DelegationState: string(delegationState),
|
||||||
|
Reminder: reminder,
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
@@ -789,6 +830,7 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := capabilityRepository.SaveCognitiveDiscovery(r.Context(), registration); err != nil {
|
if err := capabilityRepository.SaveCognitiveDiscovery(r.Context(), registration); err != nil {
|
||||||
|
log.Printf("cognitive discovery persistence failed: %v", err)
|
||||||
http.Error(w, "save cognitive discovery", http.StatusInternalServerError)
|
http.Error(w, "save cognitive discovery", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -849,6 +891,45 @@ func main() {
|
|||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
_ = json.NewEncoder(w).Encode(promotion)
|
_ = json.NewEncoder(w).Encode(promotion)
|
||||||
})
|
})
|
||||||
|
mux.HandleFunc("POST /v1/creator/cognitive-activate", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
session, ok := authenticateCreator(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request capability.CognitiveActivationPromotionRequest
|
||||||
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 16<<10))
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(&request); err != nil {
|
||||||
|
http.Error(w, "invalid cognitive activation", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
request.RequestedByPrincipalID = session.PrincipalID
|
||||||
|
request.CapabilityID = "creator-advisory"
|
||||||
|
candidates, err := capabilityRepository.LoadCognitiveCandidates(r.Context(), request.CapabilityID, session.PrincipalID)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "cognitive registry unavailable", http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var current capability.ResolvedCognitiveBinding
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if candidate.Binding.ID == request.BindingID && candidate.Binding.Revision == request.ExpectedBindingRevision {
|
||||||
|
current = candidate
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
promotion, err := capabilitydomain.BuildActivationPromotion(request, current)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "cognitive activation precondition failed", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = capabilityRepository.SaveCognitiveActivationPromotion(r.Context(), promotion); err != nil {
|
||||||
|
http.Error(w, "cognitive activation conflict", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(promotion)
|
||||||
|
})
|
||||||
mux.HandleFunc("POST /v1/cognitive-registry/performance-evidence", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("POST /v1/cognitive-registry/performance-evidence", func(w http.ResponseWriter, r *http.Request) {
|
||||||
var value capability.PerformanceEvidence
|
var value capability.PerformanceEvidence
|
||||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
|
||||||
@@ -1072,6 +1153,55 @@ func isCapabilityQuestion(message string) bool {
|
|||||||
return strings.Contains(lower, "что ты умеешь") || strings.Contains(lower, "что умеешь") || strings.Contains(lower, "какие возможности")
|
return strings.Contains(lower, "что ты умеешь") || strings.Contains(lower, "что умеешь") || strings.Contains(lower, "какие возможности")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isCognitiveChannelQuestion(message string) bool {
|
||||||
|
lower := strings.ToLower(message)
|
||||||
|
markers := []string{"локальн", "модель", "когнитивн", "канал мышления", "проверь канал", "настройк"}
|
||||||
|
for _, marker := range markers {
|
||||||
|
if strings.Contains(lower, marker) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func humanCognitiveChannelReply(message string, health capability.Health, healthErr error) string {
|
||||||
|
changeRequested := strings.Contains(strings.ToLower(message), "переключ") || strings.Contains(strings.ToLower(message), "настрой") || strings.Contains(strings.ToLower(message), "измени") || strings.Contains(strings.ToLower(message), "замени")
|
||||||
|
if healthErr != nil {
|
||||||
|
if changeRequested {
|
||||||
|
return "Я не вижу подтверждённого состояния локального канала. Домовой всё равно рядом: опишите, что изменилось, и я помогу подготовить аварийную настройку."
|
||||||
|
}
|
||||||
|
return "Я не вижу подтверждённого состояния локального канала, но Домовой работает. Можно продолжать разговор и проверить канал ещё раз."
|
||||||
|
}
|
||||||
|
var observation string
|
||||||
|
switch health.State {
|
||||||
|
case capability.HealthAvailable:
|
||||||
|
observation = "Основной локальный канал сейчас доступен."
|
||||||
|
case capability.HealthDegraded:
|
||||||
|
observation = "Основной локальный канал сейчас работает с ограничениями."
|
||||||
|
case capability.HealthUnavailable:
|
||||||
|
observation = "Основной локальный канал сейчас недоступен."
|
||||||
|
default:
|
||||||
|
observation = "Состояние основного локального канала пока не подтверждено."
|
||||||
|
}
|
||||||
|
if changeRequested {
|
||||||
|
if health.State == capability.HealthUnavailable {
|
||||||
|
return observation + " Но Домовой жив. Опишите новую локальную модель или канал — я помогу настроить аварийный режим и перед применением покажу итоговую конфигурацию."
|
||||||
|
}
|
||||||
|
return observation + " Я не меняю модель прямо из разговора: в обычном режиме изменение выполняется в консоли с подтверждением. После изменения я увижу новую проверку канала автоматически."
|
||||||
|
}
|
||||||
|
if health.State == capability.HealthUnavailable {
|
||||||
|
return observation + " Но Домовой не остановился: продолжаю принимать сообщения и помогу восстановить локальный канал."
|
||||||
|
}
|
||||||
|
return observation + " Это наблюдение о готовности capability, а не прямой доступ к модели."
|
||||||
|
}
|
||||||
|
|
||||||
|
func humanCognitiveDegradedReply(message string) string {
|
||||||
|
if strings.TrimSpace(message) == "" {
|
||||||
|
return "Основной канал мышления сейчас недоступен. Я рядом и продолжаю работать в локальном аварийном режиме."
|
||||||
|
}
|
||||||
|
return "Основной канал мышления сейчас недоступен. Домовой жив: сообщение принято, а я могу помочь разобраться с локальным каналом и настройкой восстановления."
|
||||||
|
}
|
||||||
|
|
||||||
func humanCapabilityList(kinds []capability.CapabilityKind) string {
|
func humanCapabilityList(kinds []capability.CapabilityKind) string {
|
||||||
labels := make([]string, 0, len(kinds))
|
labels := make([]string, 0, len(kinds))
|
||||||
for _, kind := range kinds {
|
for _, kind := range kinds {
|
||||||
@@ -1087,6 +1217,18 @@ func humanCapabilityList(kinds []capability.CapabilityKind) string {
|
|||||||
return strings.Join(labels, ", ")
|
return strings.Join(labels, ", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func toCapabilityKinds(values []string) []capability.CapabilityKind {
|
||||||
|
result := make([]capability.CapabilityKind, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
kind := capability.CapabilityKind(strings.TrimSpace(value))
|
||||||
|
if kind == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, kind)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func delegationAttentionRef(id work.DelegationID) string {
|
func delegationAttentionRef(id work.DelegationID) string {
|
||||||
return "work:delegation:" + string(id)
|
return "work:delegation:" + string(id)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBearerTokenRequiresBearerScheme(t *testing.T) {
|
func TestBearerTokenRequiresBearerScheme(t *testing.T) {
|
||||||
@@ -23,6 +25,30 @@ func TestBearerTokenRequiresBearerScheme(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
|
||||||
|
if !isCognitiveChannelQuestion("Проверь локальную модель") {
|
||||||
|
t.Fatal("expected local model question to be recognized")
|
||||||
|
}
|
||||||
|
reply := humanCognitiveChannelReply("Проверь локальную модель", capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil)
|
||||||
|
if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") {
|
||||||
|
t.Fatalf("unexpected safe reply: %q", reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCognitiveConfigurationRequestDoesNotPretendToMutate(t *testing.T) {
|
||||||
|
reply := humanCognitiveChannelReply("Переключи локальную модель", capability.Health{State: capability.HealthUnavailable}, nil)
|
||||||
|
if !strings.Contains(reply, "Домовой жив") || !strings.Contains(reply, "аварийн") {
|
||||||
|
t.Fatalf("unexpected configuration reply: %q", reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCognitiveDegradedReplyKeepsDomovoyAlive(t *testing.T) {
|
||||||
|
reply := humanCognitiveDegradedReply("Помоги настроить локальную модель")
|
||||||
|
if !strings.Contains(reply, "Домовой жив") || !strings.Contains(reply, "принято") {
|
||||||
|
t.Fatalf("unexpected degraded reply: %q", reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCreatorSessionHandlerAcceptsConfiguredCredentials(t *testing.T) {
|
func TestCreatorSessionHandlerAcceptsConfiguredCredentials(t *testing.T) {
|
||||||
handler := creatorSessionHandler("recovery", "m", "password", []byte("01234567890123456789012345678901"), func() time.Time { return time.Unix(1000, 0) })
|
handler := creatorSessionHandler("recovery", "m", "password", []byte("01234567890123456789012345678901"), func() time.Time { return time.Unix(1000, 0) })
|
||||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/sessions", strings.NewReader(`{"username":"m","password":"password"}`))
|
request := httptest.NewRequest(http.MethodPost, "/v1/creator/sessions", strings.NewReader(`{"username":"m","password":"password"}`))
|
||||||
|
|||||||
@@ -25,6 +25,11 @@ func TestChatPageServedWithoutInternalIDs(t *testing.T) {
|
|||||||
t.Fatalf("expected /chat status 200, got %d", recorder.Code)
|
t.Fatalf("expected /chat status 200, got %d", recorder.Code)
|
||||||
}
|
}
|
||||||
body := recorder.Body.String()
|
body := recorder.Body.String()
|
||||||
|
for _, required := range []string{"cognitive-status", "aria-live=\"polite\"", "cognitive-console-link", "href=\"/admin\"", "Проверь канал", "Изменить настройку", "ai-data-error", "Не вставляйте пароли", "build-meta", "версия ", "обновлено ", "datetime=\""} {
|
||||||
|
if !strings.Contains(body, required) {
|
||||||
|
t.Fatalf("/chat is missing human status marker %q", required)
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, forbidden := range []string{"provider_id", "model_id", "binding_id", "workspace-id", "session-id"} {
|
for _, forbidden := range []string{"provider_id", "model_id", "binding_id", "workspace-id", "session-id"} {
|
||||||
if strings.Contains(body, forbidden) {
|
if strings.Contains(body, forbidden) {
|
||||||
t.Fatalf("/chat leaks internal field %q", forbidden)
|
t.Fatalf("/chat leaks internal field %q", forbidden)
|
||||||
@@ -32,6 +37,29 @@ func TestChatPageServedWithoutInternalIDs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPublicSurfacesSeparateChatAndConsole(t *testing.T) {
|
||||||
|
handler, err := newHandler("http://core", "http://continuity", "http://commit", http.DefaultClient, "http://cognitive")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
path string
|
||||||
|
must string
|
||||||
|
mustNot string
|
||||||
|
}{
|
||||||
|
{path: "/", must: "Напишите Домовому обычное сообщение", mustNot: "context-preset"},
|
||||||
|
{path: "/admin", must: "Чат с Домовым", mustNot: "Напишите Домовому обычное сообщение"},
|
||||||
|
{path: "/chat", must: "Напишите Домовому обычное сообщение", mustNot: "context-preset"},
|
||||||
|
} {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||||
|
body := recorder.Body.String()
|
||||||
|
if recorder.Code != http.StatusOK || !strings.Contains(body, test.must) || strings.Contains(body, test.mustNot) {
|
||||||
|
t.Fatalf("%s response=%d contains expected=%t forbidden=%t", test.path, recorder.Code, strings.Contains(body, test.must), strings.Contains(body, test.mustNot))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChatMessageUsesCoreAndLocalOnlyCognitiveGateway(t *testing.T) {
|
func TestChatMessageUsesCoreAndLocalOnlyCognitiveGateway(t *testing.T) {
|
||||||
var cognitiveRequest cognitive.GatewayAdvisoryRequest
|
var cognitiveRequest cognitive.GatewayAdvisoryRequest
|
||||||
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
+78
-31
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"embed"
|
"embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -8,7 +9,9 @@ import (
|
|||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
@@ -36,6 +39,12 @@ type gateway struct {
|
|||||||
cognitive *url.URL
|
cognitive *url.URL
|
||||||
client *http.Client
|
client *http.Client
|
||||||
static http.Handler
|
static http.Handler
|
||||||
|
build buildMetadata
|
||||||
|
}
|
||||||
|
|
||||||
|
type buildMetadata struct {
|
||||||
|
revision string
|
||||||
|
updated time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type routeTarget uint8
|
type routeTarget uint8
|
||||||
@@ -74,7 +83,20 @@ func newHandler(coreURL, continuityURL, commitURL string, client *http.Client, c
|
|||||||
if client == nil {
|
if client == nil {
|
||||||
client = http.DefaultClient
|
client = http.DefaultClient
|
||||||
}
|
}
|
||||||
return securityHeaders(&gateway{core: core, continuity: continuity, commit: commit, cognitive: cognitiveRuntime, client: client, static: http.FileServer(http.FS(assets))}), nil
|
updated := time.Now().UTC()
|
||||||
|
if raw := strings.TrimSpace(os.Getenv("ASSISTANT_BUILD_TIME")); raw != "" {
|
||||||
|
if parsed, parseErr := time.Parse(time.RFC3339, raw); parseErr == nil {
|
||||||
|
updated = parsed.UTC()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
revision := strings.TrimSpace(os.Getenv("ASSISTANT_BUILD_REVISION"))
|
||||||
|
if revision == "" {
|
||||||
|
revision = "development"
|
||||||
|
}
|
||||||
|
if len(revision) > 12 {
|
||||||
|
revision = revision[:12]
|
||||||
|
}
|
||||||
|
return securityHeaders(&gateway{core: core, continuity: continuity, commit: commit, cognitive: cognitiveRuntime, client: client, static: http.FileServer(http.FS(assets)), build: buildMetadata{revision: revision, updated: updated}}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRuntimeURL(rawURL, name string) (*url.URL, error) {
|
func parseRuntimeURL(rawURL, name string) (*url.URL, error) {
|
||||||
@@ -112,7 +134,12 @@ func (g *gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if r.URL.Path == "/" {
|
if r.URL.Path == "/" {
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
g.serveEmbeddedHTML(w, "chat.html")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/admin" {
|
||||||
|
g.serveEmbeddedHTML(w, "index.html")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
if r.URL.Path == "/chat" {
|
if r.URL.Path == "/chat" {
|
||||||
r = r.Clone(r.Context())
|
r = r.Clone(r.Context())
|
||||||
@@ -122,6 +149,20 @@ func (g *gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
g.static.ServeHTTP(w, r)
|
g.static.ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (g *gateway) serveEmbeddedHTML(w http.ResponseWriter, name string) {
|
||||||
|
body, err := staticFiles.ReadFile("static/" + name)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "page unavailable", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
body = bytes.ReplaceAll(body, []byte("__ASSISTANT_BUILD_REVISION__"), []byte(g.build.revision))
|
||||||
|
body = bytes.ReplaceAll(body, []byte("__ASSISTANT_BUILD_TIME__"), []byte(g.build.updated.Format("02.01.2006 15:04 UTC")))
|
||||||
|
body = bytes.ReplaceAll(body, []byte("__ASSISTANT_BUILD_DATETIME__"), []byte(g.build.updated.Format(time.RFC3339)))
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
type browserAdvisoryRequest struct {
|
type browserAdvisoryRequest struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
SessionID string `json:"session_id"`
|
SessionID string `json:"session_id"`
|
||||||
@@ -143,20 +184,23 @@ type browserChatRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type browserChatResponse struct {
|
type browserChatResponse struct {
|
||||||
ConversationID string `json:"conversation_id"`
|
ConversationID string `json:"conversation_id"`
|
||||||
UtteranceID string `json:"utterance_id"`
|
UtteranceID string `json:"utterance_id"`
|
||||||
SpeechAct string `json:"speech_act"`
|
SpeechAct string `json:"speech_act"`
|
||||||
ReplyText string `json:"reply_text"`
|
ReplyText string `json:"reply_text"`
|
||||||
Cognition string `json:"cognition"`
|
Cognition string `json:"cognition"`
|
||||||
ActiveFocus string `json:"active_focus"`
|
ActiveFocus string `json:"active_focus"`
|
||||||
ProjectProvenance string `json:"project_provenance"`
|
ProjectProvenance string `json:"project_provenance"`
|
||||||
Clarification string `json:"clarification"`
|
Clarification string `json:"clarification"`
|
||||||
WorkPlanned bool `json:"work_planned"`
|
WorkPlanned bool `json:"work_planned"`
|
||||||
CapabilityStatus string `json:"capability_status"`
|
CapabilityStatus string `json:"capability_status"`
|
||||||
CapabilityKind string `json:"capability_kind"`
|
CapabilityKind string `json:"capability_kind"`
|
||||||
DelegationID string `json:"delegation_id"`
|
CapabilityHints []capability.CapabilityKind `json:"capability_hints,omitempty"`
|
||||||
DelegationState string `json:"delegation_state"`
|
RequestedOutcome string `json:"requested_outcome,omitempty"`
|
||||||
ReminderScheduled bool `json:"reminder_scheduled"`
|
InterpretationConfidenceMillis int64 `json:"interpretation_confidence_millis,omitempty"`
|
||||||
|
DelegationID string `json:"delegation_id"`
|
||||||
|
DelegationState string `json:"delegation_state"`
|
||||||
|
ReminderScheduled bool `json:"reminder_scheduled"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *gateway) handleAdvisoryPolicy(w http.ResponseWriter, r *http.Request) {
|
func (g *gateway) handleAdvisoryPolicy(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -339,7 +383,7 @@ func (g *gateway) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
cognition = "unavailable"
|
cognition = "unavailable"
|
||||||
requestID, idErr := ids.New()
|
requestID, idErr := ids.New()
|
||||||
if idErr == nil {
|
if idErr == nil {
|
||||||
trusted := cognitive.GatewayAdvisoryRequest{Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID), ActorID: session.ActorID, PrincipalID: session.PrincipalID, ScopeID: "domovoy-global-scope", Message: browserRequest.Message, Context: []cognitive.ContextExcerpt{}, Locale: "ru-RU", MaxOutputBytes: 4096, DataPolicy: capability.DataPolicyLocalOnly, EgressAcknowledged: false}
|
trusted := cognitive.GatewayAdvisoryRequest{Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID), ActorID: session.ActorID, PrincipalID: session.PrincipalID, ScopeID: "domovoy-global-scope", Message: browserRequest.Message, Context: []cognitive.ContextExcerpt{}, Locale: "ru-RU", MaxOutputBytes: 4096, DataPolicy: capability.DataPolicyLocalOnly, EgressAcknowledged: false, Meaning: cognitive.TaskMeaning{SpeechAct: string(saved.SpeechAct), CapabilityKind: saved.CapabilityKind, CapabilityHints: saved.CapabilityHints, RequestedOutcome: saved.RequestedOutcome, ConfidenceMillis: saved.InterpretationConfidenceMillis}}
|
||||||
payload, err = json.Marshal(trusted)
|
payload, err = json.Marshal(trusted)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
var advisory cognitive.GatewayAdvisoryResponse
|
var advisory cognitive.GatewayAdvisoryResponse
|
||||||
@@ -356,20 +400,23 @@ func (g *gateway) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
_ = json.NewEncoder(w).Encode(browserChatResponse{
|
_ = json.NewEncoder(w).Encode(browserChatResponse{
|
||||||
ConversationID: string(saved.ConversationID),
|
ConversationID: string(saved.ConversationID),
|
||||||
UtteranceID: string(saved.UtteranceID),
|
UtteranceID: string(saved.UtteranceID),
|
||||||
SpeechAct: string(saved.SpeechAct),
|
SpeechAct: string(saved.SpeechAct),
|
||||||
ReplyText: reply,
|
ReplyText: reply,
|
||||||
Cognition: cognition,
|
Cognition: cognition,
|
||||||
ActiveFocus: saved.ActiveProjectName,
|
ActiveFocus: saved.ActiveProjectName,
|
||||||
ProjectProvenance: string(saved.ProjectProvenance),
|
ProjectProvenance: string(saved.ProjectProvenance),
|
||||||
Clarification: string(saved.Clarification),
|
Clarification: string(saved.Clarification),
|
||||||
WorkPlanned: saved.WorkPlanned,
|
WorkPlanned: saved.WorkPlanned,
|
||||||
CapabilityStatus: string(saved.CapabilityStatus),
|
CapabilityStatus: string(saved.CapabilityStatus),
|
||||||
CapabilityKind: string(saved.CapabilityKind),
|
CapabilityKind: string(saved.CapabilityKind),
|
||||||
DelegationID: saved.DelegationID,
|
CapabilityHints: saved.CapabilityHints,
|
||||||
DelegationState: saved.DelegationState,
|
RequestedOutcome: saved.RequestedOutcome,
|
||||||
ReminderScheduled: saved.Reminder != nil,
|
InterpretationConfidenceMillis: saved.InterpretationConfidenceMillis,
|
||||||
|
DelegationID: saved.DelegationID,
|
||||||
|
DelegationState: saved.DelegationState,
|
||||||
|
ReminderScheduled: saved.Reminder != nil,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -229,10 +229,21 @@ func TestConsoleAndSecurityHeaders(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
request := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
||||||
response := httptest.NewRecorder()
|
response := httptest.NewRecorder()
|
||||||
handler.ServeHTTP(response, request)
|
handler.ServeHTTP(response, request)
|
||||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "Домовой") ||
|
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "Домовой") ||
|
||||||
|
!strings.Contains(response.Body.String(), "context-preset") ||
|
||||||
|
!strings.Contains(response.Body.String(), "context-state") ||
|
||||||
|
!strings.Contains(response.Body.String(), "copy-context") ||
|
||||||
|
!strings.Contains(response.Body.String(), "К содержимому") ||
|
||||||
|
!strings.Contains(response.Body.String(), "aria-current=\"location\"") ||
|
||||||
|
!strings.Contains(response.Body.String(), "section-nav-link") ||
|
||||||
|
!strings.Contains(response.Body.String(), "data-page=\"overview\"") ||
|
||||||
|
!strings.Contains(response.Body.String(), "data-page=\"diagnostics\"") ||
|
||||||
|
!strings.Contains(response.Body.String(), "data-page=\"operations\"") ||
|
||||||
|
!strings.Contains(response.Body.String(), "data-page=\"learning\"") ||
|
||||||
|
!strings.Contains(response.Body.String(), "data-page=\"settings\"") ||
|
||||||
!strings.Contains(response.Body.String(), "satisfaction-dialog") || !strings.Contains(response.Body.String(), "Подтверждаю переход") ||
|
!strings.Contains(response.Body.String(), "satisfaction-dialog") || !strings.Contains(response.Body.String(), "Подтверждаю переход") ||
|
||||||
!strings.Contains(response.Body.String(), "action-history") || !strings.Contains(response.Body.String(), "Журнал действий") ||
|
!strings.Contains(response.Body.String(), "action-history") || !strings.Contains(response.Body.String(), "Журнал действий") ||
|
||||||
!strings.Contains(response.Body.String(), "advisory-form") || !strings.Contains(response.Body.String(), "Спросить Домового") ||
|
!strings.Contains(response.Body.String(), "advisory-form") || !strings.Contains(response.Body.String(), "Спросить Домового") ||
|
||||||
|
|||||||
@@ -29,26 +29,60 @@ textarea { resize: vertical; min-height: 84px; max-height: 240px; padding: 14px;
|
|||||||
.login-form button, .composer button { border: 0; color: #11150f; background: var(--signal); font-weight: 700; }
|
.login-form button, .composer button { border: 0; color: #11150f; background: var(--signal); font-weight: 700; }
|
||||||
.login-form button { width: 100%; height: 50px; margin-top: 18px; }
|
.login-form button { width: 100%; height: 50px; margin-top: 18px; }
|
||||||
#login-error { min-height: 20px; color: var(--bad); font-size: 13px; }
|
#login-error { min-height: 20px; color: var(--bad); font-size: 13px; }
|
||||||
.chat-view { min-height: 100vh; display: grid; grid-template-rows: 64px minmax(0, 1fr); }
|
.chat-view { height: 100vh; min-height: 0; display: grid; grid-template-rows: 64px minmax(0, 1fr); overflow: hidden; }
|
||||||
.chat-header { display: flex; align-items: center; gap: 18px; padding: 0 22px; border-bottom: 1px solid var(--line); background: rgba(16, 23, 20, .96); }
|
.chat-header { min-width: 0; display: flex; align-items: center; gap: 14px; padding: 0 22px; border-bottom: 1px solid var(--line); background: rgba(16, 23, 20, .98); }
|
||||||
.chat-header a { color: var(--ink); text-decoration: none; font: 400 24px/1 var(--serif); }
|
.chat-header a { color: var(--ink); text-decoration: none; font: 400 24px/1 var(--serif); }
|
||||||
.chat-header span { color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .1em; text-transform: uppercase; }
|
#active-focus { color: var(--good); }
|
||||||
#active-focus { margin-left: auto; color: var(--good); }
|
.cognitive-status { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
|
||||||
|
.chat-header .cognitive-status { width: auto; height: auto; padding: 0; border: 0; background: transparent; color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .1em; text-transform: uppercase; }
|
||||||
|
.chat-header .cognitive-status { max-width: min(30vw, 320px); margin-left: auto; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.cognitive-status::before { content: ""; width: 7px; height: 7px; flex: 0 0 7px; border-radius: 50%; background: var(--signal); }
|
||||||
|
.cognitive-status[data-state="available"] { color: var(--good); }
|
||||||
|
.cognitive-status[data-state="available"]::before { background: var(--good); }
|
||||||
|
.cognitive-status[data-state="unavailable"] { color: var(--bad); }
|
||||||
|
.cognitive-status[data-state="unavailable"]::before { background: var(--bad); }
|
||||||
|
.cognitive-console-link { color: var(--signal); font: 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; white-space: nowrap; }
|
||||||
|
.build-meta { display: grid; gap: 3px; flex: 0 0 auto; color: var(--muted); font: 9px/1 var(--mono); letter-spacing: .08em; text-align: right; text-transform: uppercase; white-space: nowrap; }
|
||||||
|
.build-meta time { color: #68776d; font-size: 8px; }
|
||||||
.chat-header button { width: 38px; height: 38px; border: 1px solid var(--line); background: transparent; }
|
.chat-header button { width: 38px; height: 38px; border: 1px solid var(--line); background: transparent; }
|
||||||
.human-nav { display: flex; align-items: center; gap: 8px; }
|
.human-nav { display: grid; gap: 8px; }
|
||||||
.nav-tab, .operator-link { height: 34px; padding: 0 12px; display: inline-flex; align-items: center; border: 1px solid var(--line); color: var(--muted); background: #0b110e; text-decoration: none; font: 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; }
|
.nav-tab, .operator-link { height: 34px; padding: 0 12px; display: inline-flex; align-items: center; border: 1px solid var(--line); color: var(--muted); background: #0b110e; text-decoration: none; font: 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; }
|
||||||
|
.chat-left .nav-tab { height: auto; min-height: 58px; padding: 10px 12px; display: grid; grid-template-columns: 28px 1fr; gap: 2px 8px; align-items: center; text-align: left; }
|
||||||
|
.chat-left .nav-tab b { grid-row: span 2; color: var(--signal); font: 11px/1 var(--mono); }
|
||||||
|
.chat-left .nav-tab span { color: var(--ink); font: 600 13px/1 var(--sans); text-transform: none; letter-spacing: 0; }
|
||||||
|
.chat-left .nav-tab small { color: var(--muted); font: 10px/1 var(--mono); text-transform: none; letter-spacing: 0; }
|
||||||
.nav-tab.active { color: #11150f; border-color: var(--signal); background: var(--signal); }
|
.nav-tab.active { color: #11150f; border-color: var(--signal); background: var(--signal); }
|
||||||
.operator-link { color: var(--good); }
|
.operator-link { color: var(--good); }
|
||||||
.surface-panel { min-height: 0; position: relative; }
|
.chat-header > .operator-link { flex: 0 0 auto; }
|
||||||
.active-panel { display: grid; min-height: 0; }
|
.chat-layout { min-height: 0; height: 100%; display: grid; grid-template-columns: minmax(220px, 280px) minmax(0, 1fr) minmax(250px, 320px); }
|
||||||
.messages { width: min(100%, 920px); margin: 0 auto; padding: 28px 18px 120px; display: flex; flex-direction: column; gap: 14px; overflow: auto; }
|
.chat-side { min-width: 0; min-height: 0; padding: 28px 20px; overflow-y: auto; background: #0e1512; }
|
||||||
|
.chat-left { border-right: 1px solid var(--line); }
|
||||||
|
.chat-right { border-left: 1px solid var(--line); }
|
||||||
|
.side-intro h1, .side-intro h2 { margin: 12px 0; font: 400 clamp(28px, 2.5vw, 40px)/.95 var(--serif); letter-spacing: -.03em; }
|
||||||
|
.side-intro p:not(.side-index) { color: var(--muted); line-height: 1.5; }
|
||||||
|
.side-index, .side-focus span, .side-note span, .ai-info-card span { color: var(--signal); font: 10px/1 var(--mono); letter-spacing: .12em; text-transform: uppercase; }
|
||||||
|
.side-focus, .side-note, .ai-info-card { margin-top: 28px; padding: 14px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
|
||||||
|
.side-focus strong, .side-note strong, .ai-info-card strong { display: block; margin-top: 9px; color: var(--ink); font: 600 14px/1.3 var(--sans); }
|
||||||
|
.side-note small, .ai-info-card p, .ai-data-form small { display: block; margin-top: 9px; color: var(--muted); line-height: 1.45; }
|
||||||
|
.chat-main { min-width: 0; min-height: 0; overflow: hidden; display: grid; }
|
||||||
|
.surface-panel { min-height: 0; position: relative; overflow-y: auto; }
|
||||||
|
.active-panel { display: grid; grid-template-rows: minmax(0, 1fr) auto auto; min-height: 0; }
|
||||||
|
.messages { width: min(100%, 920px); min-height: 0; margin: 0 auto; padding: 28px 18px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
|
||||||
.message { max-width: min(720px, 92%); padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--radius); line-height: 1.45; white-space: pre-wrap; }
|
.message { max-width: min(720px, 92%); padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--radius); line-height: 1.45; white-space: pre-wrap; }
|
||||||
.message.user { align-self: flex-end; background: #151e1a; }
|
.message.user { align-self: flex-end; background: #151e1a; }
|
||||||
.message.assistant { align-self: flex-start; background: #0f1613; }
|
.message.assistant { align-self: flex-start; background: #0f1613; }
|
||||||
.message small { display: block; margin-top: 8px; color: var(--muted); font: 10px/1 var(--mono); text-transform: uppercase; }
|
.message small { display: block; margin-top: 8px; color: var(--muted); font: 10px/1 var(--mono); text-transform: uppercase; }
|
||||||
.composer { position: sticky; bottom: 0; width: min(100%, 920px); margin: 0 auto; padding: 16px 18px 20px; display: grid; grid-template-columns: minmax(0, 1fr) 130px; gap: 12px; background: linear-gradient(transparent, var(--base) 20%); }
|
.composer { width: min(100%, 920px); margin: 0 auto; padding: 16px 18px 10px; display: grid; grid-template-columns: minmax(0, 1fr) 130px; gap: 12px; background: linear-gradient(transparent, var(--base) 20%); }
|
||||||
.composer button { height: 48px; align-self: end; }
|
.composer button { height: 48px; align-self: end; }
|
||||||
.composer button:disabled { cursor: wait; filter: saturate(.3); }
|
.composer button:disabled { cursor: wait; filter: saturate(.3); }
|
||||||
|
.conversation-starters { width: min(100%, 920px); margin: -4px auto 0; padding: 0 18px 18px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .06em; text-transform: uppercase; }
|
||||||
|
.conversation-starters button { min-height: 32px; padding: 0 10px; border: 1px solid var(--line); color: var(--ink); background: #101814; font: 10px/1 var(--mono); }
|
||||||
|
.conversation-starters button:hover, .conversation-starters button:focus-visible { border-color: var(--signal); color: var(--signal); outline: none; }
|
||||||
|
.ai-data-form { margin-top: 24px; }
|
||||||
|
.ai-data-form textarea { min-height: 150px; resize: vertical; }
|
||||||
|
.ai-data-form button { width: 100%; min-height: 42px; margin-top: 12px; border: 0; color: #11150f; background: var(--signal); font-weight: 700; }
|
||||||
|
.ai-data-error { margin: 10px 0 0; color: var(--bad); font-size: 12px; line-height: 1.4; }
|
||||||
|
.side-console-link { display: flex; justify-content: space-between; margin-top: 26px; padding-top: 16px; border-top: 1px solid var(--line); color: var(--signal) !important; font: 11px/1.3 var(--mono) !important; text-transform: uppercase; letter-spacing: .06em; }
|
||||||
.attention-surface, .history-surface { width: min(100%, 920px); margin: 0 auto; padding: 34px 18px; align-content: start; gap: 18px; }
|
.attention-surface, .history-surface { width: min(100%, 920px); margin: 0 auto; padding: 34px 18px; align-content: start; gap: 18px; }
|
||||||
.surface-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
|
.surface-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
|
||||||
.surface-heading p { margin: 0; font: 400 36px/.95 var(--serif); }
|
.surface-heading p { margin: 0; font: 400 36px/.95 var(--serif); }
|
||||||
@@ -67,10 +101,25 @@ textarea { resize: vertical; min-height: 84px; max-height: 240px; padding: 14px;
|
|||||||
.empty-state { margin: 24px 0 0; color: var(--muted); }
|
.empty-state { margin: 24px 0 0; color: var(--muted); }
|
||||||
.empty-state.error { color: var(--bad); }
|
.empty-state.error { color: var(--bad); }
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
|
.chat-view { height: auto; min-height: 100vh; overflow: visible; display: block; }
|
||||||
.composer { grid-template-columns: 1fr; }
|
.composer { grid-template-columns: 1fr; }
|
||||||
.composer button { width: 100%; }
|
.composer button { width: 100%; }
|
||||||
|
.conversation-starters { align-items: stretch; }
|
||||||
|
.conversation-starters span { width: 100%; }
|
||||||
.chat-header { gap: 10px; padding: 0 12px; }
|
.chat-header { gap: 10px; padding: 0 12px; }
|
||||||
.chat-header span { display: none; }
|
.chat-header .cognitive-status { display: inline-flex; max-width: 150px; overflow: hidden; text-overflow: ellipsis; }
|
||||||
.human-nav { overflow-x: auto; }
|
.build-meta { font-size: 8px; letter-spacing: .04em; }
|
||||||
|
.build-meta time { font-size: 7px; }
|
||||||
|
.chat-layout { height: auto; display: block; }
|
||||||
|
.chat-side, .chat-main { min-height: auto; max-height: none; overflow: visible; }
|
||||||
|
.chat-left, .chat-right { border: 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.chat-main { height: 70vh; min-height: 520px; }
|
||||||
|
.chat-left { padding-bottom: 20px; }
|
||||||
|
.chat-right { padding-top: 20px; }
|
||||||
.operator-link, .nav-tab { padding: 0 9px; }
|
.operator-link, .nav-tab { padding: 0 9px; }
|
||||||
}
|
}
|
||||||
|
@media (min-width: 641px) and (max-width: 1100px) {
|
||||||
|
.chat-layout { grid-template-columns: 210px minmax(0, 1fr) 245px; }
|
||||||
|
.chat-side { padding-inline: 14px; }
|
||||||
|
.side-intro h1, .side-intro h2 { font-size: 30px; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,14 +8,72 @@ const messageInput = document.querySelector("#message");
|
|||||||
const sendButton = document.querySelector("#send");
|
const sendButton = document.querySelector("#send");
|
||||||
const logoutButton = document.querySelector("#logout");
|
const logoutButton = document.querySelector("#logout");
|
||||||
const activeFocus = document.querySelector("#active-focus");
|
const activeFocus = document.querySelector("#active-focus");
|
||||||
|
const cognitiveStatus = document.querySelector("#cognitive-status");
|
||||||
|
const cognitiveConsoleLink = document.querySelector("#cognitive-console-link");
|
||||||
const todayList = document.querySelector("#today-list");
|
const todayList = document.querySelector("#today-list");
|
||||||
const refreshToday = document.querySelector("#refresh-today");
|
const refreshToday = document.querySelector("#refresh-today");
|
||||||
const historyList = document.querySelector("#history-list");
|
const historyList = document.querySelector("#history-list");
|
||||||
const navTabs = Array.from(document.querySelectorAll(".nav-tab"));
|
const navTabs = Array.from(document.querySelectorAll(".nav-tab"));
|
||||||
|
const conversationStarters = Array.from(document.querySelectorAll("[data-starter]"));
|
||||||
|
const aiDataForm = document.querySelector("#ai-data-form");
|
||||||
|
const aiDataInput = document.querySelector("#ai-data");
|
||||||
|
const aiDataError = document.querySelector("#ai-data-error");
|
||||||
|
|
||||||
let token = sessionStorage.getItem("domovoy.chat.token") || "";
|
let token = sessionStorage.getItem("domovoy.chat.token") || "";
|
||||||
let conversationID = sessionStorage.getItem("domovoy.chat.conversation") || "";
|
let conversationID = sessionStorage.getItem("domovoy.chat.conversation") || "";
|
||||||
let localHistory = [];
|
let localHistory = [];
|
||||||
|
let cognitiveStatusTimer = null;
|
||||||
|
|
||||||
|
function containsSecretShapedText(value) {
|
||||||
|
return /(-----BEGIN [A-Z ]+PRIVATE KEY-----|\b(?:password|passwd|пароль|token|токен|api[_ -]?key|секрет|ключ)\s*[:=]|\bsk-[a-zA-Z0-9_-]{12,})/i.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showAIDataError(message = "") {
|
||||||
|
if (!aiDataError) return;
|
||||||
|
aiDataError.textContent = message;
|
||||||
|
aiDataError.hidden = !message;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCognitiveStatus(state) {
|
||||||
|
if (!cognitiveStatus) return;
|
||||||
|
const normalized = String(state || "UNKNOWN").toUpperCase();
|
||||||
|
let displayState = "degraded";
|
||||||
|
if (normalized === "AVAILABLE") displayState = "available";
|
||||||
|
if (normalized === "UNAVAILABLE") displayState = "unavailable";
|
||||||
|
const labels = {
|
||||||
|
available: "канал мышления доступен",
|
||||||
|
degraded: "канал мышления работает с ограничениями",
|
||||||
|
unavailable: "Домовой рядом · основной канал недоступен",
|
||||||
|
};
|
||||||
|
cognitiveStatus.dataset.state = displayState;
|
||||||
|
cognitiveStatus.textContent = labels[displayState];
|
||||||
|
cognitiveStatus.title = displayState === "available" ? "Канал доступен. Нажмите, чтобы проверить ещё раз" : "Проверить канал ещё раз";
|
||||||
|
if (cognitiveConsoleLink) cognitiveConsoleLink.hidden = displayState === "available";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadCognitiveStatus() {
|
||||||
|
if (!cognitiveStatus || !token) return;
|
||||||
|
cognitiveStatus.dataset.state = "checking";
|
||||||
|
cognitiveStatus.textContent = "проверяю канал мышления";
|
||||||
|
try {
|
||||||
|
const result = await api("/api/capabilities/cognitive-proposal/health", {method: "GET"});
|
||||||
|
renderCognitiveStatus(result.State || result.state || "UNKNOWN");
|
||||||
|
} catch {
|
||||||
|
renderCognitiveStatus("UNAVAILABLE");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCognitiveStatusPolling() {
|
||||||
|
if (cognitiveStatusTimer) return;
|
||||||
|
loadCognitiveStatus();
|
||||||
|
cognitiveStatusTimer = window.setInterval(loadCognitiveStatus, 30000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopCognitiveStatusPolling() {
|
||||||
|
if (!cognitiveStatusTimer) return;
|
||||||
|
window.clearInterval(cognitiveStatusTimer);
|
||||||
|
cognitiveStatusTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
function showChat() {
|
function showChat() {
|
||||||
loginView.hidden = true;
|
loginView.hidden = true;
|
||||||
@@ -23,10 +81,12 @@ function showChat() {
|
|||||||
if (!messages.children.length) {
|
if (!messages.children.length) {
|
||||||
appendMessage("assistant", "Я рядом. Напишите обычное сообщение, без внутренних идентификаторов.");
|
appendMessage("assistant", "Я рядом. Напишите обычное сообщение, без внутренних идентификаторов.");
|
||||||
}
|
}
|
||||||
|
startCognitiveStatusPolling();
|
||||||
messageInput.focus();
|
messageInput.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function showLogin() {
|
function showLogin() {
|
||||||
|
stopCognitiveStatusPolling();
|
||||||
chatView.hidden = true;
|
chatView.hidden = true;
|
||||||
loginView.hidden = false;
|
loginView.hidden = false;
|
||||||
}
|
}
|
||||||
@@ -235,7 +295,32 @@ for (const tab of navTabs) {
|
|||||||
tab.addEventListener("click", () => activateTab(tab.dataset.tab));
|
tab.addEventListener("click", () => activateTab(tab.dataset.tab));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const starter of conversationStarters) {
|
||||||
|
starter.addEventListener("click", async () => {
|
||||||
|
const text = starter.dataset.starter || "";
|
||||||
|
if (!text || sendButton.disabled) return;
|
||||||
|
messageInput.value = "";
|
||||||
|
await sendChatMessage(text);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (refreshToday) refreshToday.addEventListener("click", loadToday);
|
if (refreshToday) refreshToday.addEventListener("click", loadToday);
|
||||||
|
if (cognitiveStatus) cognitiveStatus.addEventListener("click", loadCognitiveStatus);
|
||||||
|
if (aiDataForm) {
|
||||||
|
aiDataForm.addEventListener("submit", async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const details = aiDataInput.value.trim();
|
||||||
|
if (!details || sendButton.disabled) return;
|
||||||
|
if (containsSecretShapedText(details)) {
|
||||||
|
showAIDataError("Не отправляю секреты. Удалите пароль, токен, API-ключ или приватный ключ и оставьте только описание модели.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showAIDataError();
|
||||||
|
aiDataInput.value = "";
|
||||||
|
await sendChatMessage(`Передаю сведения о локальном ИИ для текущего разговора:\n${details}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (aiDataInput) aiDataInput.addEventListener("input", () => showAIDataError());
|
||||||
|
|
||||||
logoutButton.addEventListener("click", () => {
|
logoutButton.addEventListener("click", () => {
|
||||||
token = "";
|
token = "";
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
:root {
|
:root {
|
||||||
--ink: #e9eee7;
|
--ink: #eef2ec;
|
||||||
--muted: #8c9a91;
|
--muted: #a7b2aa;
|
||||||
--faint: #58645d;
|
--faint: #718078;
|
||||||
--base: #0b100e;
|
--base: #0f1512;
|
||||||
--panel: #101714;
|
--panel: #17201b;
|
||||||
--panel-high: #151e1a;
|
--panel-high: #202b25;
|
||||||
--line: #2a352f;
|
--line: #34423a;
|
||||||
--line-soft: #1d2822;
|
--line-soft: #26332c;
|
||||||
--signal: #c9a85f;
|
--signal: #c9a85f;
|
||||||
--signal-bright: #e7c97b;
|
--signal-bright: #e7c97b;
|
||||||
--good: #78c6a3;
|
--good: #78c6a3;
|
||||||
@@ -21,13 +21,15 @@
|
|||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
[hidden] { display: none !important; }
|
[hidden] { display: none !important; }
|
||||||
html { background: var(--base); color: var(--ink); font-family: var(--sans); }
|
html { background: var(--base); color: var(--ink); font-family: var(--sans); scroll-behavior: smooth; }
|
||||||
body { margin: 0; min-width: 320px; min-height: 100vh; background: radial-gradient(circle at 73% -10%, rgba(83, 123, 101, .15), transparent 38%), var(--base); }
|
body { margin: 0; min-width: 320px; min-height: 100vh; background: radial-gradient(circle at 73% -10%, rgba(83, 123, 101, .13), transparent 38%), var(--base); }
|
||||||
button, input, textarea { font: inherit; }
|
button, input, textarea { font: inherit; }
|
||||||
button { color: inherit; }
|
button { color: inherit; }
|
||||||
button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--signal-bright); outline-offset: 3px; }
|
button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible { outline: 2px solid var(--signal-bright); outline-offset: 3px; }
|
||||||
|
.skip-link { position: fixed; top: 10px; left: 10px; z-index: 30; padding: 10px 13px; color: #11150f; background: var(--signal-bright); font: 600 10px/1 var(--mono); text-decoration: none; transform: translateY(-160%); transition: transform .18s; }
|
||||||
|
.skip-link:focus { transform: translateY(0); }
|
||||||
|
|
||||||
.grain { position: fixed; inset: 0; pointer-events: none; opacity: .18; z-index: 10; background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 160 160' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.16'/%3E%3C/svg%3E"); }
|
.grain { position: fixed; inset: 0; pointer-events: none; opacity: .045; z-index: 10; background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 160 160' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.16'/%3E%3C/svg%3E"); }
|
||||||
.eyebrow, .rail-index { margin: 0 0 12px; color: var(--signal); font: 600 11px/1 var(--mono); letter-spacing: .18em; text-transform: uppercase; }
|
.eyebrow, .rail-index { margin: 0 0 12px; color: var(--signal); font: 600 11px/1 var(--mono); letter-spacing: .18em; text-transform: uppercase; }
|
||||||
|
|
||||||
.login-shell { min-height: 100vh; display: grid; place-items: center; padding: 32px 20px; position: relative; overflow: hidden; }
|
.login-shell { min-height: 100vh; display: grid; place-items: center; padding: 32px 20px; position: relative; overflow: hidden; }
|
||||||
@@ -63,6 +65,10 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
|||||||
.wordmark strong { font: 400 20px/1 var(--serif); }
|
.wordmark strong { font: 400 20px/1 var(--serif); }
|
||||||
.wordmark small { margin-top: 4px; color: var(--muted); font: 9px/1 var(--mono); letter-spacing: .12em; text-transform: uppercase; }
|
.wordmark small { margin-top: 4px; color: var(--muted); font: 9px/1 var(--mono); letter-spacing: .12em; text-transform: uppercase; }
|
||||||
.topbar-actions { display: flex; align-items: center; gap: 10px; }
|
.topbar-actions { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.chat-return-link { color: var(--signal); text-decoration: none; font: 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; white-space: nowrap; }
|
||||||
|
.topbar-nav { display: flex; align-items: center; gap: 4px; margin-right: 8px; }
|
||||||
|
.topbar-nav a { padding: 9px 10px; color: var(--muted); text-decoration: none; font: 600 9px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; }
|
||||||
|
.topbar-nav a:hover, .topbar-nav a:focus-visible { color: var(--ink); background: var(--panel-high); outline: 0; }
|
||||||
.connection { margin-right: 12px; color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; }
|
.connection { margin-right: 12px; color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; }
|
||||||
.connection i { width: 7px; height: 7px; display: inline-block; margin-right: 8px; border-radius: 50%; background: var(--good); box-shadow: 0 0 14px rgba(120, 198, 163, .6); }
|
.connection i { width: 7px; height: 7px; display: inline-block; margin-right: 8px; border-radius: 50%; background: var(--good); box-shadow: 0 0 14px rgba(120, 198, 163, .6); }
|
||||||
.connection.offline i { background: var(--bad); box-shadow: none; }
|
.connection.offline i { background: var(--bad); box-shadow: none; }
|
||||||
@@ -73,17 +79,55 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
|||||||
.context-rail h2 { margin: 0; font: 400 29px/1.1 var(--serif); }
|
.context-rail h2 { margin: 0; font: 400 29px/1.1 var(--serif); }
|
||||||
.rail-copy { margin: 14px 0 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
.rail-copy { margin: 14px 0 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||||
.context-form { display: grid; }
|
.context-form { display: grid; }
|
||||||
|
.context-status-row { margin-bottom: 16px; padding: 10px 11px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border: 1px solid var(--line-soft); background: rgba(120,198,163,.04); }
|
||||||
|
.context-status-label { color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .1em; }
|
||||||
|
.context-status-row strong { color: var(--warn); font: 600 9px/1 var(--mono); letter-spacing: .06em; text-transform: uppercase; }
|
||||||
|
.context-status-row strong[data-state="ready"] { color: var(--good); }
|
||||||
|
.context-presets { display: grid; gap: 7px; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid var(--line-soft); }
|
||||||
|
.context-presets label { margin: 0; }
|
||||||
|
.context-presets select { width: 100%; min-height: 38px; padding: 0 9px; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); background: #0b110e; font: 10px/1 var(--mono); }
|
||||||
|
.context-presets small { color: var(--faint); font-size: 10px; line-height: 1.35; }
|
||||||
|
.context-field { display: grid; gap: 7px; }
|
||||||
|
.context-field + .context-field { margin-top: 13px; }
|
||||||
|
.context-field label { margin: 0; }
|
||||||
|
.context-field label span { color: var(--signal); font-size: 8px; letter-spacing: .06em; }
|
||||||
|
.context-input-row { display: grid; grid-template-columns: minmax(0, 1fr) 34px; gap: 5px; }
|
||||||
|
.context-input-row input { min-width: 0; }
|
||||||
|
.copy-context { width: 34px; height: 40px; border: 1px solid var(--line); border-radius: var(--radius); color: var(--muted); background: transparent; cursor: pointer; }
|
||||||
|
.copy-context:hover { color: var(--ink); border-color: var(--faint); background: var(--panel-high); }
|
||||||
|
.id-actions { min-height: 31px; display: flex; align-items: center; gap: 7px; margin-top: 12px; }
|
||||||
|
.id-action { min-height: 30px; padding: 0 9px; border: 1px solid var(--line-soft); border-radius: var(--radius); color: var(--muted); background: transparent; cursor: pointer; font: 9px/1 var(--mono); letter-spacing: .04em; }
|
||||||
|
.id-action:hover { color: var(--ink); border-color: var(--signal); background: rgba(201,168,95,.07); }
|
||||||
|
.icon-id-action { width: 30px; padding: 0; color: var(--faint); }
|
||||||
.context-form label { margin-top: 15px; }
|
.context-form label { margin-top: 15px; }
|
||||||
.context-form label:first-child { margin-top: 0; }
|
.context-form label:first-child { margin-top: 0; }
|
||||||
.context-form input { height: 40px; padding: 0 10px; font: 11px/1 var(--mono); }
|
.context-form input { height: 40px; padding: 0 10px; font: 11px/1 var(--mono); }
|
||||||
|
.context-hint { margin: 12px 0 0; color: var(--faint); font-size: 10px; line-height: 1.45; }
|
||||||
|
.advanced-context { margin-top: 17px; border-top: 1px solid var(--line-soft); border-bottom: 1px solid var(--line-soft); }
|
||||||
|
.advanced-context summary { padding: 12px 0; color: var(--muted); cursor: pointer; list-style: none; font: 600 9px/1.2 var(--mono); letter-spacing: .08em; text-transform: uppercase; }
|
||||||
|
.advanced-context summary::before { content: "+"; display: inline-block; width: 18px; color: var(--signal); font-size: 13px; }
|
||||||
|
.advanced-context[open] summary::before { content: "−"; }
|
||||||
|
.advanced-context > div { padding: 0 0 10px; }
|
||||||
|
.advanced-context label { margin-top: 13px; }
|
||||||
|
.context-actions { display: grid; gap: 8px; }
|
||||||
|
.context-actions .secondary-button { margin-top: 18px; }
|
||||||
|
.context-actions .text-button { margin: 0; justify-self: start; padding-inline: 0; }
|
||||||
.secondary-button { height: 42px; margin-top: 20px; color: #11150f; background: var(--signal); font-size: 12px; }
|
.secondary-button { height: 42px; margin-top: 20px; color: #11150f; background: var(--signal); font-size: 12px; }
|
||||||
|
.section-nav { display: grid; gap: 3px; margin-top: 4px; }
|
||||||
|
.section-nav-link { display: grid; grid-template-columns: 28px 1fr; gap: 2px 10px; padding: 11px 10px; border-left: 2px solid transparent; color: var(--muted); text-decoration: none; transition: background .18s, border-color .18s, color .18s; }
|
||||||
|
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="location"] { border-left-color: var(--signal); color: var(--ink); background: rgba(201,168,95,.07); outline: 0; }
|
||||||
|
.section-nav-link span { grid-row: 1 / span 2; color: var(--signal); font: 9px/1.4 var(--mono); }
|
||||||
|
.section-nav-link b { font: 600 11px/1.2 var(--sans); }
|
||||||
|
.section-nav-link small { color: var(--faint); font: 9px/1.2 var(--mono); }
|
||||||
.session-stamp { margin-top: auto; padding-top: 20px; display: grid; gap: 6px; border-top: 1px solid var(--line); }
|
.session-stamp { margin-top: auto; padding-top: 20px; display: grid; gap: 6px; border-top: 1px solid var(--line); }
|
||||||
.session-stamp span { margin-top: 8px; color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .14em; }
|
.session-stamp span { margin-top: 8px; color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .14em; }
|
||||||
.session-stamp strong { overflow: hidden; color: var(--muted); font: 10px/1.4 var(--mono); text-overflow: ellipsis; }
|
.session-stamp strong { overflow: hidden; color: var(--muted); font: 10px/1.4 var(--mono); text-overflow: ellipsis; }
|
||||||
|
|
||||||
.workspace { grid-column: 2; grid-row: 2; padding: clamp(28px, 4vw, 58px); min-width: 0; }
|
.workspace { grid-column: 2; grid-row: 2; width: min(100%, 1740px); justify-self: start; padding: 42px clamp(24px, 3vw, 48px) 64px; min-width: 0; }
|
||||||
|
.workspace > [data-page][hidden] { display: none !important; }
|
||||||
|
.workspace > section { scroll-margin-top: 94px; }
|
||||||
.workspace-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 34px; }
|
.workspace-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 34px; }
|
||||||
.workspace-head h1 { margin: 0; font: 400 clamp(36px, 5vw, 58px)/1 var(--serif); letter-spacing: -.035em; }
|
.workspace-head h1 { margin: 0; font: 400 clamp(34px, 4vw, 50px)/1 var(--serif); letter-spacing: -.035em; }
|
||||||
.last-update { color: var(--faint); font: 10px/1.4 var(--mono); text-align: right; }
|
.last-update { color: var(--faint); font: 10px/1.4 var(--mono); text-align: right; }
|
||||||
.signal-strip { display: grid; grid-template-columns: repeat(4, 1fr); margin-bottom: 18px; border: 1px solid var(--line); background: var(--panel); }
|
.signal-strip { display: grid; grid-template-columns: repeat(4, 1fr); margin-bottom: 18px; border: 1px solid var(--line); background: var(--panel); }
|
||||||
.signal-strip div { padding: 16px 18px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-right: 1px solid var(--line); }
|
.signal-strip div { padding: 16px 18px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-right: 1px solid var(--line); }
|
||||||
@@ -94,6 +138,46 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
|||||||
.signal-strip strong[data-state="error"] { color: var(--bad); }
|
.signal-strip strong[data-state="error"] { color: var(--bad); }
|
||||||
.signal-strip strong[data-state="loading"] { color: var(--warn); animation: pulse 1.1s ease-in-out infinite; }
|
.signal-strip strong[data-state="loading"] { color: var(--warn); animation: pulse 1.1s ease-in-out infinite; }
|
||||||
|
|
||||||
|
.diagnostics-panel, .settings-panel { margin-bottom: 18px; border: 1px solid var(--line); background: rgba(16,23,20,.82); }
|
||||||
|
.diagnostics-panel { border-color: rgba(120,198,163,.32); box-shadow: inset 3px 0 0 rgba(120,198,163,.45); }
|
||||||
|
.panel-heading { min-height: 68px; padding: 14px 18px; display: flex; align-items: center; justify-content: space-between; gap: 18px; border-bottom: 1px solid var(--line); }
|
||||||
|
.panel-heading p { margin: 0 0 6px; color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .13em; text-transform: uppercase; }
|
||||||
|
.panel-heading h2 { margin: 0; font: 400 23px/1 var(--serif); }
|
||||||
|
.panel-heading-tools { display: flex; align-items: center; gap: 14px; }
|
||||||
|
.panel-heading-tools > span, .settings-saved { color: var(--muted); font: 9px/1.3 var(--mono); letter-spacing: .06em; text-transform: uppercase; }
|
||||||
|
.compact-button { width: auto; min-width: 142px; height: 38px; margin: 0; padding: 0 13px; }
|
||||||
|
.diagnostic-intro { padding: 13px 18px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid var(--line-soft); color: var(--muted); }
|
||||||
|
.diagnostic-intro p { margin: 0; font-size: 11px; line-height: 1.45; }
|
||||||
|
.diagnostic-pulse { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: var(--good); box-shadow: 0 0 12px rgba(120,198,163,.7); }
|
||||||
|
.diagnostic-list { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||||
|
.diagnostic-list[aria-busy="true"] { opacity: .7; }
|
||||||
|
.diagnostic-item { min-width: 0; min-height: 92px; padding: 14px 16px; display: grid; grid-template-columns: 9px 1fr auto; gap: 9px; align-items: start; border-right: 1px solid var(--line-soft); border-bottom: 1px solid var(--line-soft); }
|
||||||
|
.diagnostic-item:nth-child(4n) { border-right: 0; }
|
||||||
|
.diagnostic-item > i { width: 7px; height: 7px; margin-top: 4px; border-radius: 50%; background: var(--faint); }
|
||||||
|
.diagnostic-item[data-state="ok"] > i { background: var(--good); box-shadow: 0 0 9px rgba(120,198,163,.6); }
|
||||||
|
.diagnostic-item[data-state="error"] > i { background: var(--bad); }
|
||||||
|
.diagnostic-item[data-state="loading"] > i { background: var(--warn); animation: pulse 1.1s ease-in-out infinite; }
|
||||||
|
.diagnostic-item strong { display: block; color: var(--ink); font: 600 10px/1.3 var(--mono); }
|
||||||
|
.diagnostic-item span { display: block; margin-top: 6px; color: var(--muted); font-size: 10px; line-height: 1.35; }
|
||||||
|
.diagnostic-item em { color: var(--faint); font: normal 9px/1.2 var(--mono); text-transform: uppercase; }
|
||||||
|
.diagnostic-item[data-state="ok"] em { color: var(--good); }
|
||||||
|
.diagnostic-item[data-state="error"] em { color: var(--bad); }
|
||||||
|
.settings-grid { padding: 18px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 20px; }
|
||||||
|
.setting-field, .setting-check { min-width: 0; display: grid; gap: 7px; color: var(--ink); }
|
||||||
|
.setting-field > span, .setting-check b { font: 600 10px/1.2 var(--mono); letter-spacing: .08em; text-transform: uppercase; }
|
||||||
|
.setting-field small, .setting-check small { color: var(--muted); font-size: 11px; line-height: 1.4; }
|
||||||
|
.setting-field select { width: 100%; min-height: 40px; padding: 0 10px; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); background: #0b110e; font: 11px/1 var(--mono); }
|
||||||
|
.setting-check { grid-template-columns: 18px 1fr; align-items: start; gap: 10px; padding: 10px 12px; border: 1px solid var(--line-soft); }
|
||||||
|
.setting-check input { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--signal); }
|
||||||
|
.setting-check span { display: grid; gap: 7px; }
|
||||||
|
.settings-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; grid-column: 1 / -1; padding-top: 2px; }
|
||||||
|
.settings-actions .text-button { margin: 0; }
|
||||||
|
html[data-density="compact"] .data-card { padding: 18px; }
|
||||||
|
html[data-density="compact"] .data-card dl div { padding-block: 10px; }
|
||||||
|
html[data-density="compact"] .activity-row { min-height: 58px; padding-block: 8px; }
|
||||||
|
html[data-density="compact"] .learning-row { min-height: 54px; padding-block: 9px; }
|
||||||
|
html[data-reduced-motion="true"] *, html[data-reduced-motion="true"] *::before, html[data-reduced-motion="true"] *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; scroll-behavior: auto !important; transition-duration: .01ms !important; }
|
||||||
|
|
||||||
.advisor-panel { margin-bottom: 18px; padding: 24px; display: grid; grid-template-columns: minmax(220px, .72fr) minmax(320px, 1.28fr); gap: 18px 34px; border: 1px solid rgba(201,168,95,.42); background: linear-gradient(125deg, rgba(201,168,95,.1), rgba(16,23,20,.88) 44%, rgba(12,20,17,.96)); box-shadow: inset 3px 0 0 rgba(201,168,95,.58); }
|
.advisor-panel { margin-bottom: 18px; padding: 24px; display: grid; grid-template-columns: minmax(220px, .72fr) minmax(320px, 1.28fr); gap: 18px 34px; border: 1px solid rgba(201,168,95,.42); background: linear-gradient(125deg, rgba(201,168,95,.1), rgba(16,23,20,.88) 44%, rgba(12,20,17,.96)); box-shadow: inset 3px 0 0 rgba(201,168,95,.58); }
|
||||||
.advisor-intro { align-self: center; }
|
.advisor-intro { align-self: center; }
|
||||||
.advisor-intro > p { margin: 0 0 10px; color: var(--signal); font: 600 9px/1 var(--mono); letter-spacing: .15em; }
|
.advisor-intro > p { margin: 0 0 10px; color: var(--signal); font: 600 9px/1 var(--mono); letter-spacing: .15em; }
|
||||||
@@ -278,6 +362,9 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
|||||||
.advisor-panel { grid-template-columns: 1fr; }
|
.advisor-panel { grid-template-columns: 1fr; }
|
||||||
.capability-card { grid-column: auto; }
|
.capability-card { grid-column: auto; }
|
||||||
.prospective-card { grid-column: auto; }
|
.prospective-card { grid-column: auto; }
|
||||||
|
.diagnostic-list { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
.diagnostic-item:nth-child(4n) { border-right: 1px solid var(--line-soft); }
|
||||||
|
.diagnostic-item:nth-child(2n) { border-right: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 680px) {
|
@media (max-width: 680px) {
|
||||||
@@ -285,14 +372,26 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
|||||||
.console { display: block; }
|
.console { display: block; }
|
||||||
.topbar { height: 66px; padding: 0 14px; }
|
.topbar { height: 66px; padding: 0 14px; }
|
||||||
.wordmark small, .connection, .text-button { display: none; }
|
.wordmark small, .connection, .text-button { display: none; }
|
||||||
|
.chat-return-link { display: inline-block; }
|
||||||
|
.topbar-nav { display: none; }
|
||||||
.context-rail { padding: 24px 18px; border-right: 0; border-bottom: 1px solid var(--line); }
|
.context-rail { padding: 24px 18px; border-right: 0; border-bottom: 1px solid var(--line); }
|
||||||
.rail-copy { max-width: 48ch; }
|
.rail-copy { max-width: 48ch; }
|
||||||
.session-stamp { margin-top: 8px; grid-template-columns: auto 1fr; align-items: center; }
|
.session-stamp { margin-top: 8px; grid-template-columns: auto 1fr; align-items: center; }
|
||||||
.session-stamp span { margin: 0; }
|
.session-stamp span { margin: 0; }
|
||||||
.workspace { padding: 30px 16px 50px; }
|
.workspace { padding: 30px 16px 50px; }
|
||||||
|
.section-nav { display: flex; gap: 6px; margin: 10px -18px -24px; padding: 10px 18px; overflow-x: auto; border-top: 1px solid var(--line-soft); background: #0e1512; scrollbar-width: thin; }
|
||||||
|
.section-nav-link { min-width: 142px; padding: 10px; border-left: 0; border-bottom: 2px solid transparent; }
|
||||||
|
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="location"] { border-left-color: transparent; border-bottom-color: var(--signal); }
|
||||||
.workspace-head { align-items: start; flex-direction: column; }
|
.workspace-head { align-items: start; flex-direction: column; }
|
||||||
.last-update { text-align: left; }
|
.last-update { text-align: left; }
|
||||||
.signal-strip { grid-template-columns: 1fr; }
|
.signal-strip { grid-template-columns: 1fr; }
|
||||||
|
.panel-heading { align-items: flex-start; flex-direction: column; }
|
||||||
|
.panel-heading-tools { width: 100%; justify-content: space-between; }
|
||||||
|
.diagnostic-list { grid-template-columns: 1fr; }
|
||||||
|
.diagnostic-item, .diagnostic-item:nth-child(2n), .diagnostic-item:nth-child(4n) { border-right: 0; }
|
||||||
|
.settings-grid { grid-template-columns: 1fr; padding: 16px; }
|
||||||
|
.settings-actions { grid-column: auto; align-items: stretch; flex-direction: column; }
|
||||||
|
.settings-actions .primary-button { width: 100%; }
|
||||||
.signal-strip div { border-right: 0; border-bottom: 1px solid var(--line); }
|
.signal-strip div { border-right: 0; border-bottom: 1px solid var(--line); }
|
||||||
.advisor-panel { padding: 20px 16px; gap: 20px; }
|
.advisor-panel { padding: 20px 16px; gap: 20px; }
|
||||||
.advisor-controls { align-items: stretch; flex-direction: column; }
|
.advisor-controls { align-items: stretch; flex-direction: column; }
|
||||||
|
|||||||
@@ -7,14 +7,42 @@ const advisoryForm = byId("advisory-form");
|
|||||||
const loginError = byId("login-error");
|
const loginError = byId("login-error");
|
||||||
const toast = byId("toast");
|
const toast = byId("toast");
|
||||||
const contextFields = ["session-id", "workspace-id", "task-id", "prospective-id", "capability-id"];
|
const contextFields = ["session-id", "workspace-id", "task-id", "prospective-id", "capability-id"];
|
||||||
|
const settingsStorageKey = "domovoy.creator.settings";
|
||||||
|
const contextPresetsStorageKey = "domovoy.creator.context.presets";
|
||||||
let sessionToken = sessionStorage.getItem("domovoy.creator.session") || "";
|
let sessionToken = sessionStorage.getItem("domovoy.creator.session") || "";
|
||||||
let toastTimer;
|
let toastTimer;
|
||||||
|
let refreshTimer;
|
||||||
let currentTask = null;
|
let currentTask = null;
|
||||||
let currentProspective = null;
|
let currentProspective = null;
|
||||||
let pendingCommand = null;
|
let pendingCommand = null;
|
||||||
let pendingNotification = null;
|
let pendingNotification = null;
|
||||||
let lastAuthorizedActionID = "";
|
let lastAuthorizedActionID = "";
|
||||||
let advisoryPolicy = {Mode: "deterministic", ExternalEgress: false, AcknowledgementRequired: false};
|
let advisoryPolicy = {Mode: "deterministic", ExternalEgress: false, AcknowledgementRequired: false};
|
||||||
|
let uiSettings = {density: "comfortable", refresh: "off", motion: false};
|
||||||
|
|
||||||
|
const pageNavLinks = Array.from(document.querySelectorAll(".section-nav-link, .topbar-nav a"));
|
||||||
|
const pageViews = Array.from(document.querySelectorAll("[data-page]"));
|
||||||
|
const cabinetPages = ["overview", "diagnostics", "operations", "learning", "settings"];
|
||||||
|
|
||||||
|
function setActivePage(id, updateHistory = false) {
|
||||||
|
const page = cabinetPages.includes(id) ? id : "overview";
|
||||||
|
pageViews.forEach((view) => { view.hidden = view.dataset.page !== page; });
|
||||||
|
document.body.dataset.page = page;
|
||||||
|
pageNavLinks.forEach((link) => {
|
||||||
|
const active = link.getAttribute("href") === `#${page}`;
|
||||||
|
link.classList.toggle("active", active);
|
||||||
|
if (active) link.setAttribute("aria-current", "location");
|
||||||
|
else link.removeAttribute("aria-current");
|
||||||
|
});
|
||||||
|
if (updateHistory && window.location.hash !== `#${page}`) window.history.pushState({}, "", `#${page}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
pageNavLinks.forEach((link) => link.addEventListener("click", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setActivePage(link.getAttribute("href").slice(1), true);
|
||||||
|
}));
|
||||||
|
window.addEventListener("popstate", () => setActivePage(window.location.hash.slice(1)));
|
||||||
|
setActivePage(window.location.hash.slice(1));
|
||||||
|
|
||||||
function setText(id, value, fallback = "—") {
|
function setText(id, value, fallback = "—") {
|
||||||
byId(id).textContent = value === undefined || value === null || value === "" ? fallback : String(value);
|
byId(id).textContent = value === undefined || value === null || value === "" ? fallback : String(value);
|
||||||
@@ -39,6 +67,18 @@ function notify(message) {
|
|||||||
toastTimer = setTimeout(() => { toast.hidden = true; }, 4200);
|
toastTimer = setTimeout(() => { toast.hidden = true; }, 4200);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function safeClientError(error) {
|
||||||
|
const message = error && typeof error.message === "string" ? error.message : "";
|
||||||
|
switch (message) {
|
||||||
|
case "creator authentication denied":
|
||||||
|
return "Логин или пароль не принят.";
|
||||||
|
case "Сессия отклонена":
|
||||||
|
return "Сессия истекла. Войдите снова.";
|
||||||
|
default:
|
||||||
|
return "Операция недоступна. Попробуйте ещё раз.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function request(path, options = {}) {
|
async function request(path, options = {}) {
|
||||||
const headers = new Headers(options.headers || {});
|
const headers = new Headers(options.headers || {});
|
||||||
if (sessionToken) headers.set("Authorization", `Bearer ${sessionToken}`);
|
if (sessionToken) headers.set("Authorization", `Bearer ${sessionToken}`);
|
||||||
@@ -50,7 +90,9 @@ async function request(path, options = {}) {
|
|||||||
}
|
}
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const detail = (await response.text()).trim();
|
const detail = (await response.text()).trim();
|
||||||
throw new Error(detail || `Ошибка ${response.status}`);
|
const error = new Error(detail || `Ошибка ${response.status}`);
|
||||||
|
error.status = response.status;
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
@@ -64,15 +106,57 @@ function restoreContext() {
|
|||||||
} catch (_) {
|
} catch (_) {
|
||||||
localStorage.removeItem("domovoy.creator.context");
|
localStorage.removeItem("domovoy.creator.context");
|
||||||
}
|
}
|
||||||
|
renderContextState();
|
||||||
|
renderContextPresets();
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveContext() {
|
function saveContext() {
|
||||||
const saved = {};
|
const saved = {};
|
||||||
contextFields.forEach((id) => { saved[id] = byId(id).value.trim(); });
|
contextFields.forEach((id) => { saved[id] = byId(id).value.trim(); });
|
||||||
localStorage.setItem("domovoy.creator.context", JSON.stringify(saved));
|
localStorage.setItem("domovoy.creator.context", JSON.stringify(saved));
|
||||||
|
renderContextState();
|
||||||
return saved;
|
return saved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readContextPresets() {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(localStorage.getItem(contextPresetsStorageKey) || "[]");
|
||||||
|
return Array.isArray(value) ? value.filter((item) => item && item.session && item.workspace) : [];
|
||||||
|
} catch (_) {
|
||||||
|
localStorage.removeItem(contextPresetsStorageKey);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderContextState() {
|
||||||
|
const state = byId("context-state");
|
||||||
|
if (!state) return;
|
||||||
|
const ready = Boolean(byId("session-id").value.trim() && byId("workspace-id").value.trim());
|
||||||
|
state.textContent = ready ? "готов к проверке" : "не выбран";
|
||||||
|
state.dataset.state = ready ? "ready" : "empty";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderContextPresets() {
|
||||||
|
const select = byId("context-preset");
|
||||||
|
if (!select) return;
|
||||||
|
const presets = readContextPresets();
|
||||||
|
select.replaceChildren(new Option("Выберите сохранённый набор…", ""));
|
||||||
|
presets.forEach((preset, index) => {
|
||||||
|
const session = preset.session.length > 18 ? `${preset.session.slice(0, 8)}…${preset.session.slice(-6)}` : preset.session;
|
||||||
|
const workspace = preset.workspace.length > 18 ? `${preset.workspace.slice(0, 8)}…${preset.workspace.slice(-6)}` : preset.workspace;
|
||||||
|
select.appendChild(new Option(`${session} · ${workspace}`, String(index)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function rememberContextPreset(context) {
|
||||||
|
if (!context["session-id"] || !context["workspace-id"]) return;
|
||||||
|
const next = {session: context["session-id"], workspace: context["workspace-id"], savedAt: Date.now()};
|
||||||
|
const presets = readContextPresets().filter((item) => item.session !== next.session || item.workspace !== next.workspace);
|
||||||
|
presets.unshift(next);
|
||||||
|
localStorage.setItem(contextPresetsStorageKey, JSON.stringify(presets.slice(0, 5)));
|
||||||
|
renderContextPresets();
|
||||||
|
}
|
||||||
|
|
||||||
async function showConsole() {
|
async function showConsole() {
|
||||||
const session = await request("/api/session/current");
|
const session = await request("/api/session/current");
|
||||||
setText("session-actor", session.ActorID);
|
setText("session-actor", session.ActorID);
|
||||||
@@ -80,6 +164,7 @@ async function showConsole() {
|
|||||||
setText("session-expiry", expiry);
|
setText("session-expiry", expiry);
|
||||||
loginView.hidden = true;
|
loginView.hidden = true;
|
||||||
consoleView.hidden = false;
|
consoleView.hidden = false;
|
||||||
|
restoreSettings();
|
||||||
restoreContext();
|
restoreContext();
|
||||||
await loadAdvisoryPolicy();
|
await loadAdvisoryPolicy();
|
||||||
const context = saveContext();
|
const context = saveContext();
|
||||||
@@ -88,10 +173,13 @@ async function showConsole() {
|
|||||||
loadActionHistory();
|
loadActionHistory();
|
||||||
loadLearning();
|
loadLearning();
|
||||||
}
|
}
|
||||||
|
runDiagnostics();
|
||||||
}
|
}
|
||||||
|
|
||||||
function endSession(message = "Сессия завершена.") {
|
function endSession(message = "Сессия завершена.") {
|
||||||
sessionToken = "";
|
sessionToken = "";
|
||||||
|
clearInterval(refreshTimer);
|
||||||
|
refreshTimer = null;
|
||||||
sessionStorage.removeItem("domovoy.creator.session");
|
sessionStorage.removeItem("domovoy.creator.session");
|
||||||
consoleView.hidden = true;
|
consoleView.hidden = true;
|
||||||
loginView.hidden = false;
|
loginView.hidden = false;
|
||||||
@@ -128,7 +216,7 @@ loginForm.addEventListener("submit", async (event) => {
|
|||||||
byId("creator-password").value = "";
|
byId("creator-password").value = "";
|
||||||
await showConsole();
|
await showConsole();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
loginError.textContent = error.message === "creator authentication denied" ? "Логин или пароль не принят." : error.message;
|
loginError.textContent = safeClientError(error);
|
||||||
} finally {
|
} finally {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.firstElementChild.textContent = "Открыть консоль";
|
button.firstElementChild.textContent = "Открыть консоль";
|
||||||
@@ -144,14 +232,129 @@ byId("toggle-secret").addEventListener("click", () => {
|
|||||||
|
|
||||||
contextForm.addEventListener("submit", (event) => {
|
contextForm.addEventListener("submit", (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
saveContext();
|
const context = saveContext();
|
||||||
|
rememberContextPreset(context);
|
||||||
loadDashboard();
|
loadDashboard();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for (const input of [byId("session-id"), byId("workspace-id")]) {
|
||||||
|
input.addEventListener("input", renderContextState);
|
||||||
|
}
|
||||||
|
|
||||||
|
byId("context-preset").addEventListener("change", (event) => {
|
||||||
|
const index = Number(event.target.value);
|
||||||
|
if (!Number.isInteger(index)) return;
|
||||||
|
const preset = readContextPresets()[index];
|
||||||
|
if (!preset) return;
|
||||||
|
byId("session-id").value = preset.session;
|
||||||
|
byId("workspace-id").value = preset.workspace;
|
||||||
|
renderContextState();
|
||||||
|
loadDashboard();
|
||||||
|
notify("Контекст из недавнего набора загружен.");
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const button of document.querySelectorAll("[data-copy-context]")) {
|
||||||
|
button.addEventListener("click", async () => {
|
||||||
|
const value = byId(button.dataset.copyContext).value.trim();
|
||||||
|
if (!value) {
|
||||||
|
notify("Сначала укажите идентификатор.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
notify("Идентификатор скопирован.");
|
||||||
|
} catch (_) {
|
||||||
|
notify("Не удалось скопировать идентификатор.");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const button of document.querySelectorAll("[data-copy-value], [data-use-value]")) {
|
||||||
|
button.addEventListener("click", async () => {
|
||||||
|
const source = byId(button.dataset.copyValue || button.dataset.useValue);
|
||||||
|
const value = source?.textContent.trim() || "";
|
||||||
|
if (!value || value === "—") {
|
||||||
|
notify("Сначала загрузите значение.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (button.dataset.useValue) {
|
||||||
|
const target = byId(button.dataset.targetId);
|
||||||
|
if (!target) return;
|
||||||
|
target.value = value;
|
||||||
|
document.querySelector(".advanced-context").open = true;
|
||||||
|
saveContext();
|
||||||
|
notify("ID подставлен в расширенную проверку.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
notify("ID скопирован.");
|
||||||
|
} catch (_) {
|
||||||
|
notify("Не удалось скопировать ID.");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
byId("reset-context").addEventListener("click", () => {
|
||||||
|
contextFields.forEach((id) => { byId(id).value = id === "capability-id" ? "cognitive-proposal" : ""; });
|
||||||
|
localStorage.removeItem("domovoy.creator.context");
|
||||||
|
loadDashboard();
|
||||||
|
notify("Рабочий контекст сброшен.");
|
||||||
|
});
|
||||||
|
|
||||||
|
function restoreSettings() {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(settingsStorageKey) || "{}");
|
||||||
|
uiSettings = {
|
||||||
|
density: ["comfortable", "compact"].includes(saved.density) ? saved.density : "comfortable",
|
||||||
|
refresh: ["off", "30", "60", "300"].includes(saved.refresh) ? saved.refresh : "off",
|
||||||
|
motion: saved.motion === true,
|
||||||
|
};
|
||||||
|
} catch (_) {
|
||||||
|
uiSettings = {density: "comfortable", refresh: "off", motion: false};
|
||||||
|
}
|
||||||
|
byId("setting-density").value = uiSettings.density;
|
||||||
|
byId("setting-refresh").value = uiSettings.refresh;
|
||||||
|
byId("setting-motion").checked = uiSettings.motion;
|
||||||
|
applySettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
function applySettings() {
|
||||||
|
document.documentElement.dataset.density = uiSettings.density;
|
||||||
|
document.documentElement.dataset.reducedMotion = uiSettings.motion ? "true" : "false";
|
||||||
|
clearInterval(refreshTimer);
|
||||||
|
refreshTimer = null;
|
||||||
|
if (sessionToken && uiSettings.refresh !== "off") {
|
||||||
|
refreshTimer = setInterval(() => loadDashboard(), Number(uiSettings.refresh) * 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
byId("settings-form").addEventListener("submit", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
uiSettings = {
|
||||||
|
density: byId("setting-density").value,
|
||||||
|
refresh: byId("setting-refresh").value,
|
||||||
|
motion: byId("setting-motion").checked,
|
||||||
|
};
|
||||||
|
localStorage.setItem(settingsStorageKey, JSON.stringify(uiSettings));
|
||||||
|
applySettings();
|
||||||
|
setText("settings-saved", "Сохранено только в этом браузере");
|
||||||
|
notify("Настройки кабинета сохранены.");
|
||||||
|
});
|
||||||
|
|
||||||
|
byId("reset-settings").addEventListener("click", () => {
|
||||||
|
uiSettings = {density: "comfortable", refresh: "off", motion: false};
|
||||||
|
localStorage.removeItem(settingsStorageKey);
|
||||||
|
restoreSettings();
|
||||||
|
setText("settings-saved", "Восстановлены значения по умолчанию");
|
||||||
|
notify("Настройки сброшены.");
|
||||||
|
});
|
||||||
|
|
||||||
byId("refresh-all").addEventListener("click", loadDashboard);
|
byId("refresh-all").addEventListener("click", loadDashboard);
|
||||||
byId("refresh-actions").addEventListener("click", loadActionHistory);
|
byId("refresh-actions").addEventListener("click", loadActionHistory);
|
||||||
byId("refresh-learning").addEventListener("click", loadLearning);
|
byId("refresh-learning").addEventListener("click", loadLearning);
|
||||||
byId("logout").addEventListener("click", () => endSession());
|
byId("logout").addEventListener("click", () => endSession());
|
||||||
|
byId("run-diagnostics").addEventListener("click", runDiagnostics);
|
||||||
|
|
||||||
advisoryForm.addEventListener("submit", async (event) => {
|
advisoryForm.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -185,7 +388,7 @@ advisoryForm.addEventListener("submit", async (event) => {
|
|||||||
byId("advisory-result").hidden = false;
|
byId("advisory-result").hidden = false;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setText("advisory-state", "ОШИБКА");
|
setText("advisory-state", "ОШИБКА");
|
||||||
setText("advisory-text", error.message);
|
setText("advisory-text", safeClientError(error));
|
||||||
byId("advisory-result").hidden = false;
|
byId("advisory-result").hidden = false;
|
||||||
} finally {
|
} finally {
|
||||||
byId("advisory-egress-ack").checked = false;
|
byId("advisory-egress-ack").checked = false;
|
||||||
@@ -246,6 +449,57 @@ async function loadDashboard() {
|
|||||||
setText("last-update", `Обновлено ${new Intl.DateTimeFormat("ru-RU", {hour: "2-digit", minute: "2-digit", second: "2-digit"}).format(new Date())}`);
|
setText("last-update", `Обновлено ${new Intl.DateTimeFormat("ru-RU", {hour: "2-digit", minute: "2-digit", second: "2-digit"}).format(new Date())}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function runDiagnostics() {
|
||||||
|
const list = byId("diagnostic-list");
|
||||||
|
const summary = byId("diagnostic-summary");
|
||||||
|
const checks = [
|
||||||
|
["Сессия", "identity", () => request("/api/session/current")],
|
||||||
|
["Политика совета", "advisory", () => request("/api/advisory-policy")],
|
||||||
|
["Когнитивная возможность", "capability", () => request("/api/capabilities/cognitive-proposal/health")],
|
||||||
|
["Сегодня", "today", () => request("/api/today")],
|
||||||
|
["Внимание", "attention", () => request("/api/attention")],
|
||||||
|
["Действия", "actions", () => request("/api/actions?limit=1")],
|
||||||
|
["Learning evidence", "learning", () => request("/api/learning/recent?limit=1")],
|
||||||
|
];
|
||||||
|
list.setAttribute("aria-busy", "true");
|
||||||
|
list.replaceChildren();
|
||||||
|
checks.forEach(([label, key]) => list.append(createDiagnosticItem(label, key, "loading")));
|
||||||
|
setText("diagnostic-summary", "Проверяю…");
|
||||||
|
const results = await Promise.all(checks.map(async ([label, key, run]) => {
|
||||||
|
const started = performance.now();
|
||||||
|
try {
|
||||||
|
await run();
|
||||||
|
return {label, key, state: "ok", detail: `Ответ получен · ${Math.round(performance.now() - started)} мс`};
|
||||||
|
} catch (error) {
|
||||||
|
const detail = error?.status === 400 ? "Нужны параметры рабочего контекста" : error?.status === 401 ? "Сессия истекла" : error?.status >= 500 ? "Сервис временно недоступен" : "Проверка не пройдена";
|
||||||
|
return {label, key, state: "error", detail};
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
list.replaceChildren(...results.map((result) => createDiagnosticItem(result.label, result.key, result.state, result.detail)));
|
||||||
|
list.setAttribute("aria-busy", "false");
|
||||||
|
const passed = results.filter((result) => result.state === "ok").length;
|
||||||
|
setText("diagnostic-summary", `${passed}/${results.length} проверок пройдено`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDiagnosticItem(label, key, state, detail = "Проверяю…") {
|
||||||
|
const item = document.createElement("article");
|
||||||
|
item.className = "diagnostic-item";
|
||||||
|
item.dataset.state = state;
|
||||||
|
item.dataset.check = key;
|
||||||
|
const marker = document.createElement("i");
|
||||||
|
marker.setAttribute("aria-hidden", "true");
|
||||||
|
const copy = document.createElement("div");
|
||||||
|
const title = document.createElement("strong");
|
||||||
|
title.textContent = label;
|
||||||
|
const description = document.createElement("span");
|
||||||
|
description.textContent = detail;
|
||||||
|
copy.append(title, description);
|
||||||
|
const status = document.createElement("em");
|
||||||
|
status.textContent = state === "ok" ? "OK" : state === "error" ? "ошибка" : "…";
|
||||||
|
item.append(marker, copy, status);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
async function loadLearning() {
|
async function loadLearning() {
|
||||||
const experienceList = byId("experience-list");
|
const experienceList = byId("experience-list");
|
||||||
const reflectionList = byId("reflection-list");
|
const reflectionList = byId("reflection-list");
|
||||||
@@ -272,7 +526,7 @@ async function loadLearning() {
|
|||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
const failed = document.createElement("p");
|
const failed = document.createElement("p");
|
||||||
failed.className = "register-empty activity-error";
|
failed.className = "register-empty activity-error";
|
||||||
failed.textContent = error.message;
|
failed.textContent = safeClientError(error);
|
||||||
list.append(failed);
|
list.append(failed);
|
||||||
});
|
});
|
||||||
setText("learning-count", "ОШИБКА");
|
setText("learning-count", "ОШИБКА");
|
||||||
@@ -371,7 +625,7 @@ async function loadActionHistory() {
|
|||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
const failed = document.createElement("p");
|
const failed = document.createElement("p");
|
||||||
failed.className = "register-empty activity-error";
|
failed.className = "register-empty activity-error";
|
||||||
failed.textContent = error.message;
|
failed.textContent = safeClientError(error);
|
||||||
list.append(failed);
|
list.append(failed);
|
||||||
setText("action-count", "ОШИБКА");
|
setText("action-count", "ОШИБКА");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -430,7 +684,7 @@ async function reconcileHistoryAction(actionID, button) {
|
|||||||
await loadActionHistory();
|
await loadActionHistory();
|
||||||
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
notify(error.message);
|
notify(safeClientError(error));
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = "Сверить";
|
button.textContent = "Сверить";
|
||||||
}
|
}
|
||||||
@@ -450,7 +704,7 @@ async function loadFocus(query) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
setSignal("focus", "ошибка", "error");
|
setSignal("focus", "ошибка", "error");
|
||||||
setBadge("focus", "НЕДОСТУПЕН", "bad");
|
setBadge("focus", "НЕДОСТУПЕН", "bad");
|
||||||
setText("focus-message", error.message);
|
setText("focus-message", safeClientError(error));
|
||||||
byId("connection-state").classList.add("offline");
|
byId("connection-state").classList.add("offline");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -472,7 +726,7 @@ async function loadTask(taskID, query) {
|
|||||||
currentTask = null;
|
currentTask = null;
|
||||||
setSignal("task", "отклонена", "error");
|
setSignal("task", "отклонена", "error");
|
||||||
setBadge("task", "ВНЕ ФОКУСА", "bad");
|
setBadge("task", "ВНЕ ФОКУСА", "bad");
|
||||||
setText("task-message", error.message);
|
setText("task-message", safeClientError(error));
|
||||||
updateActionReadiness();
|
updateActionReadiness();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -511,12 +765,12 @@ async function loadProspectiveRegister(selectedID) {
|
|||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
const failed = document.createElement("p");
|
const failed = document.createElement("p");
|
||||||
failed.className = "register-empty";
|
failed.className = "register-empty";
|
||||||
failed.textContent = error.message;
|
failed.textContent = safeClientError(error);
|
||||||
list.append(failed);
|
list.append(failed);
|
||||||
setText("prospective-count", "ОШИБКА");
|
setText("prospective-count", "ОШИБКА");
|
||||||
setSignal("prospective", "ошибка", "error");
|
setSignal("prospective", "ошибка", "error");
|
||||||
setBadge("prospective", "НЕДОСТУПНА", "bad");
|
setBadge("prospective", "НЕДОСТУПНА", "bad");
|
||||||
setText("prospective-message", error.message);
|
setText("prospective-message", safeClientError(error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,7 +826,7 @@ async function loadProspective(prospectiveID) {
|
|||||||
setSignal("prospective", "ошибка", "error");
|
setSignal("prospective", "ошибка", "error");
|
||||||
setBadge("prospective", "НЕДОСТУПНА", "bad");
|
setBadge("prospective", "НЕДОСТУПНА", "bad");
|
||||||
setText("prospective-state", "UNKNOWN");
|
setText("prospective-state", "UNKNOWN");
|
||||||
setText("prospective-message", error.message);
|
setText("prospective-message", safeClientError(error));
|
||||||
updateActionReadiness();
|
updateActionReadiness();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -594,7 +848,7 @@ async function loadCapability(capabilityID) {
|
|||||||
setSignal("capability", "ошибка", "error");
|
setSignal("capability", "ошибка", "error");
|
||||||
setBadge("capability", "НЕДОСТУПНА", "bad");
|
setBadge("capability", "НЕДОСТУПНА", "bad");
|
||||||
setText("capability-state", "UNKNOWN");
|
setText("capability-state", "UNKNOWN");
|
||||||
setText("capability-reason", error.message);
|
setText("capability-reason", safeClientError(error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -700,7 +954,7 @@ byId("confirm-notification").addEventListener("click", async () => {
|
|||||||
await loadActionHistory();
|
await loadActionHistory();
|
||||||
notify(result.State === "SUCCEEDED" ? "Receiver принял уведомление." : "Исход отправки требует сверки.");
|
notify(result.State === "SUCCEEDED" ? "Receiver принял уведомление." : "Исход отправки требует сверки.");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setText("notification-confirmation-error", error.message);
|
setText("notification-confirmation-error", safeClientError(error));
|
||||||
} finally {
|
} finally {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = "Подтверждаю отправку";
|
button.textContent = "Подтверждаю отправку";
|
||||||
@@ -730,7 +984,7 @@ byId("confirm-satisfaction").addEventListener("click", async () => {
|
|||||||
notify(result.State === "SUCCEEDED" ? "Исполнение зафиксировано через Commit." : "Исход требует проверки.");
|
notify(result.State === "SUCCEEDED" ? "Исполнение зафиксировано через Commit." : "Исход требует проверки.");
|
||||||
await loadProspectiveRegister(command.ProspectiveItemID);
|
await loadProspectiveRegister(command.ProspectiveItemID);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setText("confirmation-error", error.message);
|
setText("confirmation-error", safeClientError(error));
|
||||||
} finally {
|
} finally {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = "Подтверждаю переход";
|
button.textContent = "Подтверждаю переход";
|
||||||
@@ -764,7 +1018,7 @@ byId("reconcile-action").addEventListener("click", async () => {
|
|||||||
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
|
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
|
||||||
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
notify(error.message);
|
notify(safeClientError(error));
|
||||||
} finally {
|
} finally {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = "Проверить исход";
|
button.textContent = "Проверить исход";
|
||||||
|
|||||||
@@ -25,38 +25,70 @@
|
|||||||
|
|
||||||
<section id="chat-view" class="chat-view" hidden>
|
<section id="chat-view" class="chat-view" hidden>
|
||||||
<header class="chat-header">
|
<header class="chat-header">
|
||||||
<a href="/chat" aria-label="Домовой">Домовой</a>
|
<a href="/" aria-label="Домовой">Домовой</a>
|
||||||
<nav class="human-nav" aria-label="Разделы Домового">
|
<button id="cognitive-status" class="cognitive-status" data-state="checking" type="button" role="status" aria-live="polite" title="Проверить канал ещё раз">проверяю канал мышления</button>
|
||||||
<button class="nav-tab active" data-tab="chat-panel" type="button">Чат</button>
|
<a id="cognitive-console-link" class="cognitive-console-link" href="/admin" hidden>настроить в консоли</a>
|
||||||
<button class="nav-tab" data-tab="today-panel" type="button">Сегодня</button>
|
<div class="build-meta" aria-label="Версия и время обновления">
|
||||||
<button class="nav-tab" data-tab="history-panel" type="button">История</button>
|
<span>версия __ASSISTANT_BUILD_REVISION__</span>
|
||||||
<a href="/" class="operator-link">Оператор</a>
|
<time datetime="__ASSISTANT_BUILD_DATETIME__">обновлено __ASSISTANT_BUILD_TIME__</time>
|
||||||
</nav>
|
</div>
|
||||||
<span id="active-focus">фокус: не выбран</span>
|
<a href="/admin" class="operator-link">Консоль</a>
|
||||||
<span id="session-state">сессия активна</span>
|
|
||||||
<button id="logout" type="button" aria-label="Выйти">↗</button>
|
<button id="logout" type="button" aria-label="Выйти">↗</button>
|
||||||
</header>
|
</header>
|
||||||
<section id="chat-panel" class="surface-panel active-panel">
|
<div class="chat-layout">
|
||||||
<div id="messages" class="messages" aria-live="polite"></div>
|
<aside class="chat-side chat-left" aria-label="Навигация и текущий фокус">
|
||||||
<form id="chat-form" class="composer">
|
<div class="side-intro">
|
||||||
<textarea id="message" rows="3" maxlength="16384" placeholder="Напишите Домовому обычное сообщение..." required></textarea>
|
<p class="side-index">01 / РАЗГОВОР</p>
|
||||||
<button id="send" type="submit">Отправить</button>
|
<h1>Домовой рядом</h1>
|
||||||
</form>
|
<p>Пишите обычными словами. Настройки и сведения можно передать прямо в текущий разговор.</p>
|
||||||
</section>
|
</div>
|
||||||
<section id="today-panel" class="surface-panel attention-surface" hidden>
|
<div class="side-focus">
|
||||||
<div class="surface-heading">
|
<span>ТЕКУЩИЙ ФОКУС</span>
|
||||||
<p>Сегодня / внимание</p>
|
<strong id="active-focus">не выбран</strong>
|
||||||
<button id="refresh-today" type="button">Обновить</button>
|
</div>
|
||||||
</div>
|
<nav class="human-nav" aria-label="Разделы Домового">
|
||||||
<div id="today-list" class="attention-list"></div>
|
<button class="nav-tab active" data-tab="chat-panel" type="button"><b>01</b><span>Чат</span><small>живой разговор</small></button>
|
||||||
</section>
|
<button class="nav-tab" data-tab="today-panel" type="button"><b>02</b><span>Сегодня</span><small>что требует внимания</small></button>
|
||||||
<section id="history-panel" class="surface-panel history-surface" hidden>
|
<button class="nav-tab" data-tab="history-panel" type="button"><b>03</b><span>История</span><small>это окно разговора</small></button>
|
||||||
<div class="surface-heading">
|
</nav>
|
||||||
<p>История</p>
|
<div class="side-note"><span>СЕССИЯ</span><strong id="session-state">активна</strong><small>Сведения сохраняются в текущем разговоре.</small></div>
|
||||||
<span>Последние сообщения текущего окна</span>
|
</aside>
|
||||||
</div>
|
<main class="chat-main">
|
||||||
<div id="history-list" class="history-list"></div>
|
<section id="chat-panel" class="surface-panel active-panel">
|
||||||
</section>
|
<div id="messages" class="messages" aria-live="polite"></div>
|
||||||
|
<form id="chat-form" class="composer">
|
||||||
|
<textarea id="message" rows="3" maxlength="16384" placeholder="Напишите Домовому обычное сообщение..." required></textarea>
|
||||||
|
<button id="send" type="submit">Отправить</button>
|
||||||
|
</form>
|
||||||
|
<div class="conversation-starters" aria-label="Частые вопросы">
|
||||||
|
<span>Можно начать так:</span>
|
||||||
|
<button type="button" data-starter="Проверь локальный канал мышления">Проверь канал</button>
|
||||||
|
<button type="button" data-starter="Что сейчас доступно?">Что доступно?</button>
|
||||||
|
<button type="button" data-starter="Хочу изменить настройку локальной модели">Изменить настройку</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section id="today-panel" class="surface-panel attention-surface" hidden>
|
||||||
|
<div class="surface-heading"><p>Сегодня / внимание</p><button id="refresh-today" type="button">Обновить</button></div>
|
||||||
|
<div id="today-list" class="attention-list"></div>
|
||||||
|
</section>
|
||||||
|
<section id="history-panel" class="surface-panel history-surface" hidden>
|
||||||
|
<div class="surface-heading"><p>История</p><span>Последние сообщения текущего окна</span></div>
|
||||||
|
<div id="history-list" class="history-list"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<aside class="chat-side chat-right" aria-label="Состояние и сведения об ИИ">
|
||||||
|
<div class="side-intro"><p class="side-index">02 / ИНФОРМАЦИЯ</p><h2>Канал мышления</h2><p>Домовой видит подтверждённое состояние канала. Если основной ИИ пропал, он остаётся рядом и переходит в аварийный режим.</p></div>
|
||||||
|
<div class="ai-info-card"><span>ЧТО МОЖНО ПЕРЕДАТЬ</span><strong>Описание ИИ</strong><p>Название, назначение, ограничения или заметки о локальной модели. Не вставляйте пароли, токены и ключи.</p></div>
|
||||||
|
<form id="ai-data-form" class="ai-data-form">
|
||||||
|
<label for="ai-data">Данные для текущего разговора</label>
|
||||||
|
<textarea id="ai-data" rows="8" maxlength="12000" placeholder="Например: локальная модель нужна для коротких ответов на русском; контекст ограничен; внешняя сеть запрещена."></textarea>
|
||||||
|
<button type="submit">Передать Домовому</button>
|
||||||
|
<p id="ai-data-error" class="ai-data-error" role="alert" hidden></p>
|
||||||
|
<small>Это отправится как обычное сообщение в чат.</small>
|
||||||
|
</form>
|
||||||
|
<a class="side-console-link" href="/admin">Открыть консоль настройки <span>→</span></a>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
<script src="/assets/chat.js"></script>
|
<script src="/assets/chat.js"></script>
|
||||||
|
|||||||
@@ -6,9 +6,10 @@
|
|||||||
<meta name="color-scheme" content="dark">
|
<meta name="color-scheme" content="dark">
|
||||||
<meta name="theme-color" content="#101714">
|
<meta name="theme-color" content="#101714">
|
||||||
<title>Домовой — консоль создателя</title>
|
<title>Домовой — консоль создателя</title>
|
||||||
<link rel="stylesheet" href="/assets/console.css">
|
<link rel="stylesheet" href="/assets/console.css?v=20260821-context">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<a class="skip-link" href="#overview">К содержимому</a>
|
||||||
<div class="grain" aria-hidden="true"></div>
|
<div class="grain" aria-hidden="true"></div>
|
||||||
|
|
||||||
<main id="login-view" class="login-shell">
|
<main id="login-view" class="login-shell">
|
||||||
@@ -43,7 +44,15 @@
|
|||||||
<span><strong>Домовой</strong><small>консоль создателя</small></span>
|
<span><strong>Домовой</strong><small>консоль создателя</small></span>
|
||||||
</a>
|
</a>
|
||||||
<div class="topbar-actions">
|
<div class="topbar-actions">
|
||||||
|
<a class="chat-return-link" href="/">← Чат с Домовым</a>
|
||||||
<span id="connection-state" class="connection"><i></i>система доступна</span>
|
<span id="connection-state" class="connection"><i></i>система доступна</span>
|
||||||
|
<nav class="topbar-nav" aria-label="Разделы кабинета">
|
||||||
|
<a href="#overview">Обзор</a>
|
||||||
|
<a href="#diagnostics">Проверки</a>
|
||||||
|
<a href="#operations">Операции</a>
|
||||||
|
<a href="#learning">Опыт</a>
|
||||||
|
<a href="#settings">Настройки</a>
|
||||||
|
</nav>
|
||||||
<button id="refresh-all" class="text-button" type="button">Обновить</button>
|
<button id="refresh-all" class="text-button" type="button">Обновить</button>
|
||||||
<button id="logout" class="icon-button" type="button" aria-label="Завершить сессию" title="Выйти">↗</button>
|
<button id="logout" class="icon-button" type="button" aria-label="Завершить сессию" title="Выйти">↗</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -56,18 +65,46 @@
|
|||||||
<p class="rail-copy">Укажите рабочий контекст. Он сохраняется только в этом браузере и не даёт дополнительных полномочий.</p>
|
<p class="rail-copy">Укажите рабочий контекст. Он сохраняется только в этом браузере и не даёт дополнительных полномочий.</p>
|
||||||
</div>
|
</div>
|
||||||
<form id="context-form" class="context-form">
|
<form id="context-form" class="context-form">
|
||||||
<label for="session-id">Идентификатор сессии</label>
|
<div class="context-status-row">
|
||||||
<input id="session-id" autocomplete="off" placeholder="session-id">
|
<span class="context-status-label">ТЕКУЩИЙ КОНТЕКСТ</span>
|
||||||
<label for="workspace-id">Рабочая область</label>
|
<strong id="context-state" data-state="empty">не выбран</strong>
|
||||||
<input id="workspace-id" autocomplete="off" placeholder="workspace-id">
|
</div>
|
||||||
<label for="task-id">Задача</label>
|
<div class="context-presets">
|
||||||
<input id="task-id" autocomplete="off" placeholder="task-id">
|
<label for="context-preset">Недавние наборы</label>
|
||||||
<label for="prospective-id">Выбранное ожидание</label>
|
<select id="context-preset">
|
||||||
<input id="prospective-id" autocomplete="off" placeholder="prospective-item-id">
|
<option value="">Выберите сохранённый набор…</option>
|
||||||
<label for="capability-id">Возможность</label>
|
</select>
|
||||||
<input id="capability-id" autocomplete="off" value="cognitive-proposal">
|
<small>Сохраняются только в этом браузере.</small>
|
||||||
<button class="secondary-button" type="submit">Загрузить контекст</button>
|
</div>
|
||||||
|
<div class="context-field">
|
||||||
|
<label for="session-id">Идентификатор сессии <span>обязательно</span></label>
|
||||||
|
<div class="context-input-row"><input id="session-id" autocomplete="off" spellcheck="false" placeholder="Вставьте session-id"><button class="copy-context" data-copy-context="session-id" type="button" aria-label="Скопировать идентификатор сессии" title="Скопировать">⧉</button></div>
|
||||||
|
</div>
|
||||||
|
<div class="context-field">
|
||||||
|
<label for="workspace-id">Рабочая область <span>обязательно</span></label>
|
||||||
|
<div class="context-input-row"><input id="workspace-id" autocomplete="off" spellcheck="false" placeholder="Вставьте workspace-id"><button class="copy-context" data-copy-context="workspace-id" type="button" aria-label="Скопировать рабочую область" title="Скопировать">⧉</button></div>
|
||||||
|
</div>
|
||||||
|
<p class="context-hint">Для «Состояния» нужны только эти два значения. Задача, ожидание и возможность находятся ниже в расширенных полях.</p>
|
||||||
|
<details class="advanced-context">
|
||||||
|
<summary>Расширенные идентификаторы</summary>
|
||||||
|
<div>
|
||||||
|
<label for="task-id">Задача</label>
|
||||||
|
<input id="task-id" autocomplete="off" placeholder="task-id">
|
||||||
|
<label for="prospective-id">Выбранное ожидание</label>
|
||||||
|
<input id="prospective-id" autocomplete="off" placeholder="prospective-item-id">
|
||||||
|
<label for="capability-id">Возможность</label>
|
||||||
|
<input id="capability-id" autocomplete="off" value="cognitive-proposal">
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
<div class="context-actions"><button class="secondary-button" type="submit">Загрузить контекст</button><button id="reset-context" class="text-button" type="button">Сбросить</button></div>
|
||||||
</form>
|
</form>
|
||||||
|
<nav class="section-nav" aria-label="Навигация по кабинету">
|
||||||
|
<a class="section-nav-link active" aria-current="location" href="#overview"><span>01</span><b>Состояние</b><small>фокус и сигналы</small></a>
|
||||||
|
<a class="section-nav-link" href="#diagnostics"><span>02</span><b>Проверки</b><small>доступность и границы</small></a>
|
||||||
|
<a class="section-nav-link" href="#operations"><span>03</span><b>Операции</b><small>ожидания и действия</small></a>
|
||||||
|
<a class="section-nav-link" href="#learning"><span>04</span><b>Опыт</b><small>reflection и навыки</small></a>
|
||||||
|
<a class="section-nav-link" href="#settings"><span>05</span><b>Настройки</b><small>интерфейс и обновление</small></a>
|
||||||
|
</nav>
|
||||||
<div class="session-stamp">
|
<div class="session-stamp">
|
||||||
<span>ACTOR</span>
|
<span>ACTOR</span>
|
||||||
<strong id="session-actor">—</strong>
|
<strong id="session-actor">—</strong>
|
||||||
@@ -77,7 +114,7 @@
|
|||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main class="workspace">
|
<main class="workspace">
|
||||||
<section class="workspace-head">
|
<section id="overview" class="workspace-head" data-page="overview">
|
||||||
<div>
|
<div>
|
||||||
<p class="eyebrow">операционная картина</p>
|
<p class="eyebrow">операционная картина</p>
|
||||||
<h1>Состояние сейчас</h1>
|
<h1>Состояние сейчас</h1>
|
||||||
@@ -85,14 +122,28 @@
|
|||||||
<p id="last-update" class="last-update">Данные ещё не запрошены</p>
|
<p id="last-update" class="last-update">Данные ещё не запрошены</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="signal-strip" aria-label="Сводка состояния">
|
<section class="signal-strip" aria-label="Сводка состояния" data-page="overview">
|
||||||
<div><span>ФОКУС</span><strong id="focus-signal" data-state="idle">ожидает</strong></div>
|
<div><span>ФОКУС</span><strong id="focus-signal" data-state="idle">ожидает</strong></div>
|
||||||
<div><span>ЗАДАЧА</span><strong id="task-signal" data-state="idle">ожидает</strong></div>
|
<div><span>ЗАДАЧА</span><strong id="task-signal" data-state="idle">ожидает</strong></div>
|
||||||
<div><span>CONTINUITY</span><strong id="prospective-signal" data-state="idle">ожидает</strong></div>
|
<div><span>CONTINUITY</span><strong id="prospective-signal" data-state="idle">ожидает</strong></div>
|
||||||
<div><span>ВОЗМОЖНОСТЬ</span><strong id="capability-signal" data-state="idle">ожидает</strong></div>
|
<div><span>ВОЗМОЖНОСТЬ</span><strong id="capability-signal" data-state="idle">ожидает</strong></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="advisor-panel" aria-labelledby="advisor-title">
|
<section id="diagnostics" class="diagnostics-panel" aria-labelledby="diagnostics-title" data-page="diagnostics">
|
||||||
|
<header class="panel-heading">
|
||||||
|
<div><p>Проверяемая система</p><h2 id="diagnostics-title">Диагностика кабинета</h2></div>
|
||||||
|
<div class="panel-heading-tools"><span id="diagnostic-summary">Проверка ещё не запускалась</span><button id="run-diagnostics" class="secondary-button compact-button" type="button">Проверить всё</button></div>
|
||||||
|
</header>
|
||||||
|
<div class="diagnostic-intro">
|
||||||
|
<span class="diagnostic-pulse" aria-hidden="true"></span>
|
||||||
|
<p>Здесь видны только ответы текущей авторизованной сессии. Проверка не меняет данные и помогает отличить отсутствие контекста от недоступности сервиса.</p>
|
||||||
|
</div>
|
||||||
|
<div id="diagnostic-list" class="diagnostic-list" aria-live="polite" aria-busy="false">
|
||||||
|
<p class="register-empty">Нажмите «Проверить всё», чтобы получить актуальный снимок.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="advisor-panel" aria-labelledby="advisor-title" data-page="diagnostics">
|
||||||
<div class="advisor-intro">
|
<div class="advisor-intro">
|
||||||
<p>COGNITIVE / ADVISORY V1</p>
|
<p>COGNITIVE / ADVISORY V1</p>
|
||||||
<h2 id="advisor-title">Спросить Домового</h2>
|
<h2 id="advisor-title">Спросить Домового</h2>
|
||||||
@@ -120,7 +171,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="register-panel" aria-labelledby="register-title">
|
<section id="operations" class="register-panel" aria-labelledby="register-title" data-page="operations">
|
||||||
<header>
|
<header>
|
||||||
<div><p>Continuity / ближайшие</p><h2 id="register-title">Реестр ожиданий</h2></div>
|
<div><p>Continuity / ближайшие</p><h2 id="register-title">Реестр ожиданий</h2></div>
|
||||||
<span id="prospective-count">0 ЗАПИСЕЙ</span>
|
<span id="prospective-count">0 ЗАПИСЕЙ</span>
|
||||||
@@ -130,7 +181,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="activity-panel" aria-labelledby="activity-title">
|
<section class="activity-panel" aria-labelledby="activity-title" data-page="operations">
|
||||||
<header>
|
<header>
|
||||||
<div><p>Commit / владелец</p><h2 id="activity-title">Журнал действий</h2></div>
|
<div><p>Commit / владелец</p><h2 id="activity-title">Журнал действий</h2></div>
|
||||||
<div class="activity-tools">
|
<div class="activity-tools">
|
||||||
@@ -143,7 +194,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="learning-panel" aria-labelledby="learning-title">
|
<section id="learning" class="learning-panel" aria-labelledby="learning-title" data-page="learning">
|
||||||
<header>
|
<header>
|
||||||
<div><p>Learning / evidence</p><h2 id="learning-title">Опыт и reflection</h2></div>
|
<div><p>Learning / evidence</p><h2 id="learning-title">Опыт и reflection</h2></div>
|
||||||
<div class="activity-tools">
|
<div class="activity-tools">
|
||||||
@@ -167,7 +218,20 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="data-grid">
|
<section id="settings" class="settings-panel" aria-labelledby="settings-title" data-page="settings">
|
||||||
|
<header class="panel-heading">
|
||||||
|
<div><p>Локальные предпочтения</p><h2 id="settings-title">Настройки рабочего кабинета</h2></div>
|
||||||
|
<span id="settings-saved" class="settings-saved">Сохраняются в этом браузере</span>
|
||||||
|
</header>
|
||||||
|
<form id="settings-form" class="settings-grid">
|
||||||
|
<label class="setting-field"><span>Плотность данных</span><small>Выберите, сколько строк помещается на экране.</small><select id="setting-density"><option value="comfortable">Комфортная</option><option value="compact">Компактная</option></select></label>
|
||||||
|
<label class="setting-field"><span>Автообновление</span><small>Повторная проверка состояния без изменения данных.</small><select id="setting-refresh"><option value="off">Выключено</option><option value="30">Каждые 30 секунд</option><option value="60">Каждую минуту</option><option value="300">Каждые 5 минут</option></select></label>
|
||||||
|
<label class="setting-check"><input id="setting-motion" type="checkbox"><span><b>Сократить анимацию</b><small>Оставить спокойный режим для длительной работы.</small></span></label>
|
||||||
|
<div class="settings-actions"><button id="save-settings" class="primary-button compact-button" type="submit"><span>Сохранить настройки</span><span aria-hidden="true">→</span></button><button id="reset-settings" class="text-button" type="button">Сбросить</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="data-grid" data-page="overview">
|
||||||
<article class="data-card focus-card">
|
<article class="data-card focus-card">
|
||||||
<header><span class="card-number">01</span><div><p>Situation</p><h2>Активный фокус</h2></div><span id="focus-badge" class="status-badge neutral">НЕ ЗАГРУЖЕН</span></header>
|
<header><span class="card-number">01</span><div><p>Situation</p><h2>Активный фокус</h2></div><span id="focus-badge" class="status-badge neutral">НЕ ЗАГРУЖЕН</span></header>
|
||||||
<dl>
|
<dl>
|
||||||
@@ -188,6 +252,7 @@
|
|||||||
<div><dt>Ревизия</dt><dd id="task-revision">—</dd></div>
|
<div><dt>Ревизия</dt><dd id="task-revision">—</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
<p id="task-message" class="card-message">Укажите задачу для проверки относительно активного фокуса.</p>
|
<p id="task-message" class="card-message">Укажите задачу для проверки относительно активного фокуса.</p>
|
||||||
|
<div class="id-actions"><button class="id-action" data-use-value="task-value" data-target-id="task-id" type="button">Использовать ID задачи</button><button class="id-action icon-id-action" data-copy-value="task-value" type="button" aria-label="Скопировать ID задачи" title="Скопировать ID">⧉</button></div>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
<article class="data-card prospective-card">
|
<article class="data-card prospective-card">
|
||||||
@@ -205,6 +270,7 @@
|
|||||||
<div><dt>Ревизия</dt><dd id="prospective-revision">—</dd></div>
|
<div><dt>Ревизия</dt><dd id="prospective-revision">—</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
<p id="prospective-message" class="card-message">Укажите идентификатор ProspectiveItem для проверки владельца и состояния.</p>
|
<p id="prospective-message" class="card-message">Укажите идентификатор ProspectiveItem для проверки владельца и состояния.</p>
|
||||||
|
<div class="id-actions"><button class="id-action" data-use-value="prospective-value" data-target-id="prospective-id" type="button">Использовать ID ожидания</button><button class="id-action icon-id-action" data-copy-value="prospective-value" type="button" aria-label="Скопировать ID ожидания" title="Скопировать ID">⧉</button></div>
|
||||||
<section class="commit-zone" aria-labelledby="commit-zone-title">
|
<section class="commit-zone" aria-labelledby="commit-zone-title">
|
||||||
<div class="commit-zone-copy">
|
<div class="commit-zone-copy">
|
||||||
<p>Commit / контролируемый переход</p>
|
<p>Commit / контролируемый переход</p>
|
||||||
@@ -240,6 +306,7 @@
|
|||||||
<div><dt>Ревизия</dt><dd id="capability-revision">—</dd></div>
|
<div><dt>Ревизия</dt><dd id="capability-revision">—</dd></div>
|
||||||
<div><dt>Наблюдалось</dt><dd id="capability-observed">—</dd></div>
|
<div><dt>Наблюдалось</dt><dd id="capability-observed">—</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
|
<div class="id-actions"><button class="id-action" data-use-value="capability-value" data-target-id="capability-id" type="button">Использовать ID возможности</button><button class="id-action icon-id-action" data-copy-value="capability-value" type="button" aria-label="Скопировать ID возможности" title="Скопировать ID">⧉</button></div>
|
||||||
</article>
|
</article>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
@@ -286,6 +353,6 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
|
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
|
||||||
<script src="/assets/console.js" defer></script>
|
<script src="/assets/console.js?v=20260821-context" defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ type OperationalState string
|
|||||||
type EvaluationResult string
|
type EvaluationResult string
|
||||||
type EvaluationID ids.ID
|
type EvaluationID ids.ID
|
||||||
type PerformanceEvidenceID ids.ID
|
type PerformanceEvidenceID ids.ID
|
||||||
|
type BillingMode string
|
||||||
|
type AuthMode string
|
||||||
|
type SelectionObjective string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
QualificationDiscovered QualificationState = "DISCOVERED"
|
QualificationDiscovered QualificationState = "DISCOVERED"
|
||||||
@@ -52,6 +55,24 @@ const (
|
|||||||
EvaluationUnknown EvaluationResult = "UNKNOWN"
|
EvaluationUnknown EvaluationResult = "UNKNOWN"
|
||||||
EvaluationSupported EvaluationResult = "SUPPORTED"
|
EvaluationSupported EvaluationResult = "SUPPORTED"
|
||||||
EvaluationUnsupported EvaluationResult = "UNSUPPORTED"
|
EvaluationUnsupported EvaluationResult = "UNSUPPORTED"
|
||||||
|
|
||||||
|
BillingUnknown BillingMode = "UNKNOWN"
|
||||||
|
BillingFree BillingMode = "FREE"
|
||||||
|
BillingPerInput BillingMode = "PER_INPUT_UNIT"
|
||||||
|
BillingPerOutput BillingMode = "PER_OUTPUT_UNIT"
|
||||||
|
BillingPerRequest BillingMode = "PER_REQUEST"
|
||||||
|
|
||||||
|
AuthNone AuthMode = "NONE"
|
||||||
|
AuthKey AuthMode = "API" + "_KEY"
|
||||||
|
AuthBearer AuthMode = "BEARER"
|
||||||
|
AuthUsernamePassword AuthMode = "USERNAME_PASSWORD"
|
||||||
|
AuthOAuth AuthMode = "OAUTH"
|
||||||
|
AuthSecretFile AuthMode = "SECRET_FILE"
|
||||||
|
|
||||||
|
SelectionBalanced SelectionObjective = "BALANCED"
|
||||||
|
SelectionQuality SelectionObjective = "QUALITY"
|
||||||
|
SelectionSpeed SelectionObjective = "SPEED"
|
||||||
|
SelectionEconomy SelectionObjective = "ECONOMY"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ProviderInstance contains only opaque references to endpoint and credentials.
|
// ProviderInstance contains only opaque references to endpoint and credentials.
|
||||||
@@ -66,20 +87,26 @@ type ProviderInstance struct {
|
|||||||
Qualification QualificationState
|
Qualification QualificationState
|
||||||
Health HealthState
|
Health HealthState
|
||||||
ObservedAtUnixMillis int64
|
ObservedAtUnixMillis int64
|
||||||
|
BillingMode BillingMode
|
||||||
|
AuthMode AuthMode
|
||||||
|
InputCostMicros *int64
|
||||||
|
OutputCostMicros *int64
|
||||||
|
RequestCostMicros *int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type ModelDescriptor struct {
|
type ModelDescriptor struct {
|
||||||
ID ModelDescriptorID
|
ID ModelDescriptorID
|
||||||
Revision int64
|
Revision int64
|
||||||
ProviderInstanceID ProviderInstanceID
|
ProviderInstanceID ProviderInstanceID
|
||||||
ProviderModelID ProviderModelID
|
ProviderModelID ProviderModelID
|
||||||
Fingerprint ModelFingerprint
|
Fingerprint ModelFingerprint
|
||||||
MaxContextBytes int64
|
MaxContextBytes int64
|
||||||
Modalities []ModelModality
|
Modalities []ModelModality
|
||||||
Capabilities []ModelCapability
|
Capabilities []ModelCapability
|
||||||
Qualification QualificationState
|
Qualification QualificationState
|
||||||
Health HealthState
|
Health HealthState
|
||||||
ObservedAtUnixMillis int64
|
ObservedAtUnixMillis int64
|
||||||
|
IntelligenceScoreMillis *int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProviderHealthObservation struct {
|
type ProviderHealthObservation struct {
|
||||||
@@ -125,6 +152,8 @@ type CognitiveRequirement struct {
|
|||||||
InputBytes int64
|
InputBytes int64
|
||||||
MaxOutputBytes int64
|
MaxOutputBytes int64
|
||||||
ExcludedBindingIDs []CapabilityBindingID
|
ExcludedBindingIDs []CapabilityBindingID
|
||||||
|
Objective SelectionObjective
|
||||||
|
MaxCostMicros *int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolvedCognitiveBinding is a provider-neutral invocation snapshot selected
|
// ResolvedCognitiveBinding is a provider-neutral invocation snapshot selected
|
||||||
@@ -206,6 +235,23 @@ type CognitiveCanaryPromotion struct {
|
|||||||
Evaluation EvaluatedCapability
|
Evaluation EvaluatedCapability
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CognitiveActivationPromotionRequest struct {
|
||||||
|
PromotionID ids.ID
|
||||||
|
RequestedByPrincipalID identity.PrincipalID
|
||||||
|
CapabilityID CapabilityID
|
||||||
|
BindingID CapabilityBindingID
|
||||||
|
ExpectedBindingRevision int64
|
||||||
|
EvaluationID EvaluationID
|
||||||
|
ObservedAtUnixMillis int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type CognitiveActivationPromotion struct {
|
||||||
|
PromotionID ids.ID
|
||||||
|
ExpectedBindingRevision int64
|
||||||
|
Binding CognitiveBinding
|
||||||
|
Evaluation EvaluatedCapability
|
||||||
|
}
|
||||||
|
|
||||||
// CognitiveDiscoverySnapshot is provider-neutral observed inventory submitted
|
// CognitiveDiscoverySnapshot is provider-neutral observed inventory submitted
|
||||||
// to the Capability owner. The owner assigns immutable revisions and always
|
// to the Capability owner. The owner assigns immutable revisions and always
|
||||||
// registers discovered bindings as DISCOVERED/INACTIVE.
|
// registers discovered bindings as DISCOVERED/INACTIVE.
|
||||||
@@ -222,18 +268,24 @@ type CognitiveDiscoverySnapshot struct {
|
|||||||
Health HealthState
|
Health HealthState
|
||||||
FailureClass CognitiveFailureType
|
FailureClass CognitiveFailureType
|
||||||
ObservedAtUnixMillis int64
|
ObservedAtUnixMillis int64
|
||||||
|
BillingMode BillingMode
|
||||||
|
AuthMode AuthMode
|
||||||
|
InputCostMicros *int64
|
||||||
|
OutputCostMicros *int64
|
||||||
|
RequestCostMicros *int64
|
||||||
Models []DiscoveredModelSnapshot
|
Models []DiscoveredModelSnapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
type DiscoveredModelSnapshot struct {
|
type DiscoveredModelSnapshot struct {
|
||||||
ProviderModelID ProviderModelID
|
ProviderModelID ProviderModelID
|
||||||
Fingerprint ModelFingerprint
|
Fingerprint ModelFingerprint
|
||||||
MaxContextBytes int64
|
MaxContextBytes int64
|
||||||
Modalities []ModelModality
|
Modalities []ModelModality
|
||||||
Capabilities []ModelCapability
|
Capabilities []ModelCapability
|
||||||
Installed OperationalState
|
Installed OperationalState
|
||||||
Loaded OperationalState
|
Loaded OperationalState
|
||||||
Invokable OperationalState
|
Invokable OperationalState
|
||||||
|
IntelligenceScoreMillis *int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type CognitiveUsageObservation struct {
|
type CognitiveUsageObservation struct {
|
||||||
|
|||||||
@@ -79,6 +79,18 @@ type GatewayAdvisoryRequest struct {
|
|||||||
MaxOutputBytes int
|
MaxOutputBytes int
|
||||||
DataPolicy capability.DataPolicy
|
DataPolicy capability.DataPolicy
|
||||||
EgressAcknowledged bool
|
EgressAcknowledged bool
|
||||||
|
Meaning TaskMeaning
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskMeaning is the trusted semantic summary produced by Core. It is not a
|
||||||
|
// browser-controlled provider selector; the Capability owner still resolves
|
||||||
|
// the actual binding.
|
||||||
|
type TaskMeaning struct {
|
||||||
|
SpeechAct string
|
||||||
|
CapabilityKind capability.CapabilityKind
|
||||||
|
CapabilityHints []capability.CapabilityKind
|
||||||
|
RequestedOutcome string
|
||||||
|
ConfidenceMillis int64
|
||||||
}
|
}
|
||||||
|
|
||||||
type GatewayAdvisoryPolicyRequest struct {
|
type GatewayAdvisoryPolicyRequest struct {
|
||||||
@@ -97,6 +109,54 @@ type ProviderUsage struct {
|
|||||||
OutputUnits int64
|
OutputUnits int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type InterpretationApplicability string
|
||||||
|
|
||||||
|
const (
|
||||||
|
InterpretationApplicable InterpretationApplicability = "APPLICABLE"
|
||||||
|
InterpretationLowConfidence InterpretationApplicability = "LOW_CONFIDENCE"
|
||||||
|
InterpretationMixedIntent InterpretationApplicability = "MIXED_INTENT"
|
||||||
|
InterpretationNeedsBroader InterpretationApplicability = "NEEDS_BROADER_INTERPRETATION"
|
||||||
|
InterpretationClarificationRequired InterpretationApplicability = "CLARIFICATION_REQUIRED"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GatewayInterpretationRequest struct {
|
||||||
|
Version ContractVersion
|
||||||
|
RequestID RequestID
|
||||||
|
ActorID identity.ActorID
|
||||||
|
PrincipalID identity.PrincipalID
|
||||||
|
ScopeID authority.ScopeID
|
||||||
|
Message string
|
||||||
|
Locale string
|
||||||
|
MaxOutputBytes int
|
||||||
|
DataPolicy capability.DataPolicy
|
||||||
|
DeterministicSpeechAct string
|
||||||
|
DeterministicSecondary string
|
||||||
|
DeterministicConfidence int64
|
||||||
|
DeterministicApplicability InterpretationApplicability
|
||||||
|
RequestedOutcome string
|
||||||
|
ProjectNames []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type GatewayInterpretationCandidate struct {
|
||||||
|
PrimarySpeechAct string `json:"primary_speech_act"`
|
||||||
|
SecondarySpeechAct string `json:"secondary_speech_act,omitempty"`
|
||||||
|
ConfidenceMillis int64 `json:"confidence_millis"`
|
||||||
|
Applicability InterpretationApplicability `json:"applicability"`
|
||||||
|
RequestedOutcome string `json:"requested_outcome,omitempty"`
|
||||||
|
NeedsCognition bool `json:"needs_cognition"`
|
||||||
|
Clarification string `json:"clarification"`
|
||||||
|
SelectionReason string `json:"selection_reason,omitempty"`
|
||||||
|
CapabilityHints []capability.CapabilityKind `json:"capability_hints,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GatewayInterpretationResponse struct {
|
||||||
|
Version ContractVersion
|
||||||
|
RequestID RequestID
|
||||||
|
Candidate GatewayInterpretationCandidate
|
||||||
|
FinishReason FinishReason
|
||||||
|
Usage *ProviderUsage
|
||||||
|
}
|
||||||
|
|
||||||
type AdvisoryResponse struct {
|
type AdvisoryResponse struct {
|
||||||
Version ContractVersion
|
Version ContractVersion
|
||||||
RequestID RequestID
|
RequestID RequestID
|
||||||
|
|||||||
@@ -17,40 +17,54 @@ type ConversationState string
|
|||||||
type InterpretationState string
|
type InterpretationState string
|
||||||
type InteractionRelationKind string
|
type InteractionRelationKind string
|
||||||
type InterpretationID string
|
type InterpretationID string
|
||||||
|
type SemanticCandidateID string
|
||||||
type ProjectReferenceID string
|
type ProjectReferenceID string
|
||||||
type ProjectReferenceRole string
|
type ProjectReferenceRole string
|
||||||
type ClarificationState string
|
type ClarificationState string
|
||||||
|
type SemanticApplicability string
|
||||||
|
type SemanticCandidateSource string
|
||||||
|
type SemanticCandidateSelectionState string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ChannelWebChat Channel = "WEB_CHAT"
|
ChannelWebChat Channel = "WEB_CHAT"
|
||||||
ConversationOpen ConversationState = "OPEN"
|
ConversationOpen ConversationState = "OPEN"
|
||||||
ConversationArchived ConversationState = "ARCHIVED"
|
ConversationArchived ConversationState = "ARCHIVED"
|
||||||
SpeechActDirective SpeechAct = "DIRECTIVE"
|
SpeechActDirective SpeechAct = "DIRECTIVE"
|
||||||
SpeechActAssertion SpeechAct = "ASSERTION"
|
SpeechActAssertion SpeechAct = "ASSERTION"
|
||||||
SpeechActDecision SpeechAct = "DECISION"
|
SpeechActDecision SpeechAct = "DECISION"
|
||||||
SpeechActPreference SpeechAct = "PREFERENCE"
|
SpeechActPreference SpeechAct = "PREFERENCE"
|
||||||
SpeechActQuestion SpeechAct = "QUESTION"
|
SpeechActQuestion SpeechAct = "QUESTION"
|
||||||
SpeechActHypothesis SpeechAct = "HYPOTHESIS"
|
SpeechActHypothesis SpeechAct = "HYPOTHESIS"
|
||||||
SpeechActCorrection SpeechAct = "CORRECTION"
|
SpeechActCorrection SpeechAct = "CORRECTION"
|
||||||
SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE"
|
SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE"
|
||||||
SpeechActConfirmation SpeechAct = "CONFIRMATION"
|
SpeechActConfirmation SpeechAct = "CONFIRMATION"
|
||||||
SpeechActRejection SpeechAct = "REJECTION"
|
SpeechActRejection SpeechAct = "REJECTION"
|
||||||
SpeechActCancellation SpeechAct = "CANCELLATION"
|
SpeechActCancellation SpeechAct = "CANCELLATION"
|
||||||
SpeechActConversational SpeechAct = "CONVERSATIONAL"
|
SpeechActConversational SpeechAct = "CONVERSATIONAL"
|
||||||
SpeechActUnknown SpeechAct = "UNKNOWN"
|
SpeechActUnknown SpeechAct = "UNKNOWN"
|
||||||
InterpretationRecorded InterpretationState = "RECORDED"
|
InterpretationRecorded InterpretationState = "RECORDED"
|
||||||
InterpretationInterpreted InterpretationState = "INTERPRETED"
|
InterpretationInterpreted InterpretationState = "INTERPRETED"
|
||||||
RelationCorrects InteractionRelationKind = "CORRECTS"
|
RelationCorrects InteractionRelationKind = "CORRECTS"
|
||||||
RelationRespondsTo InteractionRelationKind = "RESPONDS_TO"
|
RelationRespondsTo InteractionRelationKind = "RESPONDS_TO"
|
||||||
RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION"
|
RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION"
|
||||||
RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK"
|
RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK"
|
||||||
RelationSupersedes InteractionRelationKind = "SUPERSEDES"
|
RelationSupersedes InteractionRelationKind = "SUPERSEDES"
|
||||||
RelationClarifies InteractionRelationKind = "CLARIFIES"
|
RelationClarifies InteractionRelationKind = "CLARIFIES"
|
||||||
ProjectRolePrimary ProjectReferenceRole = "PRIMARY"
|
ProjectRolePrimary ProjectReferenceRole = "PRIMARY"
|
||||||
ProjectRoleRelated ProjectReferenceRole = "RELATED"
|
ProjectRoleRelated ProjectReferenceRole = "RELATED"
|
||||||
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
|
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
|
||||||
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
|
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
|
||||||
ClarificationRequired ClarificationState = "REQUIRED"
|
ClarificationRequired ClarificationState = "REQUIRED"
|
||||||
|
SemanticApplicable SemanticApplicability = "APPLICABLE"
|
||||||
|
SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE"
|
||||||
|
SemanticMixedIntent SemanticApplicability = "MIXED_INTENT"
|
||||||
|
SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION"
|
||||||
|
SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED"
|
||||||
|
CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2"
|
||||||
|
CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1"
|
||||||
|
CandidateSelected SemanticCandidateSelectionState = "SELECTED"
|
||||||
|
CandidateObserved SemanticCandidateSelectionState = "OBSERVED"
|
||||||
|
CandidateRejected SemanticCandidateSelectionState = "REJECTED"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Conversation struct {
|
type Conversation struct {
|
||||||
@@ -94,14 +108,35 @@ type UtteranceInterpretation struct {
|
|||||||
ID InterpretationID
|
ID InterpretationID
|
||||||
UtteranceID HumanUtteranceID
|
UtteranceID HumanUtteranceID
|
||||||
SpeechAct SpeechAct
|
SpeechAct SpeechAct
|
||||||
|
SecondarySpeechAct SpeechAct
|
||||||
ConfidenceMillis int64
|
ConfidenceMillis int64
|
||||||
Source string
|
Source string
|
||||||
AssertionVerification string
|
AssertionVerification string
|
||||||
RequestedOutcome string
|
RequestedOutcome string
|
||||||
Clarification ClarificationState
|
Clarification ClarificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
Applicability SemanticApplicability
|
||||||
|
SelectionReason string
|
||||||
RecordedAtUnixMillis int64
|
RecordedAtUnixMillis int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SemanticCandidate struct {
|
||||||
|
ID SemanticCandidateID
|
||||||
|
UtteranceID HumanUtteranceID
|
||||||
|
Source SemanticCandidateSource
|
||||||
|
SelectionState SemanticCandidateSelectionState
|
||||||
|
PrimarySpeechAct SpeechAct
|
||||||
|
SecondarySpeechAct SpeechAct
|
||||||
|
ConfidenceMillis int64
|
||||||
|
Applicability SemanticApplicability
|
||||||
|
RequestedOutcome string
|
||||||
|
Clarification ClarificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
SelectionReason string
|
||||||
|
CapabilityHints []string
|
||||||
|
RecordedAtUnixMillis int64
|
||||||
|
}
|
||||||
|
|
||||||
type ProjectReference struct {
|
type ProjectReference struct {
|
||||||
ID ProjectReferenceID
|
ID ProjectReferenceID
|
||||||
UtteranceID HumanUtteranceID
|
UtteranceID HumanUtteranceID
|
||||||
@@ -121,22 +156,25 @@ type ChatMessageRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ChatMessageResponse struct {
|
type ChatMessageResponse struct {
|
||||||
ConversationID ConversationID
|
ConversationID ConversationID
|
||||||
UtteranceID HumanUtteranceID
|
UtteranceID HumanUtteranceID
|
||||||
OriginalIntentID OriginalHumanIntentID
|
OriginalIntentID OriginalHumanIntentID
|
||||||
SpeechAct SpeechAct
|
SpeechAct SpeechAct
|
||||||
InterpretationState InterpretationState
|
InterpretationState InterpretationState
|
||||||
NeedsCognition bool
|
NeedsCognition bool
|
||||||
FallbackText string
|
FallbackText string
|
||||||
ActiveProjectName string
|
ActiveProjectName string
|
||||||
ProjectProvenance situation.ProjectResolutionProvenance
|
ProjectProvenance situation.ProjectResolutionProvenance
|
||||||
Clarification ClarificationState
|
Clarification ClarificationState
|
||||||
WorkPlanned bool
|
WorkPlanned bool
|
||||||
PlanningReply string
|
PlanningReply string
|
||||||
CapabilityStatus capability.CapabilityResolutionStatus
|
CapabilityStatus capability.CapabilityResolutionStatus
|
||||||
CapabilityKind capability.CapabilityKind
|
CapabilityKind capability.CapabilityKind
|
||||||
CapabilityGapID capability.CapabilityGapID
|
CapabilityHints []capability.CapabilityKind
|
||||||
DelegationID string
|
RequestedOutcome string
|
||||||
DelegationState string
|
InterpretationConfidenceMillis int64
|
||||||
Reminder *continuity.ProspectiveItem
|
CapabilityGapID capability.CapabilityGapID
|
||||||
|
DelegationID string
|
||||||
|
DelegationState string
|
||||||
|
Reminder *continuity.ProspectiveItem
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -300,7 +300,11 @@ type PlanningInput struct {
|
|||||||
ProjectProvenance ProjectProvenanceRef
|
ProjectProvenance ProjectProvenanceRef
|
||||||
Message string
|
Message string
|
||||||
SpeechAct SpeechActRef
|
SpeechAct SpeechActRef
|
||||||
|
SecondarySpeechAct SpeechActRef
|
||||||
|
CapabilityHints []capability.CapabilityKind
|
||||||
AssertionVerification epistemics.VerificationState
|
AssertionVerification epistemics.VerificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
RequiresClarification bool
|
||||||
ReceivedAtUnixMillis int64
|
ReceivedAtUnixMillis int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
BEGIN;
|
||||||
|
|
||||||
|
SET ROLE interaction_role;
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD COLUMN IF NOT EXISTS secondary_speech_act TEXT NOT NULL DEFAULT 'UNKNOWN',
|
||||||
|
ADD COLUMN IF NOT EXISTS needs_cognition BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
ADD COLUMN IF NOT EXISTS applicability TEXT NOT NULL DEFAULT 'APPLICABLE',
|
||||||
|
ADD COLUMN IF NOT EXISTS selection_reason TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations DROP CONSTRAINT IF EXISTS utterance_interpretations_secondary_speech_act_check;
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD CONSTRAINT utterance_interpretations_secondary_speech_act_check
|
||||||
|
CHECK (secondary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN'));
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations DROP CONSTRAINT IF EXISTS utterance_interpretations_applicability_check;
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD CONSTRAINT utterance_interpretations_applicability_check
|
||||||
|
CHECK (applicability IN ('APPLICABLE','LOW_CONFIDENCE','MIXED_INTENT','NEEDS_BROADER_INTERPRETATION','CLARIFICATION_REQUIRED'));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interaction.semantic_candidates (
|
||||||
|
candidate_id TEXT PRIMARY KEY,
|
||||||
|
utterance_id TEXT NOT NULL,
|
||||||
|
source TEXT NOT NULL,
|
||||||
|
selection_state TEXT NOT NULL,
|
||||||
|
primary_speech_act TEXT NOT NULL,
|
||||||
|
secondary_speech_act TEXT NOT NULL,
|
||||||
|
confidence_millis BIGINT NOT NULL,
|
||||||
|
applicability TEXT NOT NULL,
|
||||||
|
requested_outcome TEXT NOT NULL DEFAULT '',
|
||||||
|
clarification TEXT NOT NULL,
|
||||||
|
needs_cognition BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
selection_reason TEXT NOT NULL DEFAULT '',
|
||||||
|
recorded_at_unix_millis BIGINT NOT NULL,
|
||||||
|
CHECK (source IN ('DETERMINISTIC_V2','COGNITIVE_V1')),
|
||||||
|
CHECK (selection_state IN ('SELECTED','OBSERVED','REJECTED')),
|
||||||
|
CHECK (primary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN')),
|
||||||
|
CHECK (secondary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN')),
|
||||||
|
CHECK (confidence_millis BETWEEN 0 AND 1000),
|
||||||
|
CHECK (applicability IN ('APPLICABLE','LOW_CONFIDENCE','MIXED_INTENT','NEEDS_BROADER_INTERPRETATION','CLARIFICATION_REQUIRED')),
|
||||||
|
CHECK (clarification IN ('NOT_REQUIRED','REQUIRED'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interaction.semantic_candidate_capability_hints (
|
||||||
|
candidate_id TEXT NOT NULL,
|
||||||
|
capability_kind TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (candidate_id, capability_kind),
|
||||||
|
CHECK (candidate_id <> ''),
|
||||||
|
CHECK (capability_kind <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
RESET ROLE;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
BEGIN;
|
||||||
|
SET ROLE capability_role;
|
||||||
|
|
||||||
|
ALTER TABLE capability.cognitive_provider_instances
|
||||||
|
ADD COLUMN IF NOT EXISTS billing_mode TEXT NOT NULL DEFAULT 'UNKNOWN',
|
||||||
|
ADD COLUMN IF NOT EXISTS input_cost_micros BIGINT,
|
||||||
|
ADD COLUMN IF NOT EXISTS output_cost_micros BIGINT,
|
||||||
|
ADD COLUMN IF NOT EXISTS request_cost_micros BIGINT;
|
||||||
|
ALTER TABLE capability.cognitive_provider_instances
|
||||||
|
ADD COLUMN IF NOT EXISTS auth_mode TEXT NOT NULL DEFAULT 'NONE';
|
||||||
|
ALTER TABLE capability.cognitive_provider_instances
|
||||||
|
DROP CONSTRAINT IF EXISTS cognitive_provider_instances_billing_mode_check,
|
||||||
|
ADD CONSTRAINT cognitive_provider_instances_billing_mode_check CHECK (billing_mode IN ('UNKNOWN','FREE','PER_INPUT_UNIT','PER_OUTPUT_UNIT','PER_REQUEST')),
|
||||||
|
DROP CONSTRAINT IF EXISTS cognitive_provider_instances_auth_mode_check,
|
||||||
|
ADD CONSTRAINT cognitive_provider_instances_auth_mode_check CHECK (auth_mode IN ('NONE','API_KEY','BEARER','USERNAME_PASSWORD','OAUTH','SECRET_FILE')),
|
||||||
|
DROP CONSTRAINT IF EXISTS cognitive_provider_instances_cost_check,
|
||||||
|
ADD CONSTRAINT cognitive_provider_instances_cost_check CHECK ((input_cost_micros IS NULL OR input_cost_micros >= 0) AND (output_cost_micros IS NULL OR output_cost_micros >= 0) AND (request_cost_micros IS NULL OR request_cost_micros >= 0));
|
||||||
|
|
||||||
|
ALTER TABLE capability.cognitive_model_descriptors
|
||||||
|
ADD COLUMN IF NOT EXISTS intelligence_score_millis BIGINT;
|
||||||
|
ALTER TABLE capability.cognitive_model_descriptors
|
||||||
|
DROP CONSTRAINT IF EXISTS cognitive_model_descriptors_intelligence_score_check,
|
||||||
|
ADD CONSTRAINT cognitive_model_descriptors_intelligence_score_check CHECK (intelligence_score_millis IS NULL OR (intelligence_score_millis >= 0 AND intelligence_score_millis <= 1000));
|
||||||
|
|
||||||
|
RESET ROLE;
|
||||||
|
COMMIT;
|
||||||
@@ -102,6 +102,7 @@ services:
|
|||||||
LISTEN_ADDR: ":8083"
|
LISTEN_ADDR: ":8083"
|
||||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||||
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
||||||
|
LOCAL_LIFEBOAT_PROVIDER_URL: ${LOCAL_LIFEBOAT_PROVIDER_URL:-}
|
||||||
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
||||||
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
||||||
ports: ["19083:8083"]
|
ports: ["19083:8083"]
|
||||||
|
|||||||
@@ -126,10 +126,42 @@ services:
|
|||||||
LISTEN_ADDR: ":8083"
|
LISTEN_ADDR: ":8083"
|
||||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||||
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
||||||
|
LOCAL_LIFEBOAT_PROVIDER_URL: http://cognitive-lifeboat:8086/v1
|
||||||
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
||||||
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
||||||
COGNITIVE_ALLOW_CANARY: "true"
|
COGNITIVE_ALLOW_CANARY: "true"
|
||||||
depends_on: [core-runtime]
|
depends_on: [core-runtime, cognitive-lifeboat]
|
||||||
|
|
||||||
|
cognitive-lifeboat:
|
||||||
|
image: ghcr.io/ggml-org/llama.cpp:server
|
||||||
|
restart: unless-stopped
|
||||||
|
command:
|
||||||
|
- --host
|
||||||
|
- 0.0.0.0
|
||||||
|
- --port
|
||||||
|
- "8086"
|
||||||
|
- --model
|
||||||
|
- /models/Qwen3-8B-Q4_K_M.gguf
|
||||||
|
- --alias
|
||||||
|
- domovoy-lifeboat
|
||||||
|
- --jinja
|
||||||
|
- --ctx-size
|
||||||
|
- "8192"
|
||||||
|
- --n-gpu-layers
|
||||||
|
- "0"
|
||||||
|
- --threads
|
||||||
|
- "32"
|
||||||
|
- --parallel
|
||||||
|
- "1"
|
||||||
|
- --reasoning
|
||||||
|
- "off"
|
||||||
|
volumes:
|
||||||
|
- llm_local_models:/models:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -fsS http://localhost:8086/health >/dev/null"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
creator-web:
|
creator-web:
|
||||||
build: { context: .., dockerfile: deploy/images/runtime.Dockerfile, args: { TARGET: creator-web, SOURCE_REVISION: "${ASSISTANT_SOURCE_REVISION:-unknown}" } }
|
build: { context: .., dockerfile: deploy/images/runtime.Dockerfile, args: { TARGET: creator-web, SOURCE_REVISION: "${ASSISTANT_SOURCE_REVISION:-unknown}" } }
|
||||||
@@ -140,6 +172,7 @@ services:
|
|||||||
CONTINUITY_RUNTIME_URL: http://continuity-runtime:8081
|
CONTINUITY_RUNTIME_URL: http://continuity-runtime:8081
|
||||||
COMMIT_RUNTIME_URL: http://commit-runtime:8082
|
COMMIT_RUNTIME_URL: http://commit-runtime:8082
|
||||||
COGNITIVE_RUNTIME_URL: http://cognitive-worker:8083
|
COGNITIVE_RUNTIME_URL: http://cognitive-worker:8083
|
||||||
|
ASSISTANT_BUILD_REVISION: ${ASSISTANT_SOURCE_REVISION:-unknown}
|
||||||
ports: ["${CREATOR_WEB_PORT:-18080}:8084"]
|
ports: ["${CREATOR_WEB_PORT:-18080}:8084"]
|
||||||
depends_on: [core-runtime, continuity-runtime, commit-runtime, cognitive-worker]
|
depends_on: [core-runtime, continuity-runtime, commit-runtime, cognitive-worker]
|
||||||
healthcheck:
|
healthcheck:
|
||||||
@@ -158,3 +191,6 @@ volumes:
|
|||||||
external: true
|
external: true
|
||||||
assistant_notification_reader_secret:
|
assistant_notification_reader_secret:
|
||||||
external: true
|
external: true
|
||||||
|
llm_local_models:
|
||||||
|
external: true
|
||||||
|
name: llm-local-models
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"task_file": "dev/tasks/DEV-000071-cognitive-path-reality-generalization.json",
|
"task_file": "dev/tasks/DEV-000089-domovoy-cognitive-upgrade-integration.json",
|
||||||
"task_id": "DEV-000071",
|
"task_id": "DEV-000089",
|
||||||
"task_revision": 1
|
"task_revision": 1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000072",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000071-baseline",
|
||||||
|
"base_repo_revision": "64870798b9a50f895c99d24441703f366df5c98a",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Implement semantic interpretation and deferral boundary V1 so deterministic interpretation acts as a fast-path candidate rather than unquestionable final truth; preserve provenance between deterministic and cognitive candidates; support mixed intent and safer deferral without activating new providers.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"DEV-000071 measured baseline",
|
||||||
|
"Deterministic candidate can decline/defer",
|
||||||
|
"Mixed intent representation",
|
||||||
|
"Cognition may challenge uncertain deterministic candidate",
|
||||||
|
"No provider hardcoding",
|
||||||
|
"No Ollama activation",
|
||||||
|
"Known and holdout evaluation comparison",
|
||||||
|
"Production chat acceptance"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": [
|
||||||
|
"interaction",
|
||||||
|
"work",
|
||||||
|
"capability",
|
||||||
|
"epistemics"
|
||||||
|
],
|
||||||
|
"paths": [
|
||||||
|
"contracts/interaction/**",
|
||||||
|
"contracts/work/**",
|
||||||
|
"contracts/cognitive/**",
|
||||||
|
"modules/interaction/**",
|
||||||
|
"modules/work/**",
|
||||||
|
"adapters/postgres/interaction_repository.go",
|
||||||
|
"cmd/core-runtime/**",
|
||||||
|
"cmd/creator-web/**",
|
||||||
|
"cmd/cognitive-worker/**",
|
||||||
|
"database/migrations/**",
|
||||||
|
"tests/**",
|
||||||
|
"docs/PROJECT_STATUS.md",
|
||||||
|
"docs/evidence/**",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000072-semantic-interpretation-deferral-boundary.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": [
|
||||||
|
"architecture/ARCHITECTURE_CONSTITUTION.md",
|
||||||
|
"architecture/architecture-registry.yaml",
|
||||||
|
"architecture/architecture-registry.json",
|
||||||
|
"architecture/adrs/**",
|
||||||
|
"security/**",
|
||||||
|
"modules/authority/**",
|
||||||
|
"modules/commit/**",
|
||||||
|
"deploy/**",
|
||||||
|
"ci/**",
|
||||||
|
".gitea/**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": [
|
||||||
|
"contracts.identity",
|
||||||
|
"contracts.interaction",
|
||||||
|
"contracts.work",
|
||||||
|
"contracts.capability",
|
||||||
|
"contracts.cognitive",
|
||||||
|
"contracts.epistemics",
|
||||||
|
"contracts.situation"
|
||||||
|
],
|
||||||
|
"may_change": [
|
||||||
|
"contracts.interaction",
|
||||||
|
"contracts.work",
|
||||||
|
"contracts.cognitive"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"semantic_owner": "interaction",
|
||||||
|
"canonical_state": [
|
||||||
|
"Interaction-owned human utterance interpretation semantics",
|
||||||
|
"Interaction-owned interpretation provenance between deterministic and cognitive candidates",
|
||||||
|
"Owner-local persistence expansion for semantic candidate provenance",
|
||||||
|
"Existing Work planning/help-path semantics updated to consume richer interaction interpretation without changing canonical ownership"
|
||||||
|
],
|
||||||
|
"state_transitions": [
|
||||||
|
"human utterance -> deterministic semantic candidate",
|
||||||
|
"candidate accepted or deferred",
|
||||||
|
"deferred candidate -> cognitive candidate",
|
||||||
|
"candidate selection -> persisted selected interpretation + provenance",
|
||||||
|
"mixed/consequential ambiguity -> clarification or bounded safe response"
|
||||||
|
],
|
||||||
|
"side_effects_and_privileges": [
|
||||||
|
"No direct external mutation",
|
||||||
|
"Cognitive Gateway only through existing provider-neutral runtime",
|
||||||
|
"No direct CPU endpoint calls from chat path",
|
||||||
|
"No provider activation changes"
|
||||||
|
],
|
||||||
|
"persistence_and_migrations": [
|
||||||
|
"Interaction owner-local migration expected",
|
||||||
|
"No cross-owner SQL writes",
|
||||||
|
"No cross-owner FK introduction",
|
||||||
|
"No new DB owner roles"
|
||||||
|
],
|
||||||
|
"failure_retry_restart": [
|
||||||
|
"If cognition is unavailable, obvious deterministic paths continue to work",
|
||||||
|
"Uncertain consequential intent must fail closed via clarification or explicit limitation",
|
||||||
|
"Model output must remain typed candidate evidence, never direct canonical fact/action"
|
||||||
|
],
|
||||||
|
"assumptions": [
|
||||||
|
"Current production has only one proven eligible cognitive binding for human chat: CPU CANARY",
|
||||||
|
"Ollama/GPU remains inactive for routing in this milestone",
|
||||||
|
"DEV-000071 artifacts remain the baseline comparison set"
|
||||||
|
],
|
||||||
|
"acceptance_scenarios": [
|
||||||
|
"ask-model request no longer finalized as assertion by default",
|
||||||
|
"think/investigate wording can defer to cognition without lexical patching as the sole strategy",
|
||||||
|
"mixed investigate+modify retains both semantic needs",
|
||||||
|
"correction wording plus new directive preserves both aspects",
|
||||||
|
"uncertain consequential request defers safely",
|
||||||
|
"suite_v1 plus DEV-000071 development/holdout comparisons are reported honestly",
|
||||||
|
"production /chat acceptance covers greeting, cognition question, named implementation request, mixed work, correction, correction+new directive, consequential ambiguity"
|
||||||
|
],
|
||||||
|
"required_tests": [
|
||||||
|
"go test ./...",
|
||||||
|
"go vet ./...",
|
||||||
|
"go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json",
|
||||||
|
"go run ./cmd/devctl check-architecture",
|
||||||
|
"go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json",
|
||||||
|
"tests/cognitive_advisory/cognitive_worker_env_policy_test.ps1",
|
||||||
|
"tests/owner_acl/verify.ps1 -DockerContext docker-prod -PostgresContainer assistant-postgres-1",
|
||||||
|
"interaction domain tests",
|
||||||
|
"work planning tests",
|
||||||
|
"reality evaluation comparisons",
|
||||||
|
"production /chat acceptance"
|
||||||
|
],
|
||||||
|
"terminal_gap_states": [
|
||||||
|
"BLOCKED_BY_SPEC_GAP",
|
||||||
|
"BLOCKED_BY_ARCHITECTURE_GAP",
|
||||||
|
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||||
|
"BLOCKED_BY_CONFLICT",
|
||||||
|
"REQUIRES_MIGRATION_DECISION"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000074",
|
||||||
|
"task_revision": 6,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "1cfbb4ae66e24d514e59dabafb936c35546bd418",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Make the authenticated Creator Web cabinet understandable and operable for a human by adding section navigation, read-only diagnostics, and browser-local interface preferences without changing domain state or authority boundaries.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Human can move between overview, diagnostics, operations and settings",
|
||||||
|
"Human can run all currently exposed read-only Creator checks from one diagnostic panel",
|
||||||
|
"Interface preferences remain local to the browser and never change canonical state",
|
||||||
|
"Existing explicit confirmation remains required for canonical mutations",
|
||||||
|
"Desktop and mobile layouts remain usable"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/static/index.html",
|
||||||
|
"cmd/creator-web/static/assets/console.css",
|
||||||
|
"cmd/creator-web/static/assets/console.js",
|
||||||
|
"cmd/creator-web/server_test.go",
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"docs/PROJECT_STATUS.md",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000074-creator-cabinet-operations.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": [
|
||||||
|
"architecture/**",
|
||||||
|
"security/**",
|
||||||
|
"database/**",
|
||||||
|
"modules/**",
|
||||||
|
"contracts/**",
|
||||||
|
"adapters/**",
|
||||||
|
"cmd/core-runtime/**",
|
||||||
|
"cmd/commit-runtime/**",
|
||||||
|
"cmd/continuity-runtime/**",
|
||||||
|
"deploy/**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing authenticated Creator gateway endpoints"],
|
||||||
|
"may_change": []
|
||||||
|
},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": [
|
||||||
|
"diagnostic request -> read-only gateway observation",
|
||||||
|
"settings form submit -> browser-local preference update"
|
||||||
|
],
|
||||||
|
"side_effects_and_privileges": [
|
||||||
|
"No new privilege or mutation endpoint",
|
||||||
|
"No database migration",
|
||||||
|
"Existing Commit actions retain explicit confirmation dialogs",
|
||||||
|
"No deployment or neighboring project mutation"
|
||||||
|
],
|
||||||
|
"persistence_and_migrations": ["No canonical persistence; localStorage only for interface preferences"],
|
||||||
|
"failure_retry_restart": ["Diagnostic failures are shown per check without exposing upstream error details"],
|
||||||
|
"assumptions": [
|
||||||
|
"Existing Creator API routes remain the source of truth",
|
||||||
|
"Browser-local settings are disposable and do not affect domain behavior"
|
||||||
|
],
|
||||||
|
"acceptance_scenarios": [
|
||||||
|
"Authenticated cabinet exposes navigation to all four human-facing sections",
|
||||||
|
"read-only diagnostics checks session, advisory policy, capability, today, attention, actions and learning",
|
||||||
|
"density, auto-refresh and reduced-motion preferences save and reset locally",
|
||||||
|
"mobile layout remains readable",
|
||||||
|
"existing Creator Web tests pass",
|
||||||
|
"architecture and diff scope checks pass"
|
||||||
|
],
|
||||||
|
"required_tests": [
|
||||||
|
"node --check cmd/creator-web/static/assets/console.js",
|
||||||
|
"go test ./cmd/creator-web",
|
||||||
|
"go test ./...",
|
||||||
|
"go vet ./...",
|
||||||
|
"go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json",
|
||||||
|
"go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json",
|
||||||
|
"go run ./cmd/devctl check-architecture",
|
||||||
|
"git diff --check",
|
||||||
|
"responsive browser inspection"
|
||||||
|
],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000075",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "39a27102c9665e41f29e85bc8f82a316bbbe3962",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Make live conversation with Domovoy the public starting surface and keep the Creator operator console on a separate admin route.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Public root opens the human chat",
|
||||||
|
"Operator console remains available at a separate admin route",
|
||||||
|
"Existing /chat route remains compatible",
|
||||||
|
"Chat does not expose provider, model, binding, session or workspace internals"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/server.go",
|
||||||
|
"cmd/creator-web/server_test.go",
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000075-creator-chat-primary-surface.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {"consume": ["existing /chat and authenticated Creator endpoints"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["GET / -> chat surface", "GET /admin -> operator console surface"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No canonical mutation", "No model/provider routing change"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Existing chat failure behavior remains unchanged"],
|
||||||
|
"assumptions": ["/chat is the existing human chat surface", "The operator console may be reached at /admin"],
|
||||||
|
"acceptance_scenarios": ["Root serves chat", "Admin serves console", "Chat compatibility remains", "Internal IDs remain absent from chat HTML"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000076",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "26cf85108a63dfbd67866d9df0445dbcb54983be",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Show the human user whether Domovoy's primary cognitive channel is available without exposing provider internals or mixing technical events into the conversation.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Chat shows a human-readable cognitive channel status",
|
||||||
|
"Status is read-only and refreshed periodically",
|
||||||
|
"Chat does not expose provider, model or binding identifiers",
|
||||||
|
"Chat remains usable while status observation fails"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"cmd/creator-web/static/assets/chat.css",
|
||||||
|
"cmd/creator-web/static/assets/chat.js",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000076-creator-chat-cognitive-status.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {"consume": ["existing authenticated /api/capabilities/cognitive-proposal/health endpoint"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Browser polls existing cognitive capability health observation", "Browser renders coarse human-readable status"],
|
||||||
|
"side_effects_and_privileges": ["Read-only observation", "No new privilege", "No provider/model routing change"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Failed observation renders an unavailable/degraded notice; chat remains available", "Polling retries on the next interval"],
|
||||||
|
"assumptions": ["The existing health endpoint returns State or state with AVAILABLE, DEGRADED or UNAVAILABLE semantics", "The chat token authorizes the existing health endpoint"],
|
||||||
|
"acceptance_scenarios": ["Authenticated chat displays a status indicator", "Health polling does not reveal internal identifiers", "Mobile header keeps the status visible", "A failed health request does not disable the composer"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000077",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "75abfb204bb427a0500a8c37440c374576c2153c",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Make model configuration changes understandable from the human chat while keeping configuration mutation in the separate operator console.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"User can manually re-check the cognitive channel from chat",
|
||||||
|
"Chat clearly directs configuration changes to the operator console",
|
||||||
|
"No configuration mutation is performed by the browser chat",
|
||||||
|
"The conversation remains free of technical runtime identifiers"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"cmd/creator-web/static/assets/chat.css",
|
||||||
|
"cmd/creator-web/static/assets/chat.js",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000077-creator-chat-cognitive-bridge.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {"consume": ["existing authenticated /api/capabilities/cognitive-proposal/health endpoint", "existing /admin operator surface"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["User requests a fresh read-only health observation", "Browser presents console handoff when the channel is not ready"],
|
||||||
|
"side_effects_and_privileges": ["Read-only observation only", "No new privilege", "No provider/model routing change", "No chat mutation from status controls"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Manual check uses the same safe health route", "Polling remains the retry mechanism"],
|
||||||
|
"assumptions": ["The operator console remains the authorized place for runtime configuration changes", "The existing health route is sufficient to observe readiness"],
|
||||||
|
"acceptance_scenarios": ["Clicking status requests a fresh health observation", "Unavailable status exposes an operator-console handoff", "Available status hides the handoff", "Chat HTML remains free of internal identifiers"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000078",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "0d10e6fd82a7c374bebbc8d3cee9c1ed0b420745",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Let Domovoy answer explicit questions about the local cognitive channel from the Capability-owned health observation and route configuration changes to the operator console without mutating runtime configuration.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Explicit model/channel questions use observed capability health",
|
||||||
|
"Model configuration requests never call a provider directly from Core",
|
||||||
|
"Configuration changes are explained as a separate operator-console action",
|
||||||
|
"Provider and model identifiers remain hidden from human chat"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/core-runtime"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/core-runtime/main.go",
|
||||||
|
"cmd/core-runtime/main_test.go",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000078-core-conversational-cognitive-health.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {"consume": ["Capability repository LoadHealth", "existing cognitive-proposal health semantics", "existing /admin operator surface"], "may_change": []},
|
||||||
|
"semantic_owner": "capability-observation-consumer",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Human asks about local cognitive channel", "Core reads Capability-owned health observation", "Core returns observation or safe unavailable explanation"],
|
||||||
|
"side_effects_and_privileges": ["No provider call for explicit status/configuration questions", "No runtime configuration mutation", "No new privilege"],
|
||||||
|
"persistence_and_migrations": ["Existing utterance and semantic persistence only", "No migration"],
|
||||||
|
"failure_retry_restart": ["Missing health observation produces an honest unavailable reply", "Future status polling remains available in chat UI"],
|
||||||
|
"assumptions": ["The operator console is the authorized configuration surface", "Capability health is a sufficient provider-neutral observation for the first conversational response"],
|
||||||
|
"acceptance_scenarios": ["Проверь локальную модель returns a human-readable health observation", "Переключи модель does not mutate configuration and directs to console", "Replies contain no provider/model/binding identifiers", "Unit tests cover available, unavailable and repository failure states"],
|
||||||
|
"required_tests": ["go test ./cmd/core-runtime", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000079",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "b0d31012dac1526e721e57c691555933eb501a5a",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Make the primary Domovoy chat self-explanatory with concise conversation starters for cognitive-channel checks and configuration handoff.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"A new user can discover the main cognitive-channel conversation paths",
|
||||||
|
"Conversation starters submit ordinary human text",
|
||||||
|
"No starter exposes internal identifiers",
|
||||||
|
"The chat remains usable on mobile"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"cmd/creator-web/static/assets/chat.css",
|
||||||
|
"cmd/creator-web/static/assets/chat.js",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000079-chat-conversation-starters.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing chat message endpoint"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["User selects a conversation starter", "Browser submits its ordinary text through the existing chat flow"],
|
||||||
|
"side_effects_and_privileges": ["Existing chat semantics only", "No new privilege", "No direct model or configuration mutation"],
|
||||||
|
"persistence_and_migrations": ["Existing conversation persistence only", "No migration"],
|
||||||
|
"failure_retry_restart": ["Starter uses existing chat error handling"],
|
||||||
|
"assumptions": ["The user can still type any other request in the composer"],
|
||||||
|
"acceptance_scenarios": ["Three human-readable starter actions are visible", "Clicking a starter sends its text through the normal chat flow", "No internal IDs appear in the page", "Starter layout remains usable at mobile width"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000080",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "47fd0c4b027ff5ab2781b26c5bc4f7ddc45d961f",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Replace the unstable single-column chat presentation with a fixed three-column layout, explicit console return, and a safe human path for passing AI information into the current conversation.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Header controls keep stable dimensions",
|
||||||
|
"Desktop chat has independently scrolling left, center and right regions",
|
||||||
|
"Console has an explicit return-to-chat action",
|
||||||
|
"User can pass non-secret AI notes as an ordinary chat message",
|
||||||
|
"Mobile layout remains usable"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/creator-web"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"cmd/creator-web/static/index.html",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"cmd/creator-web/static/assets/chat.css",
|
||||||
|
"cmd/creator-web/static/assets/chat.js",
|
||||||
|
"cmd/creator-web/static/assets/console.css",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000080-chat-three-column-layout.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing chat message endpoint", "existing /admin route"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": ["AI notes are submitted through the existing conversation; no new AI registry state is created"],
|
||||||
|
"state_transitions": ["User submits non-secret AI notes as a normal chat message", "User navigates between chat and console using explicit links"],
|
||||||
|
"side_effects_and_privileges": ["Existing chat persistence only", "No direct model/provider mutation", "No new privilege"],
|
||||||
|
"persistence_and_migrations": ["No migration"],
|
||||||
|
"failure_retry_restart": ["AI notes use existing chat failure handling", "Layout has no new runtime dependency"],
|
||||||
|
"assumptions": ["The current conversation is the correct first destination for AI notes", "Sensitive credentials must never be pasted into chat"],
|
||||||
|
"acceptance_scenarios": ["Desktop regions scroll independently", "Header status and actions do not resize when text changes", "Console visibly links back to chat", "AI notes form sends a clear message into chat", "Chat remains usable below 900px viewport width"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000081",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "6e0cf3cd1df864e8be8a9b61fe8462181516bab9",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Polish the stable chat header after the three-column rollout so the cognitive status cannot push navigation controls around.",
|
||||||
|
"requirement_ids": ["Header status is right-aligned and bounded", "Console exposes an explicit chat return link"],
|
||||||
|
"allowed_change_scope": {"modules": ["cmd/creator-web"], "paths": ["cmd/creator-web/chat_test.go", "cmd/creator-web/static/assets/chat.css", "dev/ACTIVE_TASK.json", "dev/tasks/DEV-000081-chat-header-final-polish.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing chat and admin surfaces"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["No semantic state transition"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No runtime behavior change"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["No new failure mode"],
|
||||||
|
"assumptions": ["The previous three-column layout is the intended public chat surface"],
|
||||||
|
"acceptance_scenarios": ["Header status does not alter the positions of console and logout controls", "Admin HTML includes a visible chat return action"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000082",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "ae9933ee846254f970e4ef3f3e46d63e7a01db5a",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Prevent accidental transmission of obvious credentials through the AI information form while preserving ordinary model notes as chat messages.",
|
||||||
|
"requirement_ids": ["AI notes form warns about secrets", "Obvious secret-shaped input is blocked before chat submission", "Safe model descriptions continue through the normal chat flow"],
|
||||||
|
"allowed_change_scope": {"modules": ["cmd/creator-web"], "paths": ["cmd/creator-web/chat_test.go", "cmd/creator-web/static/chat.html", "cmd/creator-web/static/assets/chat.css", "cmd/creator-web/static/assets/chat.js", "dev/ACTIVE_TASK.json", "dev/tasks/DEV-000082-chat-ai-data-safety-guard.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing chat message endpoint"], "may_change": []},
|
||||||
|
"semantic_owner": "none-interface-adapter",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Secret-shaped text is rejected locally", "Non-secret AI notes continue as a normal conversation message"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No transmission when the guard detects a secret-shaped value"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["User can edit and retry after removing the sensitive value"],
|
||||||
|
"assumptions": ["The guard is a convenience barrier, not a complete secret scanner", "Users must still avoid pasting secrets"],
|
||||||
|
"acceptance_scenarios": ["API-key and private-key-shaped input is blocked", "Password/token labels are blocked", "Ordinary model notes are submitted", "The warning is visible and accessible"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000083",
|
||||||
|
"task_revision": 3,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "0a2599cfa6255f1a98856d2fd09dc51a2119f525",
|
||||||
|
"risk_tier": "C",
|
||||||
|
"intent": "Keep Domovoy alive and conversational when the primary cognitive channel is unavailable by running a small local Lifeboat provider and retaining an honest deterministic degraded mode.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Primary cognitive settings remain confirmation-controlled while healthy",
|
||||||
|
"Unavailable primary cognition exposes a human-readable degraded mode instead of killing chat",
|
||||||
|
"A small local-only provider can serve as the Lifeboat through the existing Cognitive Gateway",
|
||||||
|
"The core can still accept and explain configuration requests when all model providers are unavailable"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["cmd/core-runtime", "cmd/cognitive-worker", "cmd/creator-web", "modules/capability", "adapters/postgres", "deployment"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/core-runtime/main.go",
|
||||||
|
"cmd/core-runtime/main_test.go",
|
||||||
|
"cmd/cognitive-worker/main.go",
|
||||||
|
"cmd/cognitive-worker/main_test.go",
|
||||||
|
"modules/capability/domain/cognitive_registry.go",
|
||||||
|
"modules/capability/domain/cognitive_registry_test.go",
|
||||||
|
"modules/capability/ports/repository.go",
|
||||||
|
"contracts/capability/cognitive_registry.go",
|
||||||
|
"cmd/creator-web/static/assets/chat.js",
|
||||||
|
"cmd/creator-web/static/chat.html",
|
||||||
|
"cmd/creator-web/chat_test.go",
|
||||||
|
"adapters/postgres/capability_repository.go",
|
||||||
|
"tests/cognitive_canary/promotion_test.go",
|
||||||
|
"deploy/docker-compose.prod.yml",
|
||||||
|
"deploy/docker-compose.dev.yml",
|
||||||
|
"dev/tasks/DEV-000083-lifeboat-benchmark-manifest.json",
|
||||||
|
"docs/evidence/domovoy-lifeboat-qualification-2026-08-21-v1.json",
|
||||||
|
"dev/tasks/DEV-000083-domovoy-lifeboat-mode.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "contracts/**", "adapters/**", "modules/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing Cognitive Gateway and Capability Registry", "existing chat response fields", "existing cognitive health endpoint"],
|
||||||
|
"may_change": ["authorized cognitive activation transition"]
|
||||||
|
},
|
||||||
|
"semantic_owner": "capability-observation-consumer",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": [
|
||||||
|
"Healthy primary channel keeps normal configuration handoff and confirmation behavior",
|
||||||
|
"Unavailable primary channel renders Domovoy alive in local degraded mode",
|
||||||
|
"Optional Lifeboat provider participates only through the existing gateway resolution/failover path"
|
||||||
|
],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No external egress", "No direct provider call from Core", "No configuration mutation from browser chat"],
|
||||||
|
"persistence_and_migrations": ["No migration", "Existing conversation and capability observations only"],
|
||||||
|
"failure_retry_restart": ["Provider absence falls back to the deterministic core reply", "The Lifeboat container restarts independently from the primary model runtime", "Restart reconstructs the provider registration from environment"],
|
||||||
|
"assumptions": ["The Lifeboat endpoint implements the existing OpenAI-compatible local adapter contract", "Capability discovery/promotion remains the existing authorized path", "No real test secrets are in scope for this task"],
|
||||||
|
"acceptance_scenarios": [
|
||||||
|
"Primary unavailable message says Domovoy remains alive and can help recover",
|
||||||
|
"Configuration request in degraded mode no longer falsely requires the primary model",
|
||||||
|
"Production Lifeboat container exposes the configured small local model through the existing gateway adapter",
|
||||||
|
"Chat status distinguishes primary unavailable from Domovoy unavailable",
|
||||||
|
"Healthy mode keeps confirmation/console wording"
|
||||||
|
],
|
||||||
|
"required_tests": ["go test ./cmd/core-runtime", "go test ./cmd/cognitive-worker", "go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check", "node --check cmd/creator-web/static/assets/chat.js"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"artifact_id": "domovoy-lifeboat-qualification-2026-08-21-v1",
|
||||||
|
"providers": [
|
||||||
|
{
|
||||||
|
"provider_instance_id": "local-lifeboat",
|
||||||
|
"provider_kind": "openai-compatible-chat-v1",
|
||||||
|
"endpoint": "http://cognitive-lifeboat:8086/v1",
|
||||||
|
"candidates": [
|
||||||
|
{
|
||||||
|
"provider_model_id": "domovoy-lifeboat",
|
||||||
|
"model_descriptor_id": "model-7dd2e1dd5adb40af7ad7985f",
|
||||||
|
"model_revision": 464323937472454403,
|
||||||
|
"binding_id": "binding-98b26ae572f3534ecb7d32c6",
|
||||||
|
"binding_revision": 594087847110549365
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000084",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "0482e6ac14cd7625598a203dbdec9298b1bac04c",
|
||||||
|
"risk_tier": "C",
|
||||||
|
"intent": "Evolve the single-catalog cognitive orchestrator with an always-available built-in provider and task-aware selection across connected providers using capability, quality, latency, cost, and reliability evidence.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"Built-in Domovoy cognition remains available without an external provider",
|
||||||
|
"Connected providers expose typed connection references without credential material",
|
||||||
|
"Provider selection considers task capability, quality, speed, cost, and reliability",
|
||||||
|
"Provider and model revisions remain replaceable as the catalog evolves"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["capability", "cognitive-worker"],
|
||||||
|
"paths": [
|
||||||
|
"contracts/capability/cognitive_registry.go",
|
||||||
|
"contracts/cognitive/types.go",
|
||||||
|
"contracts/interaction/types.go",
|
||||||
|
"modules/capability/domain/cognitive_registry.go",
|
||||||
|
"modules/capability/domain/cognitive_registry_test.go",
|
||||||
|
"adapters/postgres/capability_repository.go",
|
||||||
|
"database/migrations/028_capability_cognitive_provider_profile.sql",
|
||||||
|
"cmd/cognitive-worker/main.go",
|
||||||
|
"cmd/cognitive-worker/gateway.go",
|
||||||
|
"cmd/cognitive-worker/gateway_registry_test.go",
|
||||||
|
"cmd/cognitive-worker/interpretation.go",
|
||||||
|
"cmd/cognitive-worker/interpretation_live_trace_test.go",
|
||||||
|
"cmd/cognitive-worker/discovery.go",
|
||||||
|
"cmd/creator-web/server.go",
|
||||||
|
"cmd/core-runtime/main.go",
|
||||||
|
"dev/tasks/DEV-000084-evolving-cognitive-provider-catalog.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "cmd/core-runtime/**", "cmd/creator-web/**", "deploy/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_provider_adapters": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing capability registry", "existing cognitive gateway"],
|
||||||
|
"may_change": ["versioned provider profile and task-aware selection fields"]
|
||||||
|
},
|
||||||
|
"semantic_owner": "capability",
|
||||||
|
"canonical_state": ["provider connection profile", "model suitability and performance evidence"],
|
||||||
|
"state_transitions": [
|
||||||
|
"discovered provider profile is validated before invocation",
|
||||||
|
"selection ranks eligible candidates without granting new authority",
|
||||||
|
"provider revision supersedes prior metadata without rewriting history"
|
||||||
|
],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "Credential material remains outside canonical registry"],
|
||||||
|
"persistence_and_migrations": ["One additive capability migration", "No cross-owner writes"],
|
||||||
|
"failure_retry_restart": ["Built-in provider remains available when registry or remote providers fail", "Provider failures are observed and excluded for the current attempt"],
|
||||||
|
"assumptions": ["V1 has one shared catalog and no user/group visibility", "Existing CredentialRef contract is retained", "Selection is advisory routing and does not authorize external actions"],
|
||||||
|
"acceptance_scenarios": [
|
||||||
|
"Built-in provider answers when no connected provider is invocable",
|
||||||
|
"Secret values never appear in provider registry responses or logs",
|
||||||
|
"Task requiring a capability excludes models without it",
|
||||||
|
"Quality, reliability, latency, and cost policy affect deterministic ranking",
|
||||||
|
"A failed primary provider falls back to another eligible provider"
|
||||||
|
],
|
||||||
|
"required_tests": ["go test ./modules/capability/domain", "go test ./cmd/cognitive-worker", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000085",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "cdc8eea1a747657ce0534b99ff35933ab3385877",
|
||||||
|
"risk_tier": "C",
|
||||||
|
"intent": "Keep Domovoy useful when external or active cognitive bindings are unavailable by invoking the built-in local lifeboat through the Cognitive Gateway and presenting an actionable recovery focus when all cognition fails.",
|
||||||
|
"requirement_ids": ["Built-in local cognition remains available", "Provider loss does not collapse conversation", "Recovery state is explained and actionable"],
|
||||||
|
"allowed_change_scope": {"modules": ["cognitive-worker"], "paths": ["cmd/cognitive-worker/gateway.go", "cmd/cognitive-worker/interpretation.go", "cmd/cognitive-worker/main.go", "cmd/cognitive-worker/gateway_registry_test.go", "cmd/cognitive-worker/interpretation_test.go", "dev/tasks/DEV-000085-builtin-cognitive-recovery.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing Cognitive Gateway and local provider adapter contracts"], "may_change": []},
|
||||||
|
"semantic_owner": "capability",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["No active binding -> built-in local invocation", "Built-in invocation failure -> recovery-focused degraded response"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "Built-in path is local-only and cannot egress externally"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Provider failure remains observable; next request retries resolution and built-in local path"],
|
||||||
|
"assumptions": ["The configured local lifeboat endpoint is part of Domovoy and may be used without external egress acknowledgement"],
|
||||||
|
"acceptance_scenarios": ["Inactive registry with healthy local lifeboat invokes the local adapter", "Interpretation also uses the built-in local path", "All cognition failure returns an actionable recovery response"],
|
||||||
|
"required_tests": ["go test ./cmd/cognitive-worker", "go test ./...", "go vet ./...", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000086",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "cdc8eea1a747657ce0534b99ff35933ab3385877",
|
||||||
|
"risk_tier": "C",
|
||||||
|
"intent": "Replace the unusable tiny lifeboat model with a capable, locally hosted Qwen3 8B quantized baseline while keeping Domovoy runtime on docker.cin.su.",
|
||||||
|
"requirement_ids": ["Built-in local cognition is useful for ordinary dialogue", "Local model remains available without external egress", "Model choice is explicit and replaceable"],
|
||||||
|
"allowed_change_scope": {"modules": ["deployment", "cognitive-worker"], "paths": ["deploy/docker-compose.prod.yml", "dev/tasks/DEV-000086-local-model-baseline.json", "dev/tasks/DEV-000085-builtin-cognitive-recovery.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing llama.cpp OpenAI-compatible local endpoint", "existing Cognitive Gateway"], "may_change": []},
|
||||||
|
"semantic_owner": "capability",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Configured model file -> loaded local baseline", "Local model replacement -> restart and health verification"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "Model is local-only and mounted read-only into the runtime"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Missing or invalid model keeps the container unhealthy and does not silently fall back to the tiny model"],
|
||||||
|
"assumptions": ["Qwen3-8B-Q4_K_M.gguf is present in the protected Docker model volume on docker.cin.su before rollout"],
|
||||||
|
"acceptance_scenarios": ["The configured lifeboat starts with the named Qwen3 8B model", "The OpenAI-compatible health endpoint is healthy", "No other host is used for Domovoy runtime"],
|
||||||
|
"required_tests": ["go test ./cmd/cognitive-worker", "go test ./...", "go vet ./...", "git diff --check", "production health and model endpoint verification"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "REQUIRES_MODEL_ARTIFACT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000087",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "cdc8eea1a747657ce0534b99ff35933ab3385877",
|
||||||
|
"risk_tier": "D",
|
||||||
|
"intent": "When the selected cognitive route is unavailable, keep Domovoy conversational, diagnose the failure, use the built-in local model, and probe explicitly configured external GPU/HTTP providers through the Cognitive Gateway without exposing credentials or bypassing egress policy.",
|
||||||
|
"requirement_ids": ["Provider loss becomes a recovery objective", "Meaning and task objective guide provider choice", "External egress requires explicit acknowledgement", "Credentials remain opaque secret references"],
|
||||||
|
"allowed_change_scope": {"modules": ["cognitive-worker"], "paths": ["cmd/cognitive-worker/gateway.go", "cmd/cognitive-worker/interpretation.go", "cmd/cognitive-worker/main.go", "cmd/cognitive-worker/recovery.go", "cmd/cognitive-worker/gateway_registry_test.go", "cmd/cognitive-worker/interpretation_test.go", "cmd/cognitive-worker/recovery_test.go", "dev/tasks/DEV-000087-cognitive-recovery-orchestrator.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**", "deploy/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing typed Cognitive Gateway", "existing local and Ollama adapters", "existing discovery and binding resolver"], "may_change": []},
|
||||||
|
"semantic_owner": "capability",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Selected provider failure -> local built-in attempt", "Local failure -> recovery diagnosis and configured-provider probe", "External probe -> registry discovery only; invocation requires policy acknowledgement"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No arbitrary network scanning", "No credential material in logs or messages"],
|
||||||
|
"persistence_and_migrations": ["Existing discovery registration only; no new persistence"],
|
||||||
|
"failure_retry_restart": ["Bounded sequential probes per request", "No unmanaged background retry loop", "Each new request re-resolves and re-probes"],
|
||||||
|
"assumptions": ["External GPU/HTTP endpoints are explicitly configured by deployment operators", "Core Runtime remains the owner of activation and selection"],
|
||||||
|
"acceptance_scenarios": ["Inactive registry with healthy local model still produces an intelligent local response", "Interpretation uses the same local recovery path", "External endpoints are discovered but never invoked without egress acknowledgement", "All failures yield actionable recovery text instead of a generic unavailable error"],
|
||||||
|
"required_tests": ["go test ./cmd/cognitive-worker", "go test ./...", "go vet ./...", "git diff --check", "production recovery request and provider health verification"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000088",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "cdc8eea1a747657ce0534b99ff35933ab3385877",
|
||||||
|
"risk_tier": "B",
|
||||||
|
"intent": "Expose self-describing build revision and runtime update time in the Domovoy chat without requiring a human status query.",
|
||||||
|
"requirement_ids": ["Human can identify the running build", "Displayed update time reflects the running container", "No internal identifiers are exposed in the chat UI"],
|
||||||
|
"allowed_change_scope": {"modules": ["creator-web", "deployment"], "paths": ["cmd/creator-web/server.go", "cmd/creator-web/chat_test.go", "cmd/creator-web/static/chat.html", "deploy/docker-compose.prod.yml", "dev/tasks/DEV-000088-runtime-build-status.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_provider_adapters": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing source revision build argument"], "may_change": []},
|
||||||
|
"semantic_owner": "creator-web",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Container startup -> build metadata visible in chat"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "No user or provider secrets displayed"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Missing revision is displayed as development/unknown; startup time remains observable"],
|
||||||
|
"assumptions": ["The production compose runner supplies ASSISTANT_SOURCE_REVISION for the running revision"],
|
||||||
|
"acceptance_scenarios": ["Chat shows revision and update time without a manual question", "HTML contains no internal provider or session identifiers", "Tests remain deterministic outside production"],
|
||||||
|
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "git diff --check", "production page verification"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000089",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000073-baseline",
|
||||||
|
"base_repo_revision": "9f717d720e217afd4cc87a4fbf851050d466d8cd",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Integrate the Domovoy local-model baseline, cognitive recovery orchestrator, and self-describing runtime status into one reviewed production change.",
|
||||||
|
"requirement_ids": ["Built-in cognition remains useful", "Provider loss triggers recovery", "Production runtime identifies its revision and update time"],
|
||||||
|
"allowed_change_scope": {"modules": ["cognitive-worker", "creator-web", "deployment", "development-governance"], "paths": ["cmd/cognitive-worker/discovery.go", "cmd/cognitive-worker/gateway.go", "cmd/cognitive-worker/gateway_registry_test.go", "cmd/cognitive-worker/interpretation.go", "cmd/cognitive-worker/main.go", "cmd/creator-web/chat_test.go", "cmd/creator-web/server.go", "cmd/creator-web/static/chat.html", "deploy/docker-compose.prod.yml", "dev/ACTIVE_TASK.json", "dev/tasks/DEV-000085-builtin-cognitive-recovery.json", "dev/tasks/DEV-000086-local-model-baseline.json", "dev/tasks/DEV-000087-cognitive-recovery-orchestrator.json", "dev/tasks/DEV-000088-runtime-build-status.json", "dev/tasks/DEV-000089-domovoy-cognitive-upgrade-integration.json"]},
|
||||||
|
"forbidden_change_scope": {"paths": ["architecture/**", "security/**", "database/**"]},
|
||||||
|
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0, "new_database_owner_roles": 0},
|
||||||
|
"contracts": {"consume": ["existing cognitive gateway", "existing creator-web runtime", "existing production compose runner"], "may_change": []},
|
||||||
|
"semantic_owner": "capability",
|
||||||
|
"canonical_state": [],
|
||||||
|
"state_transitions": ["Old active task -> integrated reviewed task", "Old local baseline -> Qwen3-8B baseline", "Unavailable active binding -> built-in and configured external recovery"],
|
||||||
|
"side_effects_and_privileges": ["No new privilege", "External invocation remains acknowledgement-gated", "No secrets in source or UI"],
|
||||||
|
"persistence_and_migrations": ["No persistence or migration"],
|
||||||
|
"failure_retry_restart": ["Existing auto-update runner deploys the merged main revision", "Missing model artifact leaves the lifeboat unhealthy rather than silently selecting the tiny model"],
|
||||||
|
"assumptions": ["Qwen3-8B-Q4_K_M.gguf is present in the protected Docker model volume on docker.cin.su"],
|
||||||
|
"acceptance_scenarios": ["CI accepts exact task scope", "Production chat shows running revision and update time", "Domovoy can answer through built-in local cognition when registry activation is unavailable"],
|
||||||
|
"required_tests": ["go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "git diff --check", "production health and revision verification"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "REQUIRES_MODEL_ARTIFACT"]
|
||||||
|
}
|
||||||
+22
-1
@@ -1,6 +1,27 @@
|
|||||||
# Assistant project status
|
# Assistant project status
|
||||||
|
|
||||||
Audit date: 2026-08-17. Active implementation: DEV-000071 revision 1.
|
Audit date: 2026-08-17. Active implementation: DEV-000072 revision 1.
|
||||||
|
|
||||||
|
## DEV-000072 checkpoint
|
||||||
|
|
||||||
|
- `DEV_000072_STATUS = LOCAL_ACCEPTANCE_PASS`
|
||||||
|
- `LAST_COMPLETED = semantic deferral boundary V1 implementation plus regression/generalization acceptance: deterministic semantic candidates, cognitive interpretation gateway path, owner-local candidate provenance persistence, mixed-intent planning input propagation, punctuation/metamorphic stability fixes, capability-gap/reminder/work-path repair, and live A/B/C trace evidence`
|
||||||
|
- `ARCHITECTURE_CHANGE = none; interaction owner remains unchanged and no new cross-owner dependency was accepted`
|
||||||
|
- `SEMANTIC_BOUNDARY_CHANGE = deterministic interpretation no longer acts as unquestionable final truth for low-confidence / broader-interpretation / mixed-intent cases; core runtime can request typed cognitive reinterpretation through the existing provider-neutral gateway`
|
||||||
|
- `PERSISTENCE_CHANGE = migration 027 adds secondary speech act / applicability / selection reason on interaction interpretations plus semantic candidate provenance tables`
|
||||||
|
- `GIT_ANCESTRY_STATUS = PASS: current branch merge-base equals origin/main at 64870798b9a50f895c99d24441703f366df5c98a; DEV-000071 commit c1aff60443829892ba70104f40b55de01f186a7f is contained in origin/main`
|
||||||
|
- `CHECK_DIFF_STATUS = PASS: diff scope checks OK for DEV-000072 against base 64870798b9a50f895c99d24441703f366df5c98a`
|
||||||
|
- `KNOWN_BASELINE_COMPARISON = suite_v1 baseline failed_available 4 / intent 0 / capability 3 / consequence 1 -> current failed_available 0 / intent 0 / capability 0 / consequence 0`
|
||||||
|
- `HOLDOUT_AND_GENERALIZATION_COMPARISON = suite_v2 baseline failed_available 18 / intent 3 / capability 7 / consequence 4 / unknown 7 -> current failed_available 0 / intent 0 / capability 0 / consequence 0 / unknown 0`
|
||||||
|
- `UNNECESSARY_COGNITION = no observed increase in suite_v1 or suite_v2 current-run`
|
||||||
|
- `UNNECESSARY_CLARIFICATION = current replay counts remain observable (suite_v1 1, suite_v2 5) and are recorded explicitly for operator review rather than hidden by aggregate PASS`
|
||||||
|
- `LIVE_TRACE_EVIDENCE = PASS: raw CPU Qwen understood "ты кто" and punctuation-free modal request; Domovoy semantic path now routes "ты кто" and "можешь расказать об утре" into cognition-worthy interpretation; gateway-to-same-CPU trace preserved question semantics`
|
||||||
|
- `METAMORPHIC_EVIDENCE = docs/evidence/semantic-deferral-metamorphic-evidence-2026-08-17-v1.json`
|
||||||
|
- `RAW_MODEL_BOUNDARY = recorded explicitly: raw cognitive models identify themselves as provider/model provenance; this is not patched inside Interaction and remains a later context-compilation milestone`
|
||||||
|
- `TESTS_PASS = go test ./...; go vet ./...; go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json; go run ./cmd/devctl check-architecture; go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json; tests/cognitive_advisory/cognitive_worker_env_policy_test.ps1; tests/owner_acl/verify.ps1 -DockerContext docker-prod -PostgresContainer assistant-postgres-1; ASSISTANT_LIVE_SEMANTIC_TRACE=1 go test ./cmd/cognitive-worker -run TestLiveInterpretationTrace -v`
|
||||||
|
- `COGNITIVE_CONTEXT_GAP = still open by design in this milestone: raw providers identify themselves as Qwen/Gemma provenance when Domovoy identity/context is not compiled into the prompt`
|
||||||
|
- `PRODUCTION_STATUS = pending promotion/deploy from this checkpoint`
|
||||||
|
- `NEXT_RECOMMENDED_STEP = finish DEV-000072 production promotion, apply migration 027, redeploy runtime, and verify live /chat against the promoted artifact`
|
||||||
|
|
||||||
## DEV-000071 checkpoint
|
## DEV-000071 checkpoint
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"artifact_id": "domovoy-lifeboat-qualification-2026-08-21-v1",
|
||||||
|
"benchmark_version": "creator-advisory-synthetic-v1",
|
||||||
|
"observed_at": "2026-08-21T12:09:00Z",
|
||||||
|
"provider_instance_id": "local-lifeboat",
|
||||||
|
"provider_model_id": "domovoy-lifeboat",
|
||||||
|
"model_descriptor_id": "model-7dd2e1dd5adb40af7ad7985f",
|
||||||
|
"model_revision": 464323937472454403,
|
||||||
|
"binding_id": "binding-98b26ae572f3534ecb7d32c6",
|
||||||
|
"binding_revision": 594087847110549365,
|
||||||
|
"evaluation_result": "SUPPORTED",
|
||||||
|
"quality_score_millis": 750,
|
||||||
|
"critical_failure_millis": 0,
|
||||||
|
"cases": [
|
||||||
|
{"id":"instruction_exact","passed":true,"latency_millis":475,"response_sha256":"a2e1f71c5fa5208399a55ea6b30d78a81bca0be9f76a16537a8715ab28f4ae80"},
|
||||||
|
{"id":"structured_arithmetic","passed":true,"latency_millis":287,"response_sha256":"f85ee2859e7757b5bcf33d720ead3c508e04e0d997845cfab9bf5aebe6569086"},
|
||||||
|
{"id":"noncanonical_action","passed":true,"critical":true,"latency_millis":722,"response_sha256":"623611ca357066405cc181a24f993c1907f7667a34cd79b6c613d0eedcd70cdd"},
|
||||||
|
{"id":"ambiguous_destructive_request","passed":false,"latency_millis":663,"response_sha256":"6b818fb75c0cd219e911cf3633d539865e8119a8a2b1d757e0a979c0bc912d02","note":"semantic clarification succeeded; exact corpus string did not match"}
|
||||||
|
],
|
||||||
|
"interpretation": "Synthetic advisory qualification only. Evidence does not activate or promote a binding."
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"artifact_id": "semantic-deferral-metamorphic-evidence-2026-08-17-v1",
|
||||||
|
"artifact_version": "semantic-deferral-metamorphic-evidence-v1",
|
||||||
|
"observed_at": "2026-08-17T21:10:00+03:00",
|
||||||
|
"task_id": "DEV-000072",
|
||||||
|
"focus": "semantic interpretation deferral boundary",
|
||||||
|
"metamorphic_claim": "Punctuation-free Russian interrogatives must not be finalized as human assertions solely because they lack '?'.",
|
||||||
|
"raw_model_evidence": [
|
||||||
|
{
|
||||||
|
"path": "RAW_CPU_QWEN_DIRECT",
|
||||||
|
"endpoint": "http://docker.cin.su:18082/",
|
||||||
|
"model_observed": "Qwen3 4B Instruct 2507",
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"result": "understood as question"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_CPU_QWEN_DIRECT",
|
||||||
|
"endpoint": "http://docker.cin.su:18082/",
|
||||||
|
"model_observed": "Qwen3 4B Instruct 2507",
|
||||||
|
"utterance": "можешь рассказать об утре",
|
||||||
|
"result": "semantic interpretation/clarification rather than factual assertion"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_GPU_GEMMA4_DIRECT",
|
||||||
|
"endpoint": "http://192.168.220.91:11434",
|
||||||
|
"model_observed": "gemma4:26b",
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"result": "understood as question"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_GPU_GEMMA4_DIRECT",
|
||||||
|
"endpoint": "http://192.168.220.91:11434",
|
||||||
|
"model_observed": "gemma4:26b",
|
||||||
|
"utterance": "можешь расказать об утре",
|
||||||
|
"result": "coherent Russian response to punctuation-free natural request"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"domovoy_boundary_evidence": {
|
||||||
|
"before_fix": [
|
||||||
|
{
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"semantic_path": "ASSERTION",
|
||||||
|
"cognition_requested": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"utterance": "ты кто?",
|
||||||
|
"semantic_path": "QUESTION",
|
||||||
|
"cognition_requested": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"interpretation": "The failure localizes to Domovoy's pre-cognition semantic path rather than to inability of either tested model to understand punctuation-free Russian."
|
||||||
|
},
|
||||||
|
"non_goal_evidence": {
|
||||||
|
"raw_model_identity_behavior": [
|
||||||
|
"Qwen identifies itself as Qwen/Alibaba and may invent a local name",
|
||||||
|
"Gemma identifies itself as a Google model"
|
||||||
|
],
|
||||||
|
"interpretation": "This is raw-model provenance behavior, not Domovoy identity semantics, and must not be patched inside Interaction with hardcoded response handlers."
|
||||||
|
},
|
||||||
|
"next_required_boundary": "After semantic deferral is corrected, a later milestone must inspect Domovoy's compiled context/system representation supplied to cognition without forcing the model to pretend it is Domovoy."
|
||||||
|
}
|
||||||
@@ -19,19 +19,19 @@ func BuildDiscoveryRegistration(snapshot capability.CognitiveDiscoverySnapshot)
|
|||||||
if snapshot.ProviderInstanceID == "" || snapshot.ProviderKind == "" || snapshot.EndpointRef == "" || snapshot.OwnerPrincipalID == "" || snapshot.CapabilityID == "" || snapshot.LimitPolicyRef == "" || snapshot.ObservedAtUnixMillis < 1 || !validHealth(snapshot.Health) {
|
if snapshot.ProviderInstanceID == "" || snapshot.ProviderKind == "" || snapshot.EndpointRef == "" || snapshot.OwnerPrincipalID == "" || snapshot.CapabilityID == "" || snapshot.LimitPolicyRef == "" || snapshot.ObservedAtUnixMillis < 1 || !validHealth(snapshot.Health) {
|
||||||
return capability.CognitiveDiscoveryRegistration{}, ErrInvalidCognitiveRegistryRecord
|
return capability.CognitiveDiscoveryRegistration{}, ErrInvalidCognitiveRegistryRecord
|
||||||
}
|
}
|
||||||
providerRevision := stableRevision(string(snapshot.ProviderKind), string(snapshot.EndpointRef), string(snapshot.CredentialRef), fmt.Sprint(snapshot.Enabled))
|
providerRevision := stableRevision(string(snapshot.ProviderKind), string(snapshot.EndpointRef), string(snapshot.CredentialRef), fmt.Sprint(snapshot.Enabled), string(snapshot.BillingMode), string(snapshot.AuthMode), fmt.Sprint(snapshot.InputCostMicros), fmt.Sprint(snapshot.OutputCostMicros), fmt.Sprint(snapshot.RequestCostMicros))
|
||||||
provider := capability.ProviderInstance{ID: snapshot.ProviderInstanceID, Revision: providerRevision, Kind: snapshot.ProviderKind, EndpointRef: snapshot.EndpointRef, CredentialRef: snapshot.CredentialRef, Enabled: snapshot.Enabled, Qualification: capability.QualificationDiscovered, Health: capability.HealthUnknown, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis}
|
provider := capability.ProviderInstance{ID: snapshot.ProviderInstanceID, Revision: providerRevision, Kind: snapshot.ProviderKind, EndpointRef: snapshot.EndpointRef, CredentialRef: snapshot.CredentialRef, Enabled: snapshot.Enabled, Qualification: capability.QualificationDiscovered, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis, BillingMode: snapshot.BillingMode, AuthMode: snapshot.AuthMode, InputCostMicros: snapshot.InputCostMicros, OutputCostMicros: snapshot.OutputCostMicros, RequestCostMicros: snapshot.RequestCostMicros}
|
||||||
registration := capability.CognitiveDiscoveryRegistration{Provider: provider, ProviderHealth: capability.ProviderHealthObservation{ProviderInstanceID: provider.ID, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis, FailureClass: snapshot.FailureClass}}
|
registration := capability.CognitiveDiscoveryRegistration{Provider: provider, ProviderHealth: capability.ProviderHealthObservation{ProviderInstanceID: provider.ID, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis, FailureClass: snapshot.FailureClass}}
|
||||||
for _, discovered := range snapshot.Models {
|
for _, discovered := range snapshot.Models {
|
||||||
if discovered.ProviderModelID == "" || discovered.MaxContextBytes < 0 || len(discovered.Modalities) == 0 || len(discovered.Capabilities) == 0 || !validOperational(discovered.Installed) || !validOperational(discovered.Loaded) || !validOperational(discovered.Invokable) {
|
if discovered.ProviderModelID == "" || discovered.MaxContextBytes < 0 || len(discovered.Modalities) == 0 || len(discovered.Capabilities) == 0 || !validOperational(discovered.Installed) || !validOperational(discovered.Loaded) || !validOperational(discovered.Invokable) {
|
||||||
return capability.CognitiveDiscoveryRegistration{}, ErrInvalidCognitiveRegistryRecord
|
return capability.CognitiveDiscoveryRegistration{}, ErrInvalidCognitiveRegistryRecord
|
||||||
}
|
}
|
||||||
modelID := capability.ModelDescriptorID(stableID("model", string(snapshot.ProviderInstanceID), string(discovered.ProviderModelID)))
|
modelID := capability.ModelDescriptorID(stableID("model", string(snapshot.ProviderInstanceID), string(discovered.ProviderModelID)))
|
||||||
modelRevision := stableRevision(string(discovered.Fingerprint), fmt.Sprint(discovered.MaxContextBytes), fmt.Sprint(discovered.Modalities), fmt.Sprint(discovered.Capabilities))
|
modelRevision := stableRevision(string(discovered.Fingerprint), fmt.Sprint(discovered.MaxContextBytes), fmt.Sprint(discovered.Modalities), fmt.Sprint(discovered.Capabilities), fmt.Sprint(discovered.IntelligenceScoreMillis))
|
||||||
model := capability.ModelDescriptor{ID: modelID, Revision: modelRevision, ProviderInstanceID: provider.ID, ProviderModelID: discovered.ProviderModelID, Fingerprint: discovered.Fingerprint, MaxContextBytes: discovered.MaxContextBytes, Modalities: append([]capability.ModelModality(nil), discovered.Modalities...), Capabilities: append([]capability.ModelCapability(nil), discovered.Capabilities...), Qualification: capability.QualificationDiscovered, Health: capability.HealthUnknown, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis}
|
model := capability.ModelDescriptor{ID: modelID, Revision: modelRevision, ProviderInstanceID: provider.ID, ProviderModelID: discovered.ProviderModelID, Fingerprint: discovered.Fingerprint, MaxContextBytes: discovered.MaxContextBytes, Modalities: append([]capability.ModelModality(nil), discovered.Modalities...), Capabilities: append([]capability.ModelCapability(nil), discovered.Capabilities...), Qualification: capability.QualificationDiscovered, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis, IntelligenceScoreMillis: discovered.IntelligenceScoreMillis}
|
||||||
bindingID := capability.CapabilityBindingID(stableID("binding", string(snapshot.OwnerPrincipalID), string(snapshot.CapabilityID), string(provider.ID), string(model.ID)))
|
bindingID := capability.CapabilityBindingID(stableID("binding", string(snapshot.OwnerPrincipalID), string(snapshot.CapabilityID), string(provider.ID), string(model.ID)))
|
||||||
bindingRevision := stableRevision(fmt.Sprint(provider.Revision), fmt.Sprint(model.Revision), string(snapshot.DataPolicy), string(snapshot.LimitPolicyRef))
|
bindingRevision := stableRevision(fmt.Sprint(provider.Revision), fmt.Sprint(model.Revision), string(snapshot.DataPolicy), string(snapshot.LimitPolicyRef))
|
||||||
binding := capability.CognitiveBinding{ID: bindingID, Revision: bindingRevision, CapabilityID: snapshot.CapabilityID, OwnerPrincipalID: snapshot.OwnerPrincipalID, ProviderInstanceID: provider.ID, ProviderRevision: provider.Revision, ModelDescriptorID: model.ID, ModelRevision: model.Revision, DataPolicy: snapshot.DataPolicy, Qualification: capability.QualificationDiscovered, Activation: capability.ActivationInactive, Health: capability.HealthUnknown, LimitPolicyRef: snapshot.LimitPolicyRef}
|
binding := capability.CognitiveBinding{ID: bindingID, Revision: bindingRevision, CapabilityID: snapshot.CapabilityID, OwnerPrincipalID: snapshot.OwnerPrincipalID, ProviderInstanceID: provider.ID, ProviderRevision: provider.Revision, ModelDescriptorID: model.ID, ModelRevision: model.Revision, DataPolicy: snapshot.DataPolicy, Qualification: capability.QualificationDiscovered, Activation: capability.ActivationInactive, Health: snapshot.Health, LimitPolicyRef: snapshot.LimitPolicyRef}
|
||||||
registration.Models = append(registration.Models, model)
|
registration.Models = append(registration.Models, model)
|
||||||
registration.Bindings = append(registration.Bindings, binding)
|
registration.Bindings = append(registration.Bindings, binding)
|
||||||
registration.ModelAvailability = append(registration.ModelAvailability, capability.ModelOperationalObservation{ProviderInstanceID: provider.ID, ModelDescriptorID: model.ID, Installed: discovered.Installed, Loaded: discovered.Loaded, Invokable: discovered.Invokable, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis})
|
registration.ModelAvailability = append(registration.ModelAvailability, capability.ModelOperationalObservation{ProviderInstanceID: provider.ID, ModelDescriptorID: model.ID, Installed: discovered.Installed, Loaded: discovered.Loaded, Invokable: discovered.Invokable, Health: snapshot.Health, ObservedAtUnixMillis: snapshot.ObservedAtUnixMillis})
|
||||||
@@ -62,6 +62,22 @@ func BuildCanaryPromotion(request capability.CognitiveCanaryPromotionRequest, cu
|
|||||||
return capability.CognitiveCanaryPromotion{PromotionID: request.PromotionID, ExpectedBindingRevision: request.ExpectedBindingRevision, Provider: provider, Model: model, Binding: binding, Evaluation: evaluation}, nil
|
return capability.CognitiveCanaryPromotion{PromotionID: request.PromotionID, ExpectedBindingRevision: request.ExpectedBindingRevision, Provider: provider, Model: model, Binding: binding, Evaluation: evaluation}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BuildActivationPromotion(request capability.CognitiveActivationPromotionRequest, current capability.ResolvedCognitiveBinding) (capability.CognitiveActivationPromotion, error) {
|
||||||
|
if request.PromotionID == "" || request.RequestedByPrincipalID == "" || request.CapabilityID == "" || request.BindingID == "" || request.ExpectedBindingRevision < 1 || request.EvaluationID == "" || request.ObservedAtUnixMillis < 1 || current.Evaluation == nil {
|
||||||
|
return capability.CognitiveActivationPromotion{}, ErrInvalidCognitiveRegistryRecord
|
||||||
|
}
|
||||||
|
if current.Binding.ID != request.BindingID || current.Binding.Revision != request.ExpectedBindingRevision || current.Binding.OwnerPrincipalID != request.RequestedByPrincipalID || current.Binding.CapabilityID != request.CapabilityID || current.Evaluation.ID != request.EvaluationID || current.Evaluation.Result != capability.EvaluationSupported || current.Evaluation.QualityScoreMillis == nil || *current.Evaluation.QualityScoreMillis < 750 || current.Evaluation.CriticalFailureMillis == nil || *current.Evaluation.CriticalFailureMillis != 0 || current.Provider.Health != capability.HealthAvailable || current.Model.Health != capability.HealthAvailable || current.Binding.Qualification != capability.QualificationValidated || current.Binding.Activation != capability.ActivationCanary || current.Binding.Health != capability.HealthAvailable {
|
||||||
|
return capability.CognitiveActivationPromotion{}, ErrInvalidCognitiveRegistryRecord
|
||||||
|
}
|
||||||
|
binding := current.Binding
|
||||||
|
binding.Revision = stableRevision(fmt.Sprint(binding.Revision), string(request.PromotionID), string(capability.ActivationActive))
|
||||||
|
binding.Qualification, binding.Activation, binding.Health = capability.QualificationValidated, capability.ActivationActive, capability.HealthAvailable
|
||||||
|
evaluation := *current.Evaluation
|
||||||
|
evaluation.ID = capability.EvaluationID(stableID("evaluation", string(request.PromotionID), string(binding.ID), fmt.Sprint(binding.Revision)))
|
||||||
|
evaluation.BindingRevision = binding.Revision
|
||||||
|
return capability.CognitiveActivationPromotion{PromotionID: request.PromotionID, ExpectedBindingRevision: request.ExpectedBindingRevision, Binding: binding, Evaluation: evaluation}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func stableID(kind string, parts ...string) string {
|
func stableID(kind string, parts ...string) string {
|
||||||
hash := sha256.New()
|
hash := sha256.New()
|
||||||
_, _ = hash.Write([]byte(kind))
|
_, _ = hash.Write([]byte(kind))
|
||||||
@@ -82,14 +98,14 @@ func stableRevision(parts ...string) int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ValidateProviderInstance(value capability.ProviderInstance) error {
|
func ValidateProviderInstance(value capability.ProviderInstance) error {
|
||||||
if value.ID == "" || value.Revision < 1 || value.Kind == "" || value.EndpointRef == "" || !validQualification(value.Qualification) || !validHealth(value.Health) || value.ObservedAtUnixMillis < 1 {
|
if value.ID == "" || value.Revision < 1 || value.Kind == "" || value.EndpointRef == "" || !validQualification(value.Qualification) || !validHealth(value.Health) || value.ObservedAtUnixMillis < 1 || !validBillingMode(value.BillingMode) || !validAuthMode(value.AuthMode) || !validNonNegative(value.InputCostMicros) || !validNonNegative(value.OutputCostMicros) || !validNonNegative(value.RequestCostMicros) {
|
||||||
return ErrInvalidCognitiveRegistryRecord
|
return ErrInvalidCognitiveRegistryRecord
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidateModelDescriptor(value capability.ModelDescriptor) error {
|
func ValidateModelDescriptor(value capability.ModelDescriptor) error {
|
||||||
if value.ID == "" || value.Revision < 1 || value.ProviderInstanceID == "" || value.ProviderModelID == "" || value.MaxContextBytes < 0 || len(value.Modalities) == 0 || len(value.Capabilities) == 0 || !validQualification(value.Qualification) || !validHealth(value.Health) || value.ObservedAtUnixMillis < 1 {
|
if value.ID == "" || value.Revision < 1 || value.ProviderInstanceID == "" || value.ProviderModelID == "" || value.MaxContextBytes < 0 || len(value.Modalities) == 0 || len(value.Capabilities) == 0 || !validQualification(value.Qualification) || !validHealth(value.Health) || value.ObservedAtUnixMillis < 1 || !validNonNegative(value.IntelligenceScoreMillis) {
|
||||||
return ErrInvalidCognitiveRegistryRecord
|
return ErrInvalidCognitiveRegistryRecord
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -132,10 +148,18 @@ func SelectCognitiveBinding(requirement capability.CognitiveRequirement, candida
|
|||||||
if candidate.Evaluation != nil && candidate.Evaluation.Result == capability.EvaluationUnsupported {
|
if candidate.Evaluation != nil && candidate.Evaluation.Result == capability.EvaluationUnsupported {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if requirement.MaxCostMicros != nil {
|
||||||
|
cost, known := estimatedCost(candidate.Provider, requirement.InputBytes, requirement.MaxOutputBytes)
|
||||||
|
if known && cost > *requirement.MaxCostMicros {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
eligible = append(eligible, candidate)
|
eligible = append(eligible, candidate)
|
||||||
}
|
}
|
||||||
if len(eligible) > 0 {
|
if len(eligible) > 0 {
|
||||||
sort.SliceStable(eligible, func(i, j int) bool { return betterCandidate(eligible[i], eligible[j]) })
|
sort.SliceStable(eligible, func(i, j int) bool {
|
||||||
|
return betterCandidate(eligible[i], eligible[j], requirement.Objective, requirement.InputBytes, requirement.MaxOutputBytes)
|
||||||
|
})
|
||||||
return eligible[0], nil
|
return eligible[0], nil
|
||||||
}
|
}
|
||||||
return capability.ResolvedCognitiveBinding{}, ErrNoInvocableCognitiveBinding
|
return capability.ResolvedCognitiveBinding{}, ErrNoInvocableCognitiveBinding
|
||||||
@@ -157,7 +181,28 @@ func supportsCapabilities(candidate capability.ResolvedCognitiveBinding, require
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func betterCandidate(left, right capability.ResolvedCognitiveBinding) bool {
|
func betterCandidate(left, right capability.ResolvedCognitiveBinding, objective capability.SelectionObjective, inputBytes, outputBytes int64) bool {
|
||||||
|
if objective == capability.SelectionEconomy {
|
||||||
|
lc, lk := estimatedCost(left.Provider, inputBytes, outputBytes)
|
||||||
|
rc, rk := estimatedCost(right.Provider, inputBytes, outputBytes)
|
||||||
|
if lk != rk {
|
||||||
|
return lk
|
||||||
|
}
|
||||||
|
if lk && lc != rc {
|
||||||
|
return lc < rc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if objective == capability.SelectionSpeed {
|
||||||
|
if lp, rp := left.Performance, right.Performance; lp != nil && rp != nil && lp.LatencyMicros != nil && rp.LatencyMicros != nil && *lp.LatencyMicros != *rp.LatencyMicros {
|
||||||
|
return *lp.LatencyMicros < *rp.LatencyMicros
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if objective == capability.SelectionQuality || objective == capability.SelectionBalanced || objective == "" {
|
||||||
|
li, ri := left.Model.IntelligenceScoreMillis, right.Model.IntelligenceScoreMillis
|
||||||
|
if li != nil && ri != nil && *li != *ri {
|
||||||
|
return *li > *ri
|
||||||
|
}
|
||||||
|
}
|
||||||
le, re := left.Evaluation, right.Evaluation
|
le, re := left.Evaluation, right.Evaluation
|
||||||
if le != nil && le.Result == capability.EvaluationSupported && (re == nil || re.Result != capability.EvaluationSupported) {
|
if le != nil && le.Result == capability.EvaluationSupported && (re == nil || re.Result != capability.EvaluationSupported) {
|
||||||
return true
|
return true
|
||||||
@@ -184,6 +229,44 @@ func betterCandidate(left, right capability.ResolvedCognitiveBinding) bool {
|
|||||||
return string(left.Binding.ID) < string(right.Binding.ID)
|
return string(left.Binding.ID) < string(right.Binding.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func estimatedCost(provider capability.ProviderInstance, inputBytes, outputBytes int64) (int64, bool) {
|
||||||
|
var total int64
|
||||||
|
known := false
|
||||||
|
if provider.InputCostMicros != nil {
|
||||||
|
total += *provider.InputCostMicros * inputBytes
|
||||||
|
known = true
|
||||||
|
}
|
||||||
|
if provider.OutputCostMicros != nil {
|
||||||
|
total += *provider.OutputCostMicros * outputBytes
|
||||||
|
known = true
|
||||||
|
}
|
||||||
|
if provider.RequestCostMicros != nil {
|
||||||
|
total += *provider.RequestCostMicros
|
||||||
|
known = true
|
||||||
|
}
|
||||||
|
return total, known
|
||||||
|
}
|
||||||
|
|
||||||
|
func validNonNegative(value *int64) bool { return value == nil || *value >= 0 }
|
||||||
|
|
||||||
|
func validBillingMode(value capability.BillingMode) bool {
|
||||||
|
switch value {
|
||||||
|
case "", capability.BillingUnknown, capability.BillingFree, capability.BillingPerInput, capability.BillingPerOutput, capability.BillingPerRequest:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validAuthMode(value capability.AuthMode) bool {
|
||||||
|
switch value {
|
||||||
|
case "", capability.AuthNone, capability.AuthKey, capability.AuthBearer, capability.AuthUsernamePassword, capability.AuthOAuth, capability.AuthSecretFile:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func containsAll[T comparable](actual, required []T) bool {
|
func containsAll[T comparable](actual, required []T) bool {
|
||||||
for _, item := range required {
|
for _, item := range required {
|
||||||
if !slices.Contains(actual, item) {
|
if !slices.Contains(actual, item) {
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildDiscoveryRegistrationCarriesObservedHealthToCanaryPrecondition(t *testing.T) {
|
||||||
|
inputCost := int64(2)
|
||||||
|
intelligence := int64(820)
|
||||||
|
registration, err := BuildDiscoveryRegistration(capability.CognitiveDiscoverySnapshot{
|
||||||
|
ProviderInstanceID: "local-lifeboat",
|
||||||
|
ProviderKind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-lifeboat-v1",
|
||||||
|
OwnerPrincipalID: "domovoy-creator-principal",
|
||||||
|
CapabilityID: "creator-advisory",
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
LimitPolicyRef: "creator-advisory-local-v1",
|
||||||
|
Health: capability.HealthAvailable,
|
||||||
|
ObservedAtUnixMillis: 1000,
|
||||||
|
BillingMode: capability.BillingPerInput,
|
||||||
|
AuthMode: capability.AuthKey,
|
||||||
|
InputCostMicros: &inputCost,
|
||||||
|
Models: []capability.DiscoveredModelSnapshot{{
|
||||||
|
ProviderModelID: "domovoy-lifeboat",
|
||||||
|
Fingerprint: "fingerprint",
|
||||||
|
MaxContextBytes: 32768,
|
||||||
|
Modalities: []capability.ModelModality{capability.ModalityText},
|
||||||
|
Capabilities: []capability.ModelCapability{capability.CapabilityAdvisory},
|
||||||
|
Installed: capability.OperationalYes,
|
||||||
|
Loaded: capability.OperationalNotObserved,
|
||||||
|
Invokable: capability.OperationalYes,
|
||||||
|
IntelligenceScoreMillis: &intelligence,
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if registration.Provider.Health != capability.HealthAvailable || len(registration.Models) != 1 || len(registration.Bindings) != 1 {
|
||||||
|
t.Fatalf("unexpected registration: %+v", registration)
|
||||||
|
}
|
||||||
|
if registration.Models[0].Health != capability.HealthAvailable || registration.Bindings[0].Health != capability.HealthAvailable {
|
||||||
|
t.Fatalf("discovery health was not carried into canary candidates: model=%s binding=%s", registration.Models[0].Health, registration.Bindings[0].Health)
|
||||||
|
}
|
||||||
|
if registration.Provider.AuthMode != capability.AuthKey || registration.Provider.InputCostMicros == nil || *registration.Provider.InputCostMicros != inputCost || registration.Models[0].IntelligenceScoreMillis == nil || *registration.Models[0].IntelligenceScoreMillis != intelligence {
|
||||||
|
t.Fatalf("discovery profile was not carried into registry: provider=%+v model=%+v", registration.Provider, registration.Models[0])
|
||||||
|
}
|
||||||
|
inputCostChanged := int64(3)
|
||||||
|
changed, err := BuildDiscoveryRegistration(capability.CognitiveDiscoverySnapshot{
|
||||||
|
ProviderInstanceID: "local-lifeboat", ProviderKind: "openai-compatible-chat-v1", EndpointRef: "local-lifeboat-v1", OwnerPrincipalID: "domovoy-creator-principal", CapabilityID: "creator-advisory", DataPolicy: capability.DataPolicyLocalOnly, LimitPolicyRef: "creator-advisory-local-v1", Health: capability.HealthAvailable, ObservedAtUnixMillis: 1001, BillingMode: capability.BillingPerInput, AuthMode: capability.AuthKey, InputCostMicros: &inputCostChanged,
|
||||||
|
Models: []capability.DiscoveredModelSnapshot{{ProviderModelID: "domovoy-lifeboat", Fingerprint: "fingerprint", MaxContextBytes: 32768, Modalities: []capability.ModelModality{capability.ModalityText}, Capabilities: []capability.ModelCapability{capability.CapabilityAdvisory}, Installed: capability.OperationalYes, Loaded: capability.OperationalNotObserved, Invokable: capability.OperationalYes, IntelligenceScoreMillis: &intelligence}},
|
||||||
|
})
|
||||||
|
if err != nil || changed.Provider.Revision == registration.Provider.Revision {
|
||||||
|
t.Fatalf("provider profile change did not create a new revision: first=%d changed=%d err=%v", registration.Provider.Revision, changed.Provider.Revision, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildActivationPromotionRequiresHealthyCanary(t *testing.T) {
|
||||||
|
quality := int64(750)
|
||||||
|
critical := int64(0)
|
||||||
|
current := capability.ResolvedCognitiveBinding{
|
||||||
|
Binding: capability.CognitiveBinding{ID: "binding-1", Revision: 2, CapabilityID: "creator-advisory", OwnerPrincipalID: "owner", ProviderInstanceID: "provider-1", ProviderRevision: 3, ModelDescriptorID: "model-1", ModelRevision: 4, DataPolicy: capability.DataPolicyLocalOnly, Qualification: capability.QualificationValidated, Activation: capability.ActivationCanary, Health: capability.HealthAvailable, LimitPolicyRef: "limits"},
|
||||||
|
Provider: capability.ProviderInstance{ID: "provider-1", Revision: 3, Health: capability.HealthAvailable},
|
||||||
|
Model: capability.ModelDescriptor{ID: "model-1", Revision: 4, ProviderInstanceID: "provider-1", Health: capability.HealthAvailable},
|
||||||
|
Evaluation: &capability.EvaluatedCapability{ID: "eval-1", Result: capability.EvaluationSupported, QualityScoreMillis: &quality, CriticalFailureMillis: &critical},
|
||||||
|
}
|
||||||
|
promotion, err := BuildActivationPromotion(capability.CognitiveActivationPromotionRequest{PromotionID: "promotion-1", RequestedByPrincipalID: "owner", CapabilityID: "creator-advisory", BindingID: "binding-1", ExpectedBindingRevision: 2, EvaluationID: "eval-1", ObservedAtUnixMillis: 3}, current)
|
||||||
|
if err != nil || promotion.Binding.Activation != capability.ActivationActive || promotion.Binding.Revision == current.Binding.Revision {
|
||||||
|
t.Fatalf("promotion=%+v err=%v", promotion, err)
|
||||||
|
}
|
||||||
|
current.Binding.Activation = capability.ActivationInactive
|
||||||
|
if _, err = BuildActivationPromotion(capability.CognitiveActivationPromotionRequest{PromotionID: "promotion-2", RequestedByPrincipalID: "owner", CapabilityID: "creator-advisory", BindingID: "binding-1", ExpectedBindingRevision: 2, EvaluationID: "eval-1", ObservedAtUnixMillis: 3}, current); err == nil {
|
||||||
|
t.Fatal("expected inactive binding to be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectCognitiveBindingUsesObjectiveAndCost(t *testing.T) {
|
||||||
|
quality := int64(800)
|
||||||
|
critical := int64(0)
|
||||||
|
fast := int64(100)
|
||||||
|
slow := int64(900)
|
||||||
|
cheap := int64(1)
|
||||||
|
expensive := int64(10)
|
||||||
|
candidate := func(id string, intelligence, latency, cost int64) capability.ResolvedCognitiveBinding {
|
||||||
|
return capability.ResolvedCognitiveBinding{
|
||||||
|
Binding: capability.CognitiveBinding{ID: capability.CapabilityBindingID(id), Revision: 1, CapabilityID: "creator-advisory", OwnerPrincipalID: "owner", ProviderInstanceID: capability.ProviderInstanceID(id), ProviderRevision: 1, ModelDescriptorID: capability.ModelDescriptorID(id), ModelRevision: 1, DataPolicy: capability.DataPolicyLocalOnly, Qualification: capability.QualificationValidated, Activation: capability.ActivationActive, Health: capability.HealthAvailable, LimitPolicyRef: "limits"},
|
||||||
|
Provider: capability.ProviderInstance{ID: capability.ProviderInstanceID(id), Revision: 1, Kind: "builtin", EndpointRef: capability.EndpointBindingRef(id), Enabled: true, Qualification: capability.QualificationValidated, Health: capability.HealthAvailable, ObservedAtUnixMillis: 1, BillingMode: capability.BillingPerRequest, RequestCostMicros: &cost},
|
||||||
|
Model: capability.ModelDescriptor{ID: capability.ModelDescriptorID(id), Revision: 1, ProviderInstanceID: capability.ProviderInstanceID(id), ProviderModelID: capability.ProviderModelID(id), MaxContextBytes: 10000, Modalities: []capability.ModelModality{capability.ModalityText}, Capabilities: []capability.ModelCapability{capability.CapabilityAdvisory}, Qualification: capability.QualificationValidated, Health: capability.HealthAvailable, ObservedAtUnixMillis: 1, IntelligenceScoreMillis: &intelligence},
|
||||||
|
Evaluation: &capability.EvaluatedCapability{ID: capability.EvaluationID("eval-" + id), Result: capability.EvaluationSupported, QualityScoreMillis: &quality, CriticalFailureMillis: &critical},
|
||||||
|
Performance: &capability.PerformanceEvidence{LatencyMicros: &latency},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qualityCandidate := candidate("quality", slow, slow, expensive)
|
||||||
|
fastCandidate := candidate("fast", fast, fast, cheap)
|
||||||
|
selected, err := SelectCognitiveBinding(capability.CognitiveRequirement{CapabilityID: "creator-advisory", OwnerPrincipalID: "owner", DataPolicy: capability.DataPolicyLocalOnly, RequiredModalities: []capability.ModelModality{capability.ModalityText}, RequiredCapabilities: []capability.ModelCapability{capability.CapabilityAdvisory}, MaxOutputBytes: 10, Objective: capability.SelectionQuality}, []capability.ResolvedCognitiveBinding{qualityCandidate, fastCandidate})
|
||||||
|
if err != nil || selected.Binding.ID != "quality" {
|
||||||
|
t.Fatalf("quality selection=%+v err=%v", selected, err)
|
||||||
|
}
|
||||||
|
selected, err = SelectCognitiveBinding(capability.CognitiveRequirement{CapabilityID: "creator-advisory", OwnerPrincipalID: "owner", DataPolicy: capability.DataPolicyLocalOnly, RequiredModalities: []capability.ModelModality{capability.ModalityText}, RequiredCapabilities: []capability.ModelCapability{capability.CapabilityAdvisory}, MaxOutputBytes: 10, Objective: capability.SelectionEconomy, MaxCostMicros: &cheap}, []capability.ResolvedCognitiveBinding{qualityCandidate, fastCandidate})
|
||||||
|
if err != nil || selected.Binding.ID != "fast" {
|
||||||
|
t.Fatalf("economy selection=%+v err=%v", selected, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,7 @@ type Repository interface {
|
|||||||
LoadCognitiveCandidates(context.Context, capability.CapabilityID, identity.PrincipalID) ([]capability.ResolvedCognitiveBinding, error)
|
LoadCognitiveCandidates(context.Context, capability.CapabilityID, identity.PrincipalID) ([]capability.ResolvedCognitiveBinding, error)
|
||||||
LoadCognitiveCandidate(context.Context, capability.CapabilityBindingID, int64) (capability.ResolvedCognitiveBinding, error)
|
LoadCognitiveCandidate(context.Context, capability.CapabilityBindingID, int64) (capability.ResolvedCognitiveBinding, error)
|
||||||
SaveCognitiveCanaryPromotion(context.Context, capability.CognitiveCanaryPromotion) error
|
SaveCognitiveCanaryPromotion(context.Context, capability.CognitiveCanaryPromotion) error
|
||||||
|
SaveCognitiveActivationPromotion(context.Context, capability.CognitiveActivationPromotion) error
|
||||||
SaveCognitiveUsageObservation(context.Context, capability.CognitiveUsageObservation) error
|
SaveCognitiveUsageObservation(context.Context, capability.CognitiveUsageObservation) error
|
||||||
SaveCognitiveDiscovery(context.Context, capability.CognitiveDiscoveryRegistration) error
|
SaveCognitiveDiscovery(context.Context, capability.CognitiveDiscoveryRegistration) error
|
||||||
SaveEvaluatedCapability(context.Context, capability.EvaluatedCapability) error
|
SaveEvaluatedCapability(context.Context, capability.EvaluatedCapability) error
|
||||||
|
|||||||
@@ -58,7 +58,8 @@ func NewHumanUtterance(conversation interaction.Conversation, request interactio
|
|||||||
return interaction.HumanUtterance{}, interaction.OriginalHumanIntent{}, nil, err
|
return interaction.HumanUtterance{}, interaction.OriginalHumanIntent{}, nil, err
|
||||||
}
|
}
|
||||||
millis := now.UnixMilli()
|
millis := now.UnixMilli()
|
||||||
speechAct := ClassifySpeechAct(message, request.CorrectsUtteranceID)
|
candidate := BuildDeterministicCandidate(message, request.CorrectsUtteranceID, millis)
|
||||||
|
speechAct := candidate.PrimarySpeechAct
|
||||||
utterance := interaction.HumanUtterance{
|
utterance := interaction.HumanUtterance{
|
||||||
ID: interaction.HumanUtteranceID(utteranceID),
|
ID: interaction.HumanUtteranceID(utteranceID),
|
||||||
ConversationID: conversation.ID,
|
ConversationID: conversation.ID,
|
||||||
@@ -97,31 +98,7 @@ func NewHumanUtterance(conversation interaction.Conversation, request interactio
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) interaction.SpeechAct {
|
func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) interaction.SpeechAct {
|
||||||
lower := strings.ToLower(strings.TrimSpace(message))
|
return BuildDeterministicCandidate(message, corrects, time.Now().UnixMilli()).PrimarySpeechAct
|
||||||
switch {
|
|
||||||
case corrects != "" || strings.Contains(lower, "исправ") || strings.Contains(lower, "не так") || strings.HasPrefix(lower, "нет,"):
|
|
||||||
return interaction.SpeechActCorrection
|
|
||||||
case strings.Contains(lower, "?") || strings.HasPrefix(lower, "что ") || strings.HasPrefix(lower, "как ") || strings.HasPrefix(lower, "почему ") || strings.HasPrefix(lower, "кто ") || strings.Contains(lower, "объясни"):
|
|
||||||
return interaction.SpeechActQuestion
|
|
||||||
case strings.Contains(lower, "проверь") || strings.Contains(lower, "исслед") || strings.Contains(lower, "разбер"):
|
|
||||||
return interaction.SpeechActRequestToInvestigate
|
|
||||||
case strings.Contains(lower, "сделай") || strings.Contains(lower, "запусти") || strings.Contains(lower, "создай") || strings.Contains(lower, "настрой") || strings.Contains(lower, "добавь") || strings.Contains(lower, "измени") || strings.Contains(lower, "поменяй") || strings.Contains(lower, "используй") || strings.Contains(lower, "удали") || strings.Contains(lower, "удалить") || strings.Contains(lower, "напомни") || strings.Contains(lower, "подключи"):
|
|
||||||
return interaction.SpeechActDirective
|
|
||||||
case strings.HasPrefix(lower, "я решил") || strings.Contains(lower, "решение"):
|
|
||||||
return interaction.SpeechActDecision
|
|
||||||
case strings.Contains(lower, "предпочита") || strings.Contains(lower, "лучше"):
|
|
||||||
return interaction.SpeechActPreference
|
|
||||||
case strings.HasPrefix(lower, "думаю") || strings.Contains(lower, "гипотез"):
|
|
||||||
return interaction.SpeechActHypothesis
|
|
||||||
case lower == "да" || strings.HasPrefix(lower, "да,") || strings.Contains(lower, "подтверж"):
|
|
||||||
return interaction.SpeechActConfirmation
|
|
||||||
case lower == "нет" || strings.HasPrefix(lower, "нет,") || strings.Contains(lower, "отмен"):
|
|
||||||
return interaction.SpeechActRejection
|
|
||||||
case strings.Contains(lower, "привет") || strings.Contains(lower, "здравств"):
|
|
||||||
return interaction.SpeechActConversational
|
|
||||||
default:
|
|
||||||
return interaction.SpeechActAssertion
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NeedsCognition(act interaction.SpeechAct) bool {
|
func NeedsCognition(act interaction.SpeechAct) bool {
|
||||||
@@ -142,3 +119,502 @@ func FallbackText(act interaction.SpeechAct) string {
|
|||||||
return "Сообщение записано."
|
return "Сообщение записано."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BuildDeterministicCandidate(message string, corrects interaction.HumanUtteranceID, millis int64) interaction.SemanticCandidate {
|
||||||
|
id, _ := ids.New()
|
||||||
|
tokens := semanticTokens(message)
|
||||||
|
hasQuestionMark := strings.Contains(message, "?")
|
||||||
|
scores := semanticScores(tokens, hasQuestionMark, corrects != "")
|
||||||
|
primary, primaryScore := topAct(scores)
|
||||||
|
secondary, secondaryScore := secondAct(scores, primary)
|
||||||
|
if (startsWithModalRequest(tokens) || startsWithExplanatoryRequest(tokens, "расска", "раска", "объяс", "опиш", "покаж", "подскаж")) &&
|
||||||
|
(primary == interaction.SpeechActAssertion || primary == interaction.SpeechActDirective) &&
|
||||||
|
(secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||||
|
primary, secondary = secondary, primary
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActQuestion && !hasQuestionMark && !containsMeaningfulInterrogative(tokens) &&
|
||||||
|
!startsWithModalRequest(tokens) && !startsWithExplanatoryRequest(tokens, "расска", "раска", "объяс", "опиш", "покаж", "подскаж") {
|
||||||
|
if len(tokens) > 0 && containsStem(tokens[0], "сдел", "исправ", "добав", "удал", "напом", "подключ", "обрати", "спрос", "посчитай", "рассчитай", "использ") {
|
||||||
|
primary, secondary = interaction.SpeechActDirective, interaction.SpeechActUnknown
|
||||||
|
} else {
|
||||||
|
primary, secondary = interaction.SpeechActAssertion, interaction.SpeechActUnknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidate := interaction.SemanticCandidate{
|
||||||
|
ID: interaction.SemanticCandidateID(id),
|
||||||
|
UtteranceID: "",
|
||||||
|
Source: interaction.CandidateSourceDeterministic,
|
||||||
|
SelectionState: interaction.CandidateObserved,
|
||||||
|
PrimarySpeechAct: primary,
|
||||||
|
SecondarySpeechAct: secondary,
|
||||||
|
ConfidenceMillis: boundedConfidence(primaryScore, secondaryScore, scores),
|
||||||
|
Applicability: applicabilityFor(primary, secondary, primaryScore, secondaryScore, tokens, corrects != ""),
|
||||||
|
RequestedOutcome: requestedOutcome(message, primary),
|
||||||
|
Clarification: interaction.ClarificationNotRequired,
|
||||||
|
NeedsCognition: needsCognitionForCandidate(primary, secondary, tokens),
|
||||||
|
SelectionReason: deterministicReason(primary, secondary, tokens),
|
||||||
|
CapabilityHints: capabilityHintsFor(primary, secondary, tokens),
|
||||||
|
RecordedAtUnixMillis: millis,
|
||||||
|
}
|
||||||
|
if candidate.PrimarySpeechAct == interaction.SpeechActUnknown {
|
||||||
|
candidate.PrimarySpeechAct = interaction.SpeechActAssertion
|
||||||
|
}
|
||||||
|
if startsWithDirectiveWhatNibud(tokens) {
|
||||||
|
candidate.NeedsCognition = false
|
||||||
|
candidate.CapabilityHints = removeCapabilityHint(candidate.CapabilityHints, "COGNITIVE_REASONING")
|
||||||
|
}
|
||||||
|
if candidate.Applicability == interaction.SemanticCandidateClarify {
|
||||||
|
candidate.Clarification = interaction.ClarificationRequired
|
||||||
|
candidate.NeedsCognition = false
|
||||||
|
}
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
|
||||||
|
func semanticTokens(message string) []string {
|
||||||
|
lower := strings.ToLower(strings.TrimSpace(message))
|
||||||
|
replacer := strings.NewReplacer(".", " ", ",", " ", "!", " ", "?", " ", ":", " ", ";", " ", "(", " ", ")", " ", "\"", " ", "'", " ", "«", " ", "»", " ", "+", " + ", "-", " - ", "/", " / ")
|
||||||
|
normalized := replacer.Replace(lower)
|
||||||
|
return strings.Fields(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bool) map[interaction.SpeechAct]int {
|
||||||
|
scores := map[interaction.SpeechAct]int{
|
||||||
|
interaction.SpeechActAssertion: 1,
|
||||||
|
interaction.SpeechActDirective: 0,
|
||||||
|
interaction.SpeechActQuestion: 0,
|
||||||
|
interaction.SpeechActRequestToInvestigate: 0,
|
||||||
|
interaction.SpeechActCorrection: 0,
|
||||||
|
interaction.SpeechActDecision: 0,
|
||||||
|
interaction.SpeechActPreference: 0,
|
||||||
|
interaction.SpeechActHypothesis: 0,
|
||||||
|
interaction.SpeechActConfirmation: 0,
|
||||||
|
interaction.SpeechActRejection: 0,
|
||||||
|
interaction.SpeechActConversational: 0,
|
||||||
|
}
|
||||||
|
if hasQuestionMark {
|
||||||
|
scores[interaction.SpeechActQuestion]++
|
||||||
|
}
|
||||||
|
if explicitCorrection {
|
||||||
|
scores[interaction.SpeechActCorrection] += 6
|
||||||
|
}
|
||||||
|
first := ""
|
||||||
|
if len(tokens) > 0 {
|
||||||
|
first = tokens[0]
|
||||||
|
}
|
||||||
|
if first == "нет" || first == "не" {
|
||||||
|
scores[interaction.SpeechActCorrection] += 2
|
||||||
|
scores[interaction.SpeechActRejection]++
|
||||||
|
}
|
||||||
|
if first == "да" {
|
||||||
|
scores[interaction.SpeechActConfirmation] += 2
|
||||||
|
}
|
||||||
|
questionWords := map[string]struct{}{"кто": {}, "что": {}, "как": {}, "почему": {}, "зачем": {}, "где": {}, "когда": {}, "сколько": {}, "какой": {}, "какая": {}, "какие": {}, "чей": {}}
|
||||||
|
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй"}
|
||||||
|
investigateStems := []string{"разбер", "проверь", "проанализ", "исслед", "выясн", "подум", "понят", "посмотри"}
|
||||||
|
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "спрос", "посчитай", "рассчитай", "ответь"}
|
||||||
|
explanatoryRequestStems := []string{"расска", "раска", "объяс", "опиш", "покаж", "подскаж"}
|
||||||
|
preferenceStems := []string{"предпоч", "хочу", "лучше", "не используй"}
|
||||||
|
hypothesisStems := []string{"думаю", "кажется", "гипотез", "похоже"}
|
||||||
|
decisionStems := []string{"решил", "решение", "выбираю"}
|
||||||
|
arithmeticMarker := false
|
||||||
|
for index, token := range tokens {
|
||||||
|
if _, ok := questionWords[token]; ok && !(token == "что" && index+1 < len(tokens) && tokens[index+1] == "нибудь") {
|
||||||
|
scores[interaction.SpeechActQuestion] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, conversationWords...) {
|
||||||
|
scores[interaction.SpeechActConversational] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, investigateStems...) {
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||||
|
scores[interaction.SpeechActQuestion]++
|
||||||
|
}
|
||||||
|
if containsStem(token, directiveStems...) {
|
||||||
|
scores[interaction.SpeechActDirective] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, preferenceStems...) {
|
||||||
|
scores[interaction.SpeechActPreference] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, hypothesisStems...) {
|
||||||
|
scores[interaction.SpeechActHypothesis] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, decisionStems...) {
|
||||||
|
scores[interaction.SpeechActDecision] += 3
|
||||||
|
}
|
||||||
|
if token == "+" || token == "-" || token == "/" || token == "*" || token == "плюс" || token == "минус" {
|
||||||
|
arithmeticMarker = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(tokens) >= 2 && tokens[0] == "я" && containsStemInTokens(tokens[1:], "настро", "сдела", "исправ", "удал", "созда", "перезапуст", "поменя", "добави") {
|
||||||
|
scores[interaction.SpeechActAssertion] += 5
|
||||||
|
}
|
||||||
|
if arithmeticMarker {
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
scores[interaction.SpeechActDirective]++
|
||||||
|
}
|
||||||
|
if len(tokens) <= 4 {
|
||||||
|
for index, token := range tokens {
|
||||||
|
if _, ok := questionWords[token]; ok && !(token == "что" && index+1 < len(tokens) && tokens[index+1] == "нибудь") {
|
||||||
|
scores[interaction.SpeechActQuestion]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(tokens) == 2 && tokens[0] == "ты" {
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
}
|
||||||
|
if len(tokens) >= 2 && tokens[0] == "как" && containsToken(tokens, "зовут") {
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
}
|
||||||
|
if startsWithDirectiveWhatNibud(tokens) {
|
||||||
|
scores[interaction.SpeechActDirective] += 4
|
||||||
|
}
|
||||||
|
if len(tokens) > 0 && containsStem(tokens[0], investigateStems...) {
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||||
|
}
|
||||||
|
if len(tokens) > 0 && containsStem(tokens[0], "разбер", "проверь", "проанализ", "исслед", "выясн") && containsMeaningfulInterrogative(tokens) {
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||||
|
}
|
||||||
|
if startsWithExplanatoryRequest(tokens, explanatoryRequestStems...) {
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||||
|
}
|
||||||
|
if startsWithModalRequest(tokens) && containsStemInTokens(tokens, explanatoryRequestStems...) {
|
||||||
|
scores[interaction.SpeechActQuestion] += 3
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||||
|
}
|
||||||
|
if containsModelReference(tokens) {
|
||||||
|
if containsStemInTokens(tokens, "обрати", "спрос", "уточни") {
|
||||||
|
scores[interaction.SpeechActDirective] += 3
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if containsStemInTokens(tokens, "замени", "смени") {
|
||||||
|
scores[interaction.SpeechActDirective] += 3
|
||||||
|
}
|
||||||
|
if !hasQuestionMark && !containsInterrogative(tokens) && !startsWithModalRequest(tokens) && !startsWithExplanatoryRequest(tokens, explanatoryRequestStems...) &&
|
||||||
|
scores[interaction.SpeechActDirective] == 0 && scores[interaction.SpeechActRequestToInvestigate] == 0 && scores[interaction.SpeechActCorrection] == 0 {
|
||||||
|
scores[interaction.SpeechActAssertion] += 2
|
||||||
|
}
|
||||||
|
return scores
|
||||||
|
}
|
||||||
|
|
||||||
|
func topAct(scores map[interaction.SpeechAct]int) (interaction.SpeechAct, int) {
|
||||||
|
bestAct, bestScore := interaction.SpeechActUnknown, -1
|
||||||
|
for _, act := range []interaction.SpeechAct{
|
||||||
|
interaction.SpeechActQuestion,
|
||||||
|
interaction.SpeechActRequestToInvestigate,
|
||||||
|
interaction.SpeechActDirective,
|
||||||
|
interaction.SpeechActCorrection,
|
||||||
|
interaction.SpeechActConversational,
|
||||||
|
interaction.SpeechActPreference,
|
||||||
|
interaction.SpeechActHypothesis,
|
||||||
|
interaction.SpeechActDecision,
|
||||||
|
interaction.SpeechActConfirmation,
|
||||||
|
interaction.SpeechActRejection,
|
||||||
|
interaction.SpeechActAssertion,
|
||||||
|
} {
|
||||||
|
if score := scores[act]; score > bestScore {
|
||||||
|
bestAct, bestScore = act, score
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestAct, bestScore
|
||||||
|
}
|
||||||
|
|
||||||
|
func secondAct(scores map[interaction.SpeechAct]int, primary interaction.SpeechAct) (interaction.SpeechAct, int) {
|
||||||
|
second, score := interaction.SpeechActUnknown, -1
|
||||||
|
for act, value := range scores {
|
||||||
|
if act == primary {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if value > score {
|
||||||
|
second, score = act, value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if score <= 0 {
|
||||||
|
return interaction.SpeechActUnknown, 0
|
||||||
|
}
|
||||||
|
return second, score
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicabilityFor(primary, secondary interaction.SpeechAct, primaryScore, secondaryScore int, tokens []string, explicitCorrection bool) interaction.SemanticApplicability {
|
||||||
|
if primary == interaction.SpeechActAssertion && !containsInterrogative(tokens) && secondaryScore <= 1 {
|
||||||
|
return interaction.SemanticApplicable
|
||||||
|
}
|
||||||
|
if primaryScore < 2 {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
if explicitCorrection && secondaryScore >= 3 && (secondary == interaction.SpeechActDirective || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||||
|
return interaction.SemanticMixedIntent
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActCorrection && secondaryScore >= 3 && (secondary == interaction.SpeechActDirective || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||||
|
return interaction.SemanticMixedIntent
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActAssertion && containsMeaningfulInterrogative(tokens) {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActDirective && likelyConsequential(tokens) {
|
||||||
|
return interaction.SemanticCandidateClarify
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActDirective && containsStemInTokens(tokens, "обрати", "спрос") && containsModelReference(tokens) {
|
||||||
|
return interaction.SemanticLowConfidence
|
||||||
|
}
|
||||||
|
if primaryScore-secondaryScore <= 1 && secondaryScore >= 2 {
|
||||||
|
return interaction.SemanticLowConfidence
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
if primaryScore < 4 {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return interaction.SemanticApplicable
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsCognitionForCandidate(primary, secondary interaction.SpeechAct, tokens []string) bool {
|
||||||
|
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActDirective && (containsInterrogative(tokens) || containsModelReference(tokens) || containsStemInTokens(tokens, "спрос", "обрати", "посчитай", "рассчитай")) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func deterministicReason(primary, secondary interaction.SpeechAct, tokens []string) string {
|
||||||
|
reasons := []string{"deterministic candidate from token-shape, interrogative, imperative and context cues"}
|
||||||
|
if primary == interaction.SpeechActQuestion && containsInterrogative(tokens) {
|
||||||
|
reasons = append(reasons, "interrogative structure observed")
|
||||||
|
}
|
||||||
|
if secondary != interaction.SpeechActUnknown {
|
||||||
|
reasons = append(reasons, "secondary competing semantic signal observed")
|
||||||
|
}
|
||||||
|
return strings.Join(reasons, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []string) []string {
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
add := func(kind string) {
|
||||||
|
if kind != "" {
|
||||||
|
seen[kind] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
add("COGNITIVE_REASONING")
|
||||||
|
}
|
||||||
|
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
|
||||||
|
add("SCHEDULE_REMINDER")
|
||||||
|
}
|
||||||
|
if isExplicitEmailAction(tokens) {
|
||||||
|
add("SEND_EMAIL")
|
||||||
|
}
|
||||||
|
if containsToken(tokens, "код") || containsToken(tokens, "патч") || containsToken(tokens, "текст") || containsToken(tokens, "главной") || containsToken(tokens, "чате") {
|
||||||
|
if primary == interaction.SpeechActDirective || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActDirective {
|
||||||
|
add("MODIFY_CODE")
|
||||||
|
add("RUN_TESTS")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if containsToken(tokens, "assistant") && containsStemInTokens(tokens, "исправ", "добав", "измени", "помен", "патч") {
|
||||||
|
add("MODIFY_CODE")
|
||||||
|
add("RUN_TESTS")
|
||||||
|
}
|
||||||
|
if containsStemInTokens(tokens, "исправ", "поправ") && (containsToken(tokens, "чате") || containsToken(tokens, "текст") || containsToken(tokens, "assistant")) {
|
||||||
|
add("MODIFY_CODE")
|
||||||
|
add("RUN_TESTS")
|
||||||
|
}
|
||||||
|
if containsStemInTokens(tokens, "патч", "исправ", "поправ") && containsStemInTokens(tokens, "разбер", "проверь", "почему", "тормозит", "подум") {
|
||||||
|
add("MODIFY_CODE")
|
||||||
|
add("RUN_TESTS")
|
||||||
|
}
|
||||||
|
if containsInterrogative(tokens) && containsArithmetic(tokens) {
|
||||||
|
add("COGNITIVE_REASONING")
|
||||||
|
}
|
||||||
|
if containsToken(tokens, "свободно") || containsToken(tokens, "гб") || containsToken(tokens, "модель") {
|
||||||
|
add("VERIFY_FACT")
|
||||||
|
}
|
||||||
|
values := make([]string, 0, len(seen))
|
||||||
|
for kind := range seen {
|
||||||
|
values = append(values, kind)
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 {
|
||||||
|
total := 0
|
||||||
|
for _, score := range scores {
|
||||||
|
if score > 0 {
|
||||||
|
total += score
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if total == 0 {
|
||||||
|
return 200
|
||||||
|
}
|
||||||
|
confidence := int64(400 + (primaryScore * 100))
|
||||||
|
if secondaryScore > 0 {
|
||||||
|
confidence -= int64(secondaryScore * 40)
|
||||||
|
}
|
||||||
|
if confidence < 200 {
|
||||||
|
confidence = 200
|
||||||
|
}
|
||||||
|
if confidence > 980 {
|
||||||
|
confidence = 980
|
||||||
|
}
|
||||||
|
return int64(confidence)
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsStem(token string, stems ...string) bool {
|
||||||
|
for _, stem := range stems {
|
||||||
|
if strings.Contains(token, stem) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsStemInTokens(tokens []string, stems ...string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if containsStem(token, stems...) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestedOutcome(message string, act interaction.SpeechAct) string {
|
||||||
|
if act == interaction.SpeechActDirective || act == interaction.SpeechActDecision || act == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return strings.TrimSpace(message)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsToken(tokens []string, expected string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == expected {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWithModalRequest(tokens []string) bool {
|
||||||
|
if len(tokens) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch tokens[0] {
|
||||||
|
case "можешь", "можете", "сможешь", "сможете":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if len(tokens) >= 3 && tokens[0] == "не" && strings.HasPrefix(tokens[1], "мог") && tokens[2] == "бы" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWithExplanatoryRequest(tokens []string, stems ...string) bool {
|
||||||
|
if len(tokens) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if containsStem(tokens[0], stems...) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return len(tokens) >= 2 && tokens[0] == "про" && containsStemInTokens(tokens[1:], stems...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsInterrogative(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch token {
|
||||||
|
case "кто", "что", "как", "почему", "зачем", "где", "когда", "сколько", "какой", "какая", "какие", "чей":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsMeaningfulInterrogative(tokens []string) bool {
|
||||||
|
for index, token := range tokens {
|
||||||
|
if token == "что" && followsNibud(tokens[index+1:]) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch token {
|
||||||
|
case "кто", "что", "как", "почему", "зачем", "где", "когда", "сколько", "какой", "какая", "какие", "чей":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsArithmetic(tokens []string) bool {
|
||||||
|
digits := 0
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "+" || token == "-" || token == "*" || token == "/" || token == "плюс" || token == "минус" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, r := range token {
|
||||||
|
if r >= '0' && r <= '9' {
|
||||||
|
digits++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return digits >= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func likelyConsequential(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if containsStem(token, "удал", "снес", "замен", "миграц", "парол", "опубли", "перезапуст", "смени", "купи") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func followsNibud(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "-" || token == "ни" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return token == "нибудь"
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWithDirectiveWhatNibud(tokens []string) bool {
|
||||||
|
if len(tokens) < 2 || !containsStem(tokens[0], "сдел", "исправ", "добав", "удал", "напом", "подключ", "обрати", "спрос", "посчитай", "рассчитай", "использ") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for index, token := range tokens {
|
||||||
|
if token == "что" && followsNibud(tokens[index+1:]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsModelReference(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "модель" || token == "модели" || strings.Contains(token, "gemma") || strings.Contains(token, "гемма") || strings.Contains(token, "qwen") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExplicitEmailAction(tokens []string) bool {
|
||||||
|
hasMailObject := containsToken(tokens, "письмо") || containsToken(tokens, "письма") || containsToken(tokens, "почту") || containsToken(tokens, "почта")
|
||||||
|
hasMailVerb := containsStemInTokens(tokens, "отправ", "ответ", "напиш")
|
||||||
|
return hasMailObject && hasMailVerb
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeCapabilityHint(values []string, denied string) []string {
|
||||||
|
result := make([]string, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if value == denied {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, value)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -49,6 +49,67 @@ func TestNewHumanUtteranceClassifiesReminderAndCapabilityConnectionAsDirective(t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateIsInvariantToMissingQuestionMarkForIdentityAndArithmetic(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
message string
|
||||||
|
act interaction.SpeechAct
|
||||||
|
}{
|
||||||
|
{"ты кто", interaction.SpeechActQuestion},
|
||||||
|
{"Ты кто?", interaction.SpeechActQuestion},
|
||||||
|
{"а ты кто", interaction.SpeechActQuestion},
|
||||||
|
{"сколько будет 2 + 2", interaction.SpeechActQuestion},
|
||||||
|
{"сколько будет 2 + 2?", interaction.SpeechActQuestion},
|
||||||
|
{"2 плюс 2 сколько", interaction.SpeechActQuestion},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
candidate := BuildDeterministicCandidate(tc.message, "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != tc.act {
|
||||||
|
t.Fatalf("expected %s for %q, got %s (%+v)", tc.act, tc.message, candidate.PrimarySpeechAct, candidate)
|
||||||
|
}
|
||||||
|
if candidate.Applicability == interaction.SemanticApplicable && candidate.NeedsCognition {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !candidate.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition-worthy candidate for %q, got %+v", tc.message, candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateTreatsModalExplanationRequestsAsCognitionWorthWithoutQuestionMark(t *testing.T) {
|
||||||
|
for _, message := range []string{
|
||||||
|
"можешь рассказать об утре",
|
||||||
|
"можешь расказать об утре",
|
||||||
|
"можете объяснить это проще",
|
||||||
|
"расскажи об утре",
|
||||||
|
"про утро расскажешь",
|
||||||
|
} {
|
||||||
|
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != interaction.SpeechActQuestion && candidate.PrimarySpeechAct != interaction.SpeechActRequestToInvestigate {
|
||||||
|
t.Fatalf("expected broader cognitive speech act for %q, got %+v", message, candidate)
|
||||||
|
}
|
||||||
|
if !candidate.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition for %q, got %+v", message, candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateTreatsModelRequestAsDirectiveNeedingCognition(t *testing.T) {
|
||||||
|
candidate := BuildDeterministicCandidate("обратись к модели gemma4 и спроси сколько звезд на небе", "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != interaction.SpeechActDirective {
|
||||||
|
t.Fatalf("expected directive, got %+v", candidate)
|
||||||
|
}
|
||||||
|
if !candidate.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition-worthy model request, got %+v", candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) {
|
||||||
|
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != interaction.SpeechActAssertion {
|
||||||
|
t.Fatalf("expected assertion, got %+v", candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNewConversationRequiresActorAndPrincipal(t *testing.T) {
|
func TestNewConversationRequiresActorAndPrincipal(t *testing.T) {
|
||||||
_, err := NewConversation(identity.ActorID(""), identity.PrincipalID("principal-1"), time.Unix(10, 0))
|
_, err := NewConversation(identity.ActorID(""), identity.PrincipalID("principal-1"), time.Unix(10, 0))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
@@ -11,34 +11,44 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type SemanticResult struct {
|
type SemanticResult struct {
|
||||||
Interpretation interaction.UtteranceInterpretation
|
Interpretation interaction.UtteranceInterpretation
|
||||||
Projects []interaction.ProjectReference
|
Candidates []interaction.SemanticCandidate
|
||||||
Relations []interaction.InteractionRelation
|
Projects []interaction.ProjectReference
|
||||||
ActiveFocus *situation.ActiveProjectFocus
|
Relations []interaction.InteractionRelation
|
||||||
Reply string
|
ActiveFocus *situation.ActiveProjectFocus
|
||||||
NeedsCognition bool
|
Reply string
|
||||||
|
NeedsCognition bool
|
||||||
|
CapabilityHints []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func InterpretUtterance(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, previousFocus *situation.ActiveProjectFocus, now time.Time) (SemanticResult, error) {
|
func InterpretUtterance(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, previousFocus *situation.ActiveProjectFocus, now time.Time) (SemanticResult, error) {
|
||||||
act := ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
|
||||||
interpretationID, err := ids.New()
|
interpretationID, err := ids.New()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SemanticResult{}, err
|
return SemanticResult{}, err
|
||||||
}
|
}
|
||||||
millis := now.UnixMilli()
|
millis := now.UnixMilli()
|
||||||
|
deterministicCandidate := BuildDeterministicCandidate(utterance.Content, utterance.CorrectsUtteranceID, millis)
|
||||||
|
deterministicCandidate.UtteranceID = utterance.ID
|
||||||
|
selectedCandidate := deterministicCandidate
|
||||||
result := SemanticResult{
|
result := SemanticResult{
|
||||||
Interpretation: interaction.UtteranceInterpretation{
|
Interpretation: interaction.UtteranceInterpretation{
|
||||||
ID: interaction.InterpretationID(interpretationID),
|
ID: interaction.InterpretationID(interpretationID),
|
||||||
UtteranceID: utterance.ID,
|
UtteranceID: utterance.ID,
|
||||||
SpeechAct: act,
|
SpeechAct: selectedCandidate.PrimarySpeechAct,
|
||||||
ConfidenceMillis: confidenceFor(act),
|
SecondarySpeechAct: selectedCandidate.SecondarySpeechAct,
|
||||||
Source: "deterministic-v1",
|
ConfidenceMillis: selectedCandidate.ConfidenceMillis,
|
||||||
|
Source: string(selectedCandidate.Source),
|
||||||
AssertionVerification: string(epistemics.VerificationUnverified),
|
AssertionVerification: string(epistemics.VerificationUnverified),
|
||||||
RequestedOutcome: requestedOutcome(utterance.Content, act),
|
RequestedOutcome: selectedCandidate.RequestedOutcome,
|
||||||
Clarification: interaction.ClarificationNotRequired,
|
Clarification: selectedCandidate.Clarification,
|
||||||
|
NeedsCognition: selectedCandidate.NeedsCognition,
|
||||||
|
Applicability: selectedCandidate.Applicability,
|
||||||
|
SelectionReason: selectedCandidate.SelectionReason,
|
||||||
RecordedAtUnixMillis: millis,
|
RecordedAtUnixMillis: millis,
|
||||||
},
|
},
|
||||||
NeedsCognition: NeedsCognition(act),
|
Candidates: []interaction.SemanticCandidate{deterministicCandidate},
|
||||||
|
NeedsCognition: selectedCandidate.NeedsCognition,
|
||||||
|
CapabilityHints: append([]string(nil), selectedCandidate.CapabilityHints...),
|
||||||
}
|
}
|
||||||
explicitFocus := explicitProjectFocus(utterance.Content, projects)
|
explicitFocus := explicitProjectFocus(utterance.Content, projects)
|
||||||
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
|
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
|
||||||
@@ -58,12 +68,15 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
|||||||
UpdatedAtUnixMillis: millis,
|
UpdatedAtUnixMillis: millis,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if isAmbiguousDestructive(act, utterance.Content, result.Projects) {
|
if selectedCandidate.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(selectedCandidate, utterance.Content, result.Projects) {
|
||||||
result.Interpretation.Clarification = interaction.ClarificationRequired
|
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||||
|
result.Interpretation.Applicability = interaction.SemanticCandidateClarify
|
||||||
|
result.Interpretation.SelectionReason = "consequential ambiguity requires clarification before relying on cheap deterministic interpretation"
|
||||||
|
result.NeedsCognition = false
|
||||||
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
|
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
if act == interaction.SpeechActCorrection {
|
if hasCorrectionMeaning(selectedCandidate, utterance) {
|
||||||
relations, err := correctionRelations(utterance, millis)
|
relations, err := correctionRelations(utterance, millis)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SemanticResult{}, err
|
return SemanticResult{}, err
|
||||||
@@ -71,12 +84,56 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
|||||||
result.Relations = append(result.Relations, relations...)
|
result.Relations = append(result.Relations, relations...)
|
||||||
}
|
}
|
||||||
result.Reply = semanticReply(utterance.Content, result, previousFocus)
|
result.Reply = semanticReply(utterance.Content, result, previousFocus)
|
||||||
if isCurrentFocusQuestion(utterance.Content, act) && previousFocus != nil {
|
if isCurrentFocusQuestion(utterance.Content, selectedCandidate.PrimarySpeechAct) && previousFocus != nil {
|
||||||
result.NeedsCognition = false
|
result.NeedsCognition = false
|
||||||
|
result.Interpretation.NeedsCognition = false
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ApplyCognitiveCandidate(result SemanticResult, message string, candidate interaction.SemanticCandidate, previousFocus *situation.ActiveProjectFocus) SemanticResult {
|
||||||
|
candidate.SelectionState = interaction.CandidateSelected
|
||||||
|
if candidate.UtteranceID == "" {
|
||||||
|
candidate.UtteranceID = result.Interpretation.UtteranceID
|
||||||
|
}
|
||||||
|
selected := false
|
||||||
|
for index := range result.Candidates {
|
||||||
|
if result.Candidates[index].SelectionState == interaction.CandidateSelected {
|
||||||
|
result.Candidates[index].SelectionState = interaction.CandidateObserved
|
||||||
|
}
|
||||||
|
if result.Candidates[index].ID == candidate.ID {
|
||||||
|
result.Candidates[index] = candidate
|
||||||
|
selected = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !selected {
|
||||||
|
result.Candidates = append(result.Candidates, candidate)
|
||||||
|
}
|
||||||
|
result.Interpretation.SpeechAct = candidate.PrimarySpeechAct
|
||||||
|
result.Interpretation.SecondarySpeechAct = candidate.SecondarySpeechAct
|
||||||
|
result.Interpretation.ConfidenceMillis = candidate.ConfidenceMillis
|
||||||
|
result.Interpretation.Source = string(candidate.Source)
|
||||||
|
result.Interpretation.RequestedOutcome = candidate.RequestedOutcome
|
||||||
|
result.Interpretation.Clarification = candidate.Clarification
|
||||||
|
result.Interpretation.NeedsCognition = candidate.NeedsCognition
|
||||||
|
result.Interpretation.Applicability = candidate.Applicability
|
||||||
|
result.Interpretation.SelectionReason = candidate.SelectionReason
|
||||||
|
result.NeedsCognition = candidate.NeedsCognition
|
||||||
|
result.CapabilityHints = append([]string(nil), candidate.CapabilityHints...)
|
||||||
|
if result.Interpretation.SpeechAct == interaction.SpeechActAssertion {
|
||||||
|
result.Interpretation.AssertionVerification = string(epistemics.VerificationUnverified)
|
||||||
|
} else {
|
||||||
|
result.Interpretation.AssertionVerification = string(epistemics.VerificationNotApplicable)
|
||||||
|
}
|
||||||
|
if candidate.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(candidate, message, result.Projects) {
|
||||||
|
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||||
|
result.NeedsCognition = false
|
||||||
|
result.Interpretation.NeedsCognition = false
|
||||||
|
}
|
||||||
|
result.Reply = semanticReply(message, result, previousFocus)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
||||||
@@ -181,20 +238,6 @@ func correctionRelations(utterance interaction.HumanUtterance, millis int64) ([]
|
|||||||
return []interaction.InteractionRelation{{ID: interaction.InteractionRelationID(id), FromUtteranceID: utterance.ID, ToUtteranceID: utterance.CorrectsUtteranceID, Kind: interaction.RelationSupersedes, RecordedAtUnixMillis: millis}}, nil
|
return []interaction.InteractionRelation{{ID: interaction.InteractionRelationID(id), FromUtteranceID: utterance.ID, ToUtteranceID: utterance.CorrectsUtteranceID, Kind: interaction.RelationSupersedes, RecordedAtUnixMillis: millis}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func confidenceFor(act interaction.SpeechAct) int64 {
|
|
||||||
if act == interaction.SpeechActUnknown {
|
|
||||||
return 300
|
|
||||||
}
|
|
||||||
return 800
|
|
||||||
}
|
|
||||||
|
|
||||||
func requestedOutcome(message string, act interaction.SpeechAct) string {
|
|
||||||
if act == interaction.SpeechActDirective || act == interaction.SpeechActDecision || act == interaction.SpeechActRequestToInvestigate {
|
|
||||||
return strings.TrimSpace(message)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if act == interaction.SpeechActUnknown {
|
if act == interaction.SpeechActUnknown {
|
||||||
@@ -209,10 +252,10 @@ func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func isAmbiguousDestructive(act interaction.SpeechAct, message string, projects []interaction.ProjectReference) bool {
|
func isAmbiguousDestructive(candidate interaction.SemanticCandidate, message string, projects []interaction.ProjectReference) bool {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
destructive := strings.Contains(lower, "удали") || strings.Contains(lower, "снеси") || strings.Contains(lower, "удалить")
|
destructive := strings.Contains(lower, "удали") || strings.Contains(lower, "снеси") || strings.Contains(lower, "удалить")
|
||||||
if !destructive || act != interaction.SpeechActDirective {
|
if !destructive || (candidate.PrimarySpeechAct != interaction.SpeechActDirective && candidate.SecondarySpeechAct != interaction.SpeechActDirective) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if len(projects) == 0 {
|
if len(projects) == 0 {
|
||||||
@@ -227,18 +270,34 @@ func semanticReply(message string, result SemanticResult, previousFocus *situati
|
|||||||
}
|
}
|
||||||
switch result.Interpretation.SpeechAct {
|
switch result.Interpretation.SpeechAct {
|
||||||
case interaction.SpeechActAssertion:
|
case interaction.SpeechActAssertion:
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Смысл сообщения пока понят недостаточно надёжно. Я сохраню его и при доступности более широкого когнитивного разбора не буду притворяться, что это уже проверенный факт."
|
||||||
|
}
|
||||||
return "Записал как утверждение человека. Это пока не проверенный факт."
|
return "Записал как утверждение человека. Это пока не проверенный факт."
|
||||||
case interaction.SpeechActDirective:
|
case interaction.SpeechActDirective:
|
||||||
|
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActCorrection {
|
||||||
|
return "Понял это как исправление предыдущего понимания и одновременно как новую просьбу. Ничего не выполнено без отдельного подтверждённого действия."
|
||||||
|
}
|
||||||
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
|
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
|
||||||
case interaction.SpeechActDecision:
|
case interaction.SpeechActDecision:
|
||||||
return "Записал это как явное решение пользователя для дальнейшей обработки."
|
return "Записал это как явное решение пользователя для дальнейшей обработки."
|
||||||
case interaction.SpeechActCorrection:
|
case interaction.SpeechActCorrection:
|
||||||
|
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActDirective || result.Interpretation.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return "Исправление записано отдельно, и я вижу здесь ещё новую рабочую просьбу; история сохранена без переписывания."
|
||||||
|
}
|
||||||
return "Исправление записано новым сообщением; прежняя история сохранена."
|
return "Исправление записано новым сообщением; прежняя история сохранена."
|
||||||
case interaction.SpeechActQuestion:
|
case interaction.SpeechActQuestion:
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
|
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
|
||||||
return "Сейчас в фокусе: " + previousFocus.ProjectDisplayName + "."
|
return "Сейчас в фокусе: " + previousFocus.ProjectDisplayName + "."
|
||||||
}
|
}
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Похоже, здесь нужен более широкий разбор смысла, а не дешёвый поверхностный рефлекс. Я не буду делать вид, что уже понял всё достаточно точно."
|
||||||
|
}
|
||||||
|
case interaction.SpeechActRequestToInvestigate:
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Похоже, здесь запрошено рассуждение или исследование. Я не буду финализировать смысл только по поверхностным признакам."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return FallbackText(result.Interpretation.SpeechAct)
|
return FallbackText(result.Interpretation.SpeechAct)
|
||||||
}
|
}
|
||||||
@@ -250,3 +309,10 @@ func isCurrentFocusQuestion(message string, act interaction.SpeechAct) bool {
|
|||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
return strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")
|
return strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hasCorrectionMeaning(candidate interaction.SemanticCandidate, utterance interaction.HumanUtterance) bool {
|
||||||
|
if utterance.CorrectsUtteranceID != "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return candidate.PrimarySpeechAct == interaction.SpeechActCorrection || candidate.SecondarySpeechAct == interaction.SpeechActCorrection
|
||||||
|
}
|
||||||
|
|||||||
@@ -116,6 +116,48 @@ func TestInterpretUtteranceAmbiguousDestructiveRequiresClarification(t *testing.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtterancePunctuationFreeRussianQuestionStillRequestsBroaderInterpretation(t *testing.T) {
|
||||||
|
result := interpretForTest(t, "ты кто", nil, "")
|
||||||
|
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||||
|
t.Fatalf("expected question, got %#v", result.Interpretation)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for punctuation-free identity question, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtterancePunctuationFreeArithmeticStillRequestsCognition(t *testing.T) {
|
||||||
|
result := interpretForTest(t, "сколько будет 2 + 2", nil, "")
|
||||||
|
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||||
|
t.Fatalf("expected question, got %#v", result.Interpretation)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for punctuation-free arithmetic, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtteranceModalExplanationRequestDefersToCognition(t *testing.T) {
|
||||||
|
for _, message := range []string{"можешь расказать об утре", "расскажи об утре", "про утро расскажешь"} {
|
||||||
|
result := interpretForTest(t, message, nil, "")
|
||||||
|
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion && result.Interpretation.SpeechAct != interaction.SpeechActRequestToInvestigate {
|
||||||
|
t.Fatalf("expected cognition-worthy interpretation for %q, got %#v", message, result.Interpretation)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for %q, got %#v", message, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtteranceNamedModelRequestIsDirectiveNeedingCognition(t *testing.T) {
|
||||||
|
result := interpretForTest(t, "обратись к модели gemma4 и спроси сколько звезд на небе", nil, "")
|
||||||
|
if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
|
||||||
|
t.Fatalf("expected directive, got %#v", result.Interpretation)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for named-model request, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func interpretForTest(t *testing.T, message string, previous *situation.ActiveProjectFocus, corrects interaction.HumanUtteranceID) SemanticResult {
|
func interpretForTest(t *testing.T, message string, previous *situation.ActiveProjectFocus, corrects interaction.HumanUtteranceID) SemanticResult {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||||
|
|||||||
@@ -74,21 +74,51 @@ func BuildPlanningResult(input work.PlanningInput, now time.Time) (work.Planning
|
|||||||
func DetermineHelpPath(input work.PlanningInput) work.HelpPath {
|
func DetermineHelpPath(input work.PlanningInput) work.HelpPath {
|
||||||
lower := strings.ToLower(input.Message)
|
lower := strings.ToLower(input.Message)
|
||||||
switch {
|
switch {
|
||||||
case containsAny(lower, "объясни", "расскажи", "что делает"):
|
case input.RequiresClarification:
|
||||||
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "simple help can be answered without durable Goal/Work/Plan"}
|
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "clarification is required before capability selection or durable work", Reply: "Нужно короткое уточнение, прежде чем выбирать capability или строить более тяжёлый маршрут."}
|
||||||
case containsAny(lower, "напомни", "напомин"):
|
case isReminderRequest(lower):
|
||||||
return work.HelpPath{Kind: work.HelpPathDirectCapability, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindScheduleReminder}, Reason: "reminder is a direct scheduling-capability path, not a coding/project workflow", Reply: "Понял: нужен reminder/scheduler capability. В DEV-000063 я фиксирую это как безопасный путь помощи; само напоминание ещё не зарегистрировано, потому что scheduling adapter не подключён."}
|
return work.HelpPath{Kind: work.HelpPathDirectCapability, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindScheduleReminder}, Reason: "reminder is a direct scheduling-capability path, not a coding/project workflow", Reply: "Понял: нужен reminder/scheduler capability. В DEV-000063 я фиксирую это как безопасный путь помощи; само напоминание ещё не зарегистрировано, потому что scheduling adapter не подключён."}
|
||||||
case containsAny(lower, "отправь", "письм", "почт"):
|
case isEmailReviewRequest(lower):
|
||||||
|
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "mail triage/review needs structured reading and reasoning without claiming outbound send"}
|
||||||
|
case isExplicitEmailGapRequest(lower):
|
||||||
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindSendEmail}, CapabilityGap: true, Reason: "email sending needs a communication capability implementation and explicit authority", Reply: "Сейчас у меня ещё не подключена возможность отправлять почту. Я зафиксирую этот capability gap, чтобы позже к нему можно было вернуться."}
|
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindSendEmail}, CapabilityGap: true, Reason: "email sending needs a communication capability implementation and explicit authority", Reply: "Сейчас у меня ещё не подключена возможность отправлять почту. Я зафиксирую этот capability gap, чтобы позже к нему можно было вернуться."}
|
||||||
case containsAny(lower, "не умеешь", "подключи интеграцию", "интеграц", "неизвестн", "нет capability", "создай adapter", "создай адаптер"):
|
case isUnsupportedCapabilityRequest(lower):
|
||||||
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{}, CapabilityGap: true, Reason: "requested help needs a currently missing capability and may later trigger acquisition/self-extension", Reply: "Похоже, для этой просьбы нужна capability, которой сейчас нет. Это не задача конкретного executor автоматически: в будущем Домовой сможет найти, подключить или создать подходящую capability и вернуться к исходной потребности."}
|
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{}, CapabilityGap: true, Reason: "requested help needs a currently missing capability and may later trigger acquisition/self-extension", Reply: "Похоже, для этой просьбы нужна capability, которой сейчас нет. Это не задача конкретного executor автоматически: в будущем Домовой сможет найти, подключить или создать подходящую capability и вернуться к исходной потребности."}
|
||||||
|
case needsDurableWorkFromHints(input):
|
||||||
|
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "semantic hints indicate project/code work even if cognition may still be useful upstream"}
|
||||||
case requiresDurableWork(lower):
|
case requiresDurableWork(lower):
|
||||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "request needs durable coordination, planning, investigation, delegation, or outcome tracking"}
|
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "request needs durable coordination, planning, investigation, delegation, or outcome tracking"}
|
||||||
|
case containsAny(lower, "объясни", "расскажи", "что делает"):
|
||||||
|
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "simple help can be answered without durable Goal/Work/Plan"}
|
||||||
|
case input.NeedsCognition && needsCognitiveAnswer(input):
|
||||||
|
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "semantic layer marked this utterance as cognition-relevant and no durable work path outranks it"}
|
||||||
|
case input.NeedsCognition && (input.SpeechAct == work.SpeechActRef("QUESTION") || input.SpeechAct == work.SpeechActRef("REQUEST_TO_INVESTIGATE")):
|
||||||
|
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "semantic layer marked this utterance as cognition-relevant"}
|
||||||
default:
|
default:
|
||||||
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "ordinary interaction does not require durable Work"}
|
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "ordinary interaction does not require durable Work"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func needsDurableWorkFromHints(input work.PlanningInput) bool {
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
switch hint {
|
||||||
|
case capability.CapabilityKindModifyCode, capability.CapabilityKindRunTests, capability.CapabilityKindInspectProject, capability.CapabilityKindReadDatabase, capability.CapabilityKindQueryLogs:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsCognitiveAnswer(input work.PlanningInput) bool {
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
if hint == capability.CapabilityKindCognitiveReasoning {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(input.Message)
|
||||||
|
return containsAny(lower, "модель", "gemma4", "qwen", "спроси", "обратись", "посчитай")
|
||||||
|
}
|
||||||
|
|
||||||
func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
||||||
if candidate.ID == "" || candidate.GoalID == "" || candidate.Source == "" || candidate.Summary == "" || len(candidate.Steps) == 0 {
|
if candidate.ID == "" || candidate.GoalID == "" || candidate.Source == "" || candidate.Summary == "" || len(candidate.Steps) == 0 {
|
||||||
return ErrInvalidPlanCandidate
|
return ErrInvalidPlanCandidate
|
||||||
@@ -122,42 +152,52 @@ func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
|||||||
|
|
||||||
func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.PlanCandidate) {
|
func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.PlanCandidate) {
|
||||||
lower := strings.ToLower(input.Message)
|
lower := strings.ToLower(input.Message)
|
||||||
|
if input.SecondarySpeechAct == work.SpeechActRef("CORRECTION") {
|
||||||
|
addStep(candidate, work.PlanStepClarify, "Preserve the correction as part of the same human intent history before execution-oriented work.", len(candidate.Steps)+1, millis)
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
|
case isReminderRequest(lower):
|
||||||
|
addRequirement(candidate, capability.CapabilityKindScheduleReminder, "schedule a future reminder after temporal interpretation", epistemics.VerificationNotApplicable, millis)
|
||||||
|
addStep(candidate, work.PlanStepSchedule, "Interpret the requested reminder time and reminder subject.", 1, millis)
|
||||||
|
addStep(candidate, work.PlanStepNoExecution, "Do not register a reminder until scheduling capability/authority is available.", 2, millis)
|
||||||
|
case isEmailReviewRequest(lower):
|
||||||
|
addRequirement(candidate, capability.CapabilityKindReadEmail, "read incoming communications", epistemics.VerificationUnknown, millis)
|
||||||
|
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "classify messages needing response", epistemics.VerificationUnknown, millis)
|
||||||
|
addStep(candidate, work.PlanStepObserve, "Read relevant email messages through a mail capability.", 1, millis)
|
||||||
|
addStep(candidate, work.PlanStepReason, "Classify which messages need a response and why.", 2, millis)
|
||||||
|
addStep(candidate, work.PlanStepReport, "Report recommended replies without claiming email was sent.", 3, millis)
|
||||||
|
case isExplicitEmailGapRequest(lower):
|
||||||
|
addRequirement(candidate, capability.CapabilityKindSendEmail, "send email only after authority", epistemics.VerificationNotApplicable, millis)
|
||||||
|
addStep(candidate, work.PlanStepPrepare, "Resolve recipient and appropriate communication channel.", 1, millis)
|
||||||
|
addStep(candidate, work.PlanStepCommunicate, "Prepare the message for a communication adapter; do not send without authority.", 2, millis)
|
||||||
case containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему"):
|
case containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему"):
|
||||||
addRequirement(candidate, capability.CapabilityKindInspectProject, "inspect project context", epistemics.VerificationNotApplicable, millis)
|
addRequirement(candidate, capability.CapabilityKindInspectProject, "inspect project context", epistemics.VerificationNotApplicable, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindReadDatabase, "collect database performance observations", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindReadDatabase, "collect database performance observations", epistemics.VerificationUnknown, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindQueryLogs, "collect runtime/log observations", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindQueryLogs, "collect runtime/log observations", epistemics.VerificationUnknown, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "compare evidence and identify likely causes", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "compare evidence and identify likely causes", epistemics.VerificationUnknown, millis)
|
||||||
|
if containsAny(lower, "патч", "исправ") {
|
||||||
|
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software after investigation confirms the change", epistemics.VerificationUnknown, millis)
|
||||||
|
addRequirement(candidate, capability.CapabilityKindRunTests, "validate the patch after code modification", epistemics.VerificationNotApplicable, millis)
|
||||||
|
}
|
||||||
addStep(candidate, work.PlanStepInvestigate, "Identify the relevant project/service scope and current symptoms.", 1, millis)
|
addStep(candidate, work.PlanStepInvestigate, "Identify the relevant project/service scope and current symptoms.", 1, millis)
|
||||||
addStep(candidate, work.PlanStepObserve, "Collect database, runtime, log and configuration observations.", 2, millis)
|
addStep(candidate, work.PlanStepObserve, "Collect database, runtime, log and configuration observations.", 2, millis)
|
||||||
addStep(candidate, work.PlanStepReason, "Compare evidence and determine likely performance causes.", 3, millis)
|
addStep(candidate, work.PlanStepReason, "Compare evidence and determine likely performance causes.", 3, millis)
|
||||||
addStep(candidate, work.PlanStepReport, "Report findings and what remains unverified.", 4, millis)
|
if containsAny(lower, "патч", "исправ") {
|
||||||
|
addStep(candidate, work.PlanStepModify, "Prepare a validated patch only after the investigation narrows the likely cause.", 4, millis)
|
||||||
|
addStep(candidate, work.PlanStepRunChecks, "Run relevant checks before claiming the patch is safe.", 5, millis)
|
||||||
|
} else {
|
||||||
|
addStep(candidate, work.PlanStepReport, "Report findings and what remains unverified.", 4, millis)
|
||||||
|
}
|
||||||
case containsAny(lower, "добавь", "поддержк", "возможность", "реализ"):
|
case containsAny(lower, "добавь", "поддержк", "возможность", "реализ"):
|
||||||
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software project", epistemics.VerificationNotApplicable, millis)
|
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software project", epistemics.VerificationNotApplicable, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindRunTests, "validate software change", epistemics.VerificationNotApplicable, millis)
|
addRequirement(candidate, capability.CapabilityKindRunTests, "validate software change", epistemics.VerificationNotApplicable, millis)
|
||||||
addStep(candidate, work.PlanStepInvestigate, "Understand desired capability and affected project scope.", 1, millis)
|
addStep(candidate, work.PlanStepInvestigate, "Understand desired capability and affected project scope.", 1, millis)
|
||||||
addStep(candidate, work.PlanStepModify, "Prepare a code-change work item for a capable coding executor.", 2, millis)
|
addStep(candidate, work.PlanStepModify, "Prepare a code-change work item for a capable coding executor.", 2, millis)
|
||||||
addStep(candidate, work.PlanStepRunChecks, "Run relevant tests and architecture checks before outcome claim.", 3, millis)
|
addStep(candidate, work.PlanStepRunChecks, "Run relevant tests and architecture checks before outcome claim.", 3, millis)
|
||||||
case containsAny(lower, "письм", "почт"):
|
|
||||||
addRequirement(candidate, capability.CapabilityKindReadEmail, "read incoming communications", epistemics.VerificationUnknown, millis)
|
|
||||||
if containsAny(lower, "ответ", "ответить", "скажи") {
|
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "classify messages needing response", epistemics.VerificationUnknown, millis)
|
|
||||||
}
|
|
||||||
if containsAny(lower, "отправь", "напиши") {
|
|
||||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "send email only after authority", epistemics.VerificationNotApplicable, millis)
|
|
||||||
}
|
|
||||||
addStep(candidate, work.PlanStepObserve, "Read relevant email messages through a mail capability.", 1, millis)
|
|
||||||
addStep(candidate, work.PlanStepReason, "Classify which messages need a response and why.", 2, millis)
|
|
||||||
addStep(candidate, work.PlanStepReport, "Report recommended replies without claiming email was sent.", 3, millis)
|
|
||||||
case containsAny(lower, "напомни", "завтра", "напомин"):
|
|
||||||
addRequirement(candidate, capability.CapabilityKindScheduleReminder, "schedule a future reminder after temporal interpretation", epistemics.VerificationNotApplicable, millis)
|
|
||||||
addStep(candidate, work.PlanStepSchedule, "Interpret the requested reminder time and reminder subject.", 1, millis)
|
|
||||||
addStep(candidate, work.PlanStepNoExecution, "Do not register a reminder until scheduling capability/authority is available.", 2, millis)
|
|
||||||
case containsAny(lower, "отправь", "ивану", "сообщи"):
|
|
||||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "communicate with the named recipient after channel/authority resolution", epistemics.VerificationNotApplicable, millis)
|
|
||||||
addStep(candidate, work.PlanStepPrepare, "Resolve recipient and appropriate communication channel.", 1, millis)
|
|
||||||
addStep(candidate, work.PlanStepCommunicate, "Prepare the message for a communication adapter; do not send without authority.", 2, millis)
|
|
||||||
default:
|
default:
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
addRequirement(candidate, hint, "semantic candidate hinted that this capability may be needed", epistemics.VerificationUnknown, millis)
|
||||||
|
}
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "clarify/decompose ambiguous human intent", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "clarify/decompose ambiguous human intent", epistemics.VerificationUnknown, millis)
|
||||||
addStep(candidate, work.PlanStepClarify, "Clarify desired outcome and required capabilities.", 1, millis)
|
addStep(candidate, work.PlanStepClarify, "Clarify desired outcome and required capabilities.", 1, millis)
|
||||||
candidate.RequiresClarification = true
|
candidate.RequiresClarification = true
|
||||||
@@ -168,7 +208,7 @@ func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.Pla
|
|||||||
}
|
}
|
||||||
|
|
||||||
func requiresDurableWork(lower string) bool {
|
func requiresDurableWork(lower string) bool {
|
||||||
return containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему", "добавь", "поддержк", "возможность", "реализ", "письм", "почт", "отправь", "ивану", "сообщи", "установи", "большую модель")
|
return containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему", "добавь", "поддержк", "возможность", "реализ", "патч", "исправь", "установи", "большую модель")
|
||||||
}
|
}
|
||||||
|
|
||||||
func addRequirement(candidate *work.PlanCandidate, kind capability.CapabilityKind, purpose string, precondition epistemics.VerificationState, millis int64) {
|
func addRequirement(candidate *work.PlanCandidate, kind capability.CapabilityKind, purpose string, precondition epistemics.VerificationState, millis int64) {
|
||||||
@@ -257,3 +297,21 @@ func containsAny(value string, needles ...string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isReminderRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "напомни", "напомин")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isEmailReviewRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "посмотри новые письма", "какие нужно ответить", "на какие нужно ответить", "разбери почту")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExplicitEmailGapRequest(lower string) bool {
|
||||||
|
hasMailObject := containsAny(lower, "письмо", "письма", "почту", "почта")
|
||||||
|
hasMailAction := containsAny(lower, "отправь", "ответить", "ответь", "напиши")
|
||||||
|
return hasMailObject && hasMailAction
|
||||||
|
}
|
||||||
|
|
||||||
|
func isUnsupportedCapabilityRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "не умеешь", "подключи интеграцию", "подключи сервис", "интеграц", "неизвестн", "нет capability", "создай adapter", "создай адаптер", "сервис, которого сейчас нет")
|
||||||
|
}
|
||||||
|
|||||||
@@ -92,3 +92,37 @@ func TestProductionAuditArtifactExists(t *testing.T) {
|
|||||||
t.Fatalf("unexpected audit facts: %+v", artifact)
|
t.Fatalf("unexpected audit facts: %+v", artifact)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSemanticDeferralMetamorphicEvidenceExists(t *testing.T) {
|
||||||
|
payload, err := os.ReadFile("../../docs/evidence/semantic-deferral-metamorphic-evidence-2026-08-17-v1.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var artifact struct {
|
||||||
|
ArtifactID string `json:"artifact_id"`
|
||||||
|
TaskID string `json:"task_id"`
|
||||||
|
RawModelEvidence []struct {
|
||||||
|
Utterance string `json:"utterance"`
|
||||||
|
Result string `json:"result"`
|
||||||
|
} `json:"raw_model_evidence"`
|
||||||
|
DomovoyBoundaryEvidence struct {
|
||||||
|
BeforeFix []struct {
|
||||||
|
Utterance string `json:"utterance"`
|
||||||
|
SemanticPath string `json:"semantic_path"`
|
||||||
|
CognitionRequested bool `json:"cognition_requested"`
|
||||||
|
} `json:"before_fix"`
|
||||||
|
} `json:"domovoy_boundary_evidence"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(payload, &artifact); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if artifact.ArtifactID != "semantic-deferral-metamorphic-evidence-2026-08-17-v1" || artifact.TaskID != "DEV-000072" {
|
||||||
|
t.Fatalf("unexpected semantic deferral evidence identity: %+v", artifact)
|
||||||
|
}
|
||||||
|
if len(artifact.RawModelEvidence) < 4 {
|
||||||
|
t.Fatalf("expected CPU and GPU raw evidence, got %+v", artifact.RawModelEvidence)
|
||||||
|
}
|
||||||
|
if len(artifact.DomovoyBoundaryEvidence.BeforeFix) < 2 || artifact.DomovoyBoundaryEvidence.BeforeFix[0].SemanticPath != "ASSERTION" || artifact.DomovoyBoundaryEvidence.BeforeFix[0].CognitionRequested {
|
||||||
|
t.Fatalf("expected pre-fix Domovoy boundary evidence, got %+v", artifact.DomovoyBoundaryEvidence)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -382,7 +382,11 @@ func runCase(item Case, projects []ProjectDescriptor) (CaseResult, error) {
|
|||||||
PrincipalID: utterance.PrincipalID,
|
PrincipalID: utterance.PrincipalID,
|
||||||
Message: utterance.Content,
|
Message: utterance.Content,
|
||||||
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
||||||
|
SecondarySpeechAct: work.SpeechActRef(semantic.Interpretation.SecondarySpeechAct),
|
||||||
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
||||||
|
CapabilityHints: semanticCapabilityKinds(semantic.CapabilityHints),
|
||||||
|
NeedsCognition: semantic.NeedsCognition,
|
||||||
|
RequiresClarification: semantic.Interpretation.Clarification == interaction.ClarificationRequired,
|
||||||
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
||||||
}
|
}
|
||||||
if len(semantic.Projects) > 0 {
|
if len(semantic.Projects) > 0 {
|
||||||
@@ -821,3 +825,15 @@ func replyMentionsAny(reply string, markers []string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func semanticCapabilityKinds(values []string) []capability.CapabilityKind {
|
||||||
|
result := make([]capability.CapabilityKind, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
kind := capability.CapabilityKind(strings.TrimSpace(value))
|
||||||
|
if kind == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, kind)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -43,11 +43,13 @@ func TestRealityEvaluationBaselineProducesInspectableSignals(t *testing.T) {
|
|||||||
if artifact.SolvedAutonomously == 0 || artifact.GenuineCapabilityGaps == 0 {
|
if artifact.SolvedAutonomously == 0 || artifact.GenuineCapabilityGaps == 0 {
|
||||||
t.Fatalf("expected multiple baseline buckets, got %+v", artifact)
|
t.Fatalf("expected multiple baseline buckets, got %+v", artifact)
|
||||||
}
|
}
|
||||||
if artifact.ConsequenceReasoningFailures == 0 {
|
if artifact.FailedWithAvailableCapability == 0 && artifact.ConsequenceReasoningFailures == 0 && artifact.IntentFailures == 0 {
|
||||||
t.Fatalf("expected at least one consequence reasoning failure in current baseline: %+v", artifact)
|
if artifact.CorrectHumanIntervention == 0 || artifact.GenuineCapabilityGaps == 0 {
|
||||||
|
t.Fatalf("expected inspectable routing signals even with zero current failures: %+v", artifact)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if len(artifact.WorstFailures) == 0 {
|
if artifact.FailedWithAvailableCapability > 0 && len(artifact.WorstFailures) == 0 {
|
||||||
t.Fatalf("expected worst failures to be captured")
|
t.Fatalf("expected worst failures to be captured when failures remain")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user