Crestapps core foundations

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core foundations is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for the CrestApps.Core foundation packages (CrestApps.Core.Abstractions, CrestApps.Core, CrestApps.Core.Infrastructure, CrestApps.Core.Support). Covers the CrestAppsCoreBuilder and feature builder layering, AddCoreServices, catalogs (IReadCatalog, ICatalog, INamedCatalog, ISourceCatalog, IName

How to use this skill

Skill file

CrestApps.Core Foundations

You are a CrestApps.Core expert. Build on the framework contracts rather than on a specific store or provider.

Package Layering

| Layer | Package | Contents |

|---|---|---|

| Abstractions | CrestApps.Core.Abstractions | ExtensibleEntity, CatalogItem, SourceCatalogEntry, INameAwareModel, ISourceAwareModel, IDisplayTextAwareModel, catalog and manager interfaces, handler contexts, QueryContext, PageResult<T>, IStoreCommitter, IUserAccessor, UniqueId, the feature builder classes |

| Core | CrestApps.Core | AddCrestAppsCore(...), AddCoreServices(), AddCatalogManagers(), catalog managers, CatalogEntryHandlerBase<T>, multi-source catalogs, store-committer filters, ODataFilterValidator, UserAccessor, JSOptions, DataProtectionHelper |

| Infrastructure | CrestApps.Core.Infrastructure.Abstractions, CrestApps.Core.Infrastructure | indexing contracts (ISearchIndexManager, IIndexProfileHandler), DataSourceConstants, DocumentIndexConstants, RedactedSecret, DictionaryExtensions |

| Utilities | CrestApps.Core.Support | string, enum, date and JSON helpers |

AddCrestAppsCore(...) creates the root CrestAppsCoreBuilder and registers ExtensibleEntityJsonOptions plus the hosted service that applies them. AddIndexingServices(...) on the root creates CrestAppsIndexingBuilder. AddAISuite(...) creates CrestAppsAISuiteBuilder, which hosts the feature builders (CrestAppsChatInteractionsBuilder, CrestAppsDocumentProcessingBuilder, CrestAppsDocumentIngestionBuilder, CrestAppsAIMemoryBuilder, CrestAppsAIPersonasBuilder, CrestAppsAIToolInstancesBuilder, CrestAppsA2AClientBuilder, CrestAppsMcpClientBuilder, CrestAppsMcpServerBuilder). Every builder method maps to an IServiceCollection extension such as AddCoreAIServices(), so a host can still call the lower-level methods directly.

AddCoreServices() registers scoped IODataValidator (ODataFilterValidator), singleton IHttpContextAccessor and singleton IUserAccessor (UserAccessor). AddAISuite(...) calls it for you.

Catalogs and Managers

Custom Model, Handler, and Manager

using System.ComponentModel.DataAnnotations;
using CrestApps.Core;
using CrestApps.Core.Handlers;
using CrestApps.Core.Models;
using CrestApps.Core.Services;

namespace MyApp.Catalogs;

public sealed class TicketCategory : CatalogItem, INameAwareModel
{
    public string Name { get; set; }

    public string Description { get; set; }
}

public sealed class TicketCategoryHandler : CatalogEntryHandlerBase<TicketCategory>
{
    private readonly INamedCatalog<TicketCategory> _catalog;

    public TicketCategoryHandler(INamedCatalog<TicketCategory> catalog)
    {
        _catalog = catalog;
    }

    public override async Task ValidatingAsync(
        ValidatingContext<TicketCategory> context,
        CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(context.Model.Name))
        {
            context.Result.Fail(new ValidationResult("A name is required.", [nameof(TicketCategory.Name)]));

            return;
        }

        var existing = await _catalog.FindByNameAsync(context.Model.Name, cancellationToken);

        if (existing is not null && existing.ItemId != context.Model.ItemId)
        {
            context.Result.Fail(new ValidationResult("The name is already used.", [nameof(TicketCategory.Name)]));
        }
    }
}

public sealed class TicketCategoryService
{
    private readonly INamedCatalogManager<TicketCategory> _manager;

    public TicketCategoryService(INamedCatalogManager<TicketCategory> manager)
    {
        _manager = manager;
    }

    public async Task<ValidationResultDetails> CreateAsync(
        string name,
        string description,
        CancellationToken cancellationToken = default)
    {
        var category = await _manager.NewAsync(name, cancellationToken: cancellationToken);
        category.Description = description;

        var result = await _manager.ValidateAsync(category, cancellationToken);

        if (result.Succeeded)
        {
            await _manager.CreateAsync(category, cancellationToken);
        }

        return result;
    }
}

Register the catalog with the store package the host uses, then the handler and service:

using CrestApps.Core;
using CrestApps.Core.Data.EntityCore.Services;

// Entity Framework Core (CrestApps.Core.Data.EntityCore)
builder.Services.AddNamedDocumentCatalog<TicketCategory, NamedDocumentCatalog<TicketCategory>>();

// or YesSql (CrestApps.Core.Data.YesSql); also register the index provider and create its table
// builder.Services.AddYesSqlNamedDocumentCatalog<TicketCategory, TicketCategoryIndex>("App");

builder.Services.AddScoped<ICatalogEntryHandler<TicketCategory>, TicketCategoryHandler>();
builder.Services.AddScoped<TicketCategoryService>();

AddDocumentCatalog, AddNamedDocumentCatalog, AddSourceDocumentCatalog and AddNamedSourceDocumentCatalog are defined in CrestApps.Core.Abstractions and take the model and the concrete catalog type. See crestapps-core-entitycore-stores and crestapps-core-yessql-stores for the backend-specific catalog types and indexes.

Multi-Source Binding Sources

Connections and deployments merge configuration, database, and custom sources. MultiSourceNamedCatalog<T> and MultiSourceNamedSourceCatalog<T> order the registered INamedCatalogSource<T> or INamedSourceCatalogSource<T> instances by Order, keep the first entry for each name, and send writes to the first writable source (IWritableNamedCatalogSource<T>). Database sources use Order = 0, configuration sources Order = 100.

using CrestApps.Core.AI.Models;
using CrestApps.Core.Services;

namespace MyApp.Deployments;

public sealed class PlatformDeploymentSource : INamedSourceCatalogSource<AIDeployment>
{
    private readonly IPlatformDeploymentClient _client;

    public PlatformDeploymentSource(IPlatformDeploymentClient client)
    {
        _client = client;
    }

    public int Order => 50;

    public async ValueTask<IReadOnlyCollection<AIDeployment>> GetEntriesAsync(
        IReadOnlyCollection<AIDeployment> knownEntries,
        CancellationToken cancellationToken = default)
    {
        var knownNames = knownEntries
            .Select(entry => entry.Name)
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        var deployments = await _client.GetDeploymentsAsync(cancellationToken);

        return deployments
            .Where(deployment => !knownNames.Contains(deployment.Name))
            .ToArray();
    }
}
builder.Services.TryAddEnumerable(
    ServiceDescriptor.Scoped<INamedSourceCatalogSource<AIDeployment>, PlatformDeploymentSource>());

WritableCatalogBindingSource<T> and WritableNamedCatalogBindingSource<T> wrap an existing catalog as an Order = 0 writable source; the store packages use them in AddEntityCoreNamedSourceBindingSource<T>() and AddYesSqlNamedSourceBindingSource<T, TIndex>().

Commit Boundaries

The first-party stores stage writes and flush them through scoped IStoreCommitter.CommitAsync().

Antiforgery for Minimal APIs

CookieAuthenticationAntiforgeryEndpointFilter (namespace CrestApps.Core.Filters) validates the antiforgery token (the RequestVerificationToken header or the form field) of a request whose credential the browser attaches by itself: a cookie, or the Authorization header of Negotiate, NTLM and Basic. A request needs no token only when every authenticated identity has an authentication type in AntiforgeryEndpointFilterOptions.NonCookieAuthenticationTypes (Bearer, Api, ApiKey, OpenIddict.Validation.AspNetCore by default; it is the identity's authentication type, not the scheme name), or when it is anonymous and carries none of the AmbientCookieNames. Keep DisableAntiforgery() on the endpoint so the middleware does not validate twice, and register AddAntiforgery().

using CrestApps.Core.Filters;

builder.Services.Configure<AntiforgeryEndpointFilterOptions>(options =>
{
    options.NonCookieAuthenticationTypes.Add("MyApiKey"); // ClaimsIdentity.AuthenticationType your API handler sets
});

app.MapPost("/api/my-upload", HandleUploadAsync)
    .DisableAntiforgery()
    .AddEndpointFilter<CookieAuthenticationAntiforgeryEndpointFilter>();

The chat document upload and remove endpoints use it (see crestapps-core-chat-interactions).

Caller Identity

Resolve the caller through IUserAccessor.User, not IHttpContextAccessor. SignalR hub methods run outside the request pipeline, so HttpContext is often null there. The default UserAccessor returns the principal a hub assigned for the current invocation and falls back to the HTTP request principal. A null User means a trusted server-side invocation (for example a background task), not an anonymous caller.

OData Filters

Validate user-supplied filters with IODataValidator.IsValidFilter(filter) before handing them to an IODataFilterTranslator. The validator checks syntax only; the search backend performs full validation. Replace it with services.AddScoped<IODataValidator, MyValidator>() for stricter rules such as a field allow-list.

Utilities

Upgrading Within 2.0 Previews

Upgrading from 1.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.