Skip to main content

@specd/core — Overview

@specd/core is the domain library for SpecD. It contains all business logic — entities, use cases, ports, and errors — with zero I/O dependencies. The CLI, MCP server, and plugins are adapters that translate between their delivery mechanism and the core.

Who this documentation is for

docs/core/ targets integrators: developers who want to build a new delivery adapter (a CLI, an HTTP API, an IDE extension), implement a custom port (a database-backed repository, a remote schema registry), or consume the core as a standalone SDK.

If you are using the specd CLI or MCP server, you do not need to read these documents — the configuration reference and schema format reference are the right starting points.

Architecture

@specd/core is organized in three layers. The dependency flow is strictly one-way: domain has no dependencies, application depends on domain, infrastructure depends on application and domain.

┌──────────────────────────────────────────┐
│ domain/ │
│ Entities · Value objects · Errors │
│ No I/O. No external dependencies. │
└──────────────────┬───────────────────────┘

┌──────────────────▼───────────────────────┐
│ application/ │
│ Use cases · Ports (interfaces) │
│ Depends on domain only. │
└──────────────────┬───────────────────────┘

┌──────────────────▼───────────────────────┐
│ infrastructure/ │
│ Fs adapters · Git · Hooks │
│ Internal. Never imported directly. │
└──────────────────┬───────────────────────┘

┌──────────────────▼───────────────────────┐
│ composition/ │
│ Factory functions for adapter creation │
│ Exported. Returns abstract port types. │
└──────────────────────────────────────────┘

The infrastructure/ layer is internal — never import from it directly. Infrastructure adapters are created exclusively through the factory functions in composition/, which is the only layer permitted to instantiate them. Factories accept a discriminated union config (e.g. { type: 'fs', ... }) and return the abstract port type, keeping callers decoupled from the concrete implementation.

Public exports

@specd/core exports from a single entry point:

import { ... } from '@specd/core'       // domain + application + composition

Everything exported is a domain type (entity, value object, error, service), an application type (use case, port interface, error, config type), or a composition factory / adapter class.

What is exported

From the domain layer — entities:

ExportKindDescription
ChangeclassThe central entity representing an in-progress spec change.
SpecclassMetadata for a spec directory.
ChangeArtifactclassA single artifact file tracked within a change.
ArchivedChangeclassAn immutable historical record of a completed change.
DeltaclassA delta file record.
SYSTEM_ACTORconstThe built-in system actor identity used by automated operations.

From the domain layer — value objects:

ExportKindDescription
SpecPathclassValidated, immutable spec path value object.
ArtifactTypeclassDescribes a single artifact type as declared in the schema.
SchemaclassA fully-constructed schema with artifacts, workflow, and extraction.
ArtifactFileclassA spec-scoped artifact file record.
SpecArtifactclassA spec-scoped artifact record with metadata.
HookResultclassThe outcome of a run: hook execution.
ChangeStatetypeUnion of all valid lifecycle state strings.
ArtifactStatustype'missing' | 'in-progress' | 'complete' | 'skipped'
ArtifactScopetype'spec' | 'change' — whether an artifact lives on the spec or change.
ArtifactFormattype'markdown' | 'json' | 'yaml' | 'plaintext'
ActorIdentityinterface{ name: string; email: string } — actor identity.
ChangeEventtypeDiscriminated union of all change history event types.
WorkflowSteptypeA single step entry in the schema workflow. Includes requiresTaskCompletion.
HookEntrytypeA single hook declaration within a workflow step.
ValidationRuletypeA structural validation rule from the schema.
PreHashCleanuptypeA pre-hash substitution rule from the schema.
TaskCompletionChecktypePattern-based task completion check from the schema.
SelectortypeAn AST node selector used in validations and extractors.
ExtractortypeAn extraction configuration for metadata derivation.
MetadataExtractiontypeThe full metadata extraction block from a schema.
VALID_TRANSITIONSconstMap of valid transitions per lifecycle state.
isValidTransitionfunctionReturns whether a state transition is permitted.

From the domain layer — errors:

ExportCode
SpecdErrorabstract base class
InvalidStateTransitionErrorINVALID_STATE_TRANSITION
ApprovalRequiredErrorAPPROVAL_REQUIRED
HookFailedErrorHOOK_FAILED
ArtifactConflictErrorARTIFACT_CONFLICT
DeltaApplicationErrorDELTA_APPLICATION
InvalidSpecPathErrorINVALID_SPEC_PATH
InvalidChangeErrorINVALID_CHANGE
ArtifactNotOptionalErrorARTIFACT_NOT_OPTIONAL
SchemaValidationErrorSCHEMA_VALIDATION_ERROR
ConfigValidationErrorCONFIG_VALIDATION_ERROR
CorruptedManifestErrorCORRUPTED_MANIFEST
MetadataValidationErrorMETADATA_VALIDATION_ERROR
DependsOnOverwriteErrorDEPENDS_ON_OVERWRITE
HookNotFoundErrorHOOK_NOT_FOUND
StepNotValidErrorSTEP_NOT_VALID
PathTraversalErrorPATH_TRAVERSAL
UnsupportedPatternErrorUNSUPPORTED_PATTERN_ERROR
MissingDefaultWorkspaceErrorMISSING_DEFAULT_WORKSPACE
ArtifactParseErrorARTIFACT_PARSE_ERROR

From the domain layer — services:

ExportKindDescription
hashFilesfunctionApplies a hash function to each entry in a file-content map.
applyPreHashCleanupfunctionApplies schema-declared pre-hash substitutions to artifact content.
buildSchemafunctionConstructs a typed Schema from validated YAML data and templates.
buildSelectorfunctionConverts a raw selector shape into the domain Selector type.
mergeSchemaLayersfunctionApplies ordered customisation layers to a base schema's intermediate data.
parseSpecIdfunctionSplits a spec ID into workspace and capability path.
extractSpecSummaryfunctionExtracts a short summary from spec.md content.
extractMetadatafunctionOrchestrates metadata extraction across multiple artifact ASTs.
extractContentfunctionRuns a single extractor against an AST root.
evaluateRulesfunctionEvaluates validation rules against an AST, returning failures/warnings.
findNodesfunctionFinds all nodes matching a selector in an AST.
nodeMatchesfunctionTests whether a single AST node matches a selector.
selectBySelectorfunctionSelects nodes using a selector with parent-scope and index support.
collectAllNodesfunctionRecursively collects all nodes in an AST.
safeRegexfunctionCompiles a user-supplied pattern, returning null if invalid or unsafe.
inferFormatfunctionInfers artifact format from a filename extension.
shiftHeadingsfunctionShifts Markdown heading levels by a given delta.
selectByJsonPathfunctionNavigates an AST using a simplified JSONPath expression.
tokenizeJsonPathfunctionTokenises a JSONPath expression into segments.
specMetadataSchemaconstLenient Zod schema for reading metadata.json.
strictSpecMetadataSchemaconstStrict Zod schema for writing metadata.json.

From the application layer — ports:

ExportKindDescription
Repositoryabstract classBase class for all repository ports.
SpecRepositoryabstract classPort for reading and writing specs.
ChangeRepositoryabstract classPort for snapshot reads and serialized persisted change mutations.
ArchiveRepositoryabstract classPort for archiving and querying archived changes.
ContentHasherabstract classPort for computing content hashes.
YamlSerializerabstract classPort for serialising and deserialising YAML.
SchemaRegistryinterfacePort for discovering and resolving schemas.
HookRunnerinterfacePort for executing built-in run: hook commands.
ExternalHookRunnerinterfacePort for dispatching explicit external: workflow hooks by type.
ActorResolverinterfacePort for resolving the current actor identity.
VcsAdapterinterfacePort for querying version control system state.
FileReaderinterfacePort for reading files by absolute path.
ArtifactParserinterfacePort for parsing, applying deltas, and serialising artifacts.
ArtifactParserRegistrytypeReadonlyMap<string, ArtifactParser>
SchemaProviderinterfacePort for lazily resolving the active schema.
ConfigLoaderinterfacePort for loading and resolving specd.yaml.
ConfigWriterinterfacePort for writing project configuration.

From the application layer — use cases:

ExportKindDescription
CreateChangetypeCreates a new change.
GetStatustypeReports change state and artifact statuses.
TransitionChangetypeAdvances the change lifecycle and serializes the final manifest mutation.
DraftChangetypeShelves a change to drafts/ via serialized persistence.
RestoreChangetypeRecovers a drafted change via serialized persistence.
DiscardChangetypePermanently abandons a change via serialized persistence.
ApproveSpectypeRecords a spec approval through a serialized change mutation.
ApproveSignofftypeRecords a sign-off through a serialized change mutation.
ArchiveChangetypeFinalises and archives a completed change after serializing archiving.
ValidateArtifactstypeValidates artifact files and serializes completion/invalidation.
CompileContexttypeAssembles the AI instruction block for a lifecycle step.
ListChangestypeLists all active changes.
ListDraftstypeLists all drafted changes.
ListDiscardedtypeLists all discarded changes.
ListArchivedtypeLists all archived changes.
GetArchivedChangetypeRetrieves a single archived change.
EditChangetypeEdits change scope while serializing the persisted specIds update.
SkipArtifacttypeExplicitly skips an optional artifact on a change.
UpdateSpecDepstypeUpdates declared spec dependencies within a change.
ListSpecstypeLists all specs across all configured workspaces.
GetSpectypeLoads a spec and its artifact files.
SaveSpecMetadatatypeWrites validated metadata for a spec.
InvalidateSpecMetadatatypeRemoves content hashes from a spec's metadata.
GetActiveSchematypeResolves and returns the active schema.
ValidateSchematypeValidates a schema against structural rules.
ValidateSpecstypeValidates spec artifacts against schema structural rules.
GenerateSpecMetadatatypeGenerates deterministic metadata from schema extraction rules.
GetSpecContexttypeBuilds structured context entries for a spec.
RunStepHookstypeExecutes built-in run: hooks and explicit external: hooks for a workflow step and phase.
GetHookInstructionstypeReturns instruction: hook text for a workflow step and phase.
GetArtifactInstructiontypeReturns artifact-specific instructions, rules, and delta guidance.
InitProjecttypeInitialises a new specd project.
RecordSkillInstalltypeRecords that a skill set was installed for an agent.
GetSkillsManifesttypeReads the installed skills manifest from specd.yaml.
GetProjectContexttypeCompiles project-level context without a specific change or step.

From the application layer — config types:

ExportKindDescription
SpecdConfigtypeThe fully-resolved project configuration structure.
SpecdWorkspaceConfigtypePer-workspace configuration within SpecdConfig.
SpecdStorageConfigtypeStorage (paths) configuration within SpecdConfig.
SpecdContextEntrytypeA single entry in the project context block.
isSpecdConfigfunctionType guard for SpecdConfig.
TemplateExpanderclassExpands template variables in hook commands and instructions.

From the application layer — errors:

ExportCode
ChangeNotFoundErrorCHANGE_NOT_FOUND
ChangeAlreadyExistsErrorCHANGE_ALREADY_EXISTS
ApprovalGateDisabledErrorAPPROVAL_GATE_DISABLED
SchemaNotFoundErrorSCHEMA_NOT_FOUND
AlreadyInitialisedErrorALREADY_INITIALISED
ArtifactNotFoundErrorARTIFACT_NOT_FOUND
ParserNotRegisteredErrorPARSER_NOT_REGISTERED
SpecNotInChangeErrorSPEC_NOT_IN_CHANGE
SchemaMismatchErrorSCHEMA_MISMATCH
SpecNotFoundErrorSPEC_NOT_FOUND
WorkspaceNotFoundErrorWORKSPACE_NOT_FOUND

From the composition layer — kernel:

ExportKindDescription
createKernelfunctionConstructs all use cases from a SpecdConfig and returns them as a grouped Kernel.
KernelinterfaceThe fully-wired set of use cases, grouped as kernel.changes.*, kernel.specs.*, kernel.project.*.
KernelOptionsinterfaceOptions for createKernel, including extra node_modules paths for schema discovery.
createKernelBuilderfunctionCreates a fluent builder for additive kernel registrations before build().
KernelBuilderinterfaceFluent registration surface for parsers, storages, providers, and external hook runners.

From the composition layer — repository and schema factories:

ExportKindDescription
createSchemaRegistryfunctionConstructs a SchemaRegistry for the given adapter type ('fs').
createSchemaRepositoryfunctionConstructs a SchemaRepository for the given adapter type.
createConfigLoaderfunctionCreates a filesystem-backed ConfigLoader that discovers and parses specd.yaml.
createArtifactParserRegistryfunctionCreates the default ArtifactParserRegistry with all built-in format adapters registered.
KernelRegistryInputtypeAdditive registration inputs accepted by createKernel and createKernelBuilder.
KernelRegistryViewtypeFinal merged registry surface exposed as kernel.registry.
SpecStorageFactoryinterfaceNamed storage factory for workspace specs repositories.
SchemaStorageFactoryinterfaceNamed storage factory for workspace schema repositories.
ChangeStorageFactoryinterfaceNamed storage factory for active and shelved changes.
ArchiveStorageFactoryinterfaceNamed storage factory for archived changes.
VcsProviderinterfaceExternal-first VCS detection provider used by the kernel registry.
ActorProviderinterfaceExternal-first actor detection provider used by the kernel registry.

From the composition layer — VCS and actor adapters:

ExportKindDescription
createVcsAdapterfunctionAuto-detects the active VCS (git/hg/svn/null) and returns a VcsAdapter.
createVcsActorResolverfunctionAuto-detects the active VCS and returns an ActorResolver.
GitVcsAdapterclassVcsAdapter implementation for git repositories.
HgVcsAdapterclassVcsAdapter implementation for Mercurial repositories.
SvnVcsAdapterclassVcsAdapter implementation for Subversion repositories.
NullVcsAdapterclassNo-op VcsAdapter for projects without version control.
GitActorResolverclassActorResolver that reads actor identity from git config.
HgActorResolverclassActorResolver that reads actor identity from hg config.
SvnActorResolverclassActorResolver that reads actor identity from svn info.
NullActorResolverclassActorResolver that returns a fixed anonymous identity.
NodeContentHasherclassContentHasher implementation using Node.js crypto (SHA-256).
NodeYamlSerializerclassYamlSerializer implementation using the yaml npm package.

From the composition layer — use case creator functions (fs-wired):

These functions wire a single use case to the filesystem, creating a self-contained async function. Each accepts an options object with the relevant paths and config flags, and returns a callable function. Use them when you need only one or two use cases without constructing a full Kernel.

ExportDescription
createCreateChangeWires CreateChange to the fs.
createGetStatusWires GetStatus to the fs.
createTransitionChangeWires TransitionChange to the fs.
createDraftChangeWires DraftChange to the fs.
createRestoreChangeWires RestoreChange to the fs.
createDiscardChangeWires DiscardChange to the fs.
createApproveSpecWires ApproveSpec to the fs.
createApproveSignoffWires ApproveSignoff to the fs.
createArchiveChangeWires ArchiveChange to the fs.
createValidateArtifactsWires ValidateArtifacts to the fs.
createCompileContextWires CompileContext to the fs.
createListChangesWires ListChanges to the fs.
createListDraftsWires ListDrafts to the fs.
createListDiscardedWires ListDiscarded to the fs.
createListArchivedWires ListArchived to the fs.
createGetArchivedChangeWires GetArchivedChange to the fs.
createEditChangeWires EditChange to the fs.
createSkipArtifactWires SkipArtifact to the fs.
createListSpecsWires ListSpecs to the fs.
createGetSpecWires GetSpec to the fs.
createSaveSpecMetadataWires SaveSpecMetadata to the fs.
createInvalidateSpecMetadataWires InvalidateSpecMetadata to the fs.
createGetActiveSchemaWires GetActiveSchema to the fs.
createValidateSpecsWires ValidateSpecs to the fs.
createGetSpecContextWires GetSpecContext to the fs.
createInitProjectWires InitProject to the fs.
createRecordSkillInstallWires RecordSkillInstall to the fs.
createGetSkillsManifestWires GetSkillsManifest to the fs.
createGetProjectContextWires GetProjectContext to the fs.

Where to go next

DocumentRead when you need to…
domain-model.mdUnderstand the entities and value objects you receive as return values.
ports.mdImplement a repository, schema registry, or other port.
use-cases.mdWire and call use cases from your adapter.
errors.mdHandle errors from use cases and ports in your delivery layer.
services.mdUse domain service functions such as hashFiles and buildSchema.
examples/implementing-a-port.mdSee a full port implementation from scratch.