Skip to content
中文

FamilyDefinition ​

KIT · interface · Type contract

App-owned hooks and limits for one family.

Import ​

ts
import type { FamilyDefinition } from '@jangts/agent-core/kits/family';
js
/** @typedef {import('@jangts/agent-core/kits/family').FamilyDefinition} FamilyDefinition */

Other public entry points:@jangts/agent-core/types, @jangts/agent-core/structs, @jangts/agent-core/kits, @jangts/agent-core/kits/family.

Definition ​

ts
interface FamilyDefinition<State, App>

Type parameters ​

Type parameterConstraintDefault type
State——
App——

Field structure ​

FieldTypeRequiredDescription
storeFamilyStore<State>RequiredRead-only. See the type definition and usage context.
maxVersionsnumber | undefinedOptionalRead-only. Maximum retained versions; older versions are dropped once the bound is exceeded.
retentionMsnumber | undefinedOptionalRead-only. Retention window in milliseconds, measured from a write.
now(() => number) | undefinedOptionalRead-only. Clock override for timestamps and expiry; defaults to Date.now.
isState(value: unknown) => value is StateRequiredValidates a state loaded from the store before it is used.
authorize(operation: FamilyOperation, record: FamilyRecord<State> | undefined, context: OperationContext<App>) => MaybePromise<void>RequiredGuards one mutation; called before any write, including with an absent record.
validate(candidate: FamilyVersion<State>, context: OperationContext<App>) => MaybePromise<void>RequiredValidates a candidate version before it is appended.
merge((input: { base: State; target: State; source: State; }, context: OperationContext<App>) => MaybePromise<{ value?: State; conflicts: readonly string[]; }>) | undefinedOptionalResolves a three-way merge. Returns the merged state and any conflicts. A non-empty conflict list aborts the merge without writing a version, so value is ignored in that case.

Member index ​

MemberPurpose
isStateValidates a state loaded from the store before it is used.
authorizeGuards one mutation; called before any write, including with an absent record.
validateValidates a candidate version before it is appended.

Member details ​

isState ​

Validates a state loaded from the store before it is used.

ts
FamilyDefinition.isState(value: unknown): value is State

Validates a state loaded from the store before it is used.

ParameterTypePassingDescription
valueunknownRequired—

Returns: boolean.

authorize ​

Guards one mutation; called before any write, including with an absent record.

ts
FamilyDefinition.authorize(operation: FamilyOperation, record: FamilyRecord<State> | undefined, context: OperationContext<App>): MaybePromise<void>

Guards one mutation; called before any write, including with an absent record.

ParameterTypePassingDescription
operation"create" | "fork" | "merge" | "promote"Required—
recordFamilyRecord<State> | undefinedRequired—
contextOperationContext<App>Required—
Fields of context
FieldTypeRequiredDescription
appunknown extends App ? App : Readonly<App>RequiredRead-only. See the type definition and usage context.
loggerSubFlowLog | undefinedOptionalRead-only. Explicit optional recorder for this operation; never inferred from diagnostics.
signalAbortSignalRequiredRead-only. Non-optional cancellation signal; never undefined once execution has started.
diagnosticsDiagnosticContext | undefinedOptionalRead-only. Diagnostic scope of the enclosing call, when recording is enabled.

Optional shapes of Parameter record: choose one shape; required fields for each branch are listed separately.

Branch 1

undefined

Branch 2
FieldTypeRequiredDescription
idstringRequiredRead-only. Family id; also the store key.
revisionnumberRequiredRead-only. Optimistic concurrency token; every accepted mutation increments it by one.
activeIdstringRequiredRead-only. Id of the active version; promotion moves this pointer.
expiresAtMsnumberRequiredRead-only. Instant after which the record is no longer retained, in epoch milliseconds.
versionsreadonly FamilyVersion<State>[]RequiredRead-only. Versions in creation order; bounded by maxVersions when configured.

Returns: MaybePromise<void>.

Awaited value: void.

validate ​

Validates a candidate version before it is appended.

ts
FamilyDefinition.validate(candidate: FamilyVersion<State>, context: OperationContext<App>): MaybePromise<void>

Validates a candidate version before it is appended.

ParameterTypePassingDescription
candidateFamilyVersion<State>Required—
contextOperationContext<App>Required—
Fields of candidate
FieldTypeRequiredDescription
idstringRequiredRead-only. Unique version id, generated by the Kit.
parentIdstring | undefinedOptionalRead-only. Version this one was forked or merged from, when lineage applies.
mergeSourceIdstring | undefinedOptionalRead-only. Source version of a merge; present only on versions created by merge.
baseIdstring | undefinedOptionalRead-only. Common ancestor recorded for fork/merge bookkeeping.
branchAgentBranchRequiredRead-only. Core branch snapshot paired with this state.
stateStateRequiredRead-only. App state; treated as immutable by the Kit and snapshotted on write.
createdAtMsnumberRequiredRead-only. Creation instant in epoch milliseconds.
Fields of context
FieldTypeRequiredDescription
appunknown extends App ? App : Readonly<App>RequiredRead-only. See the type definition and usage context.
loggerSubFlowLog | undefinedOptionalRead-only. Explicit optional recorder for this operation; never inferred from diagnostics.
signalAbortSignalRequiredRead-only. Non-optional cancellation signal; never undefined once execution has started.
diagnosticsDiagnosticContext | undefinedOptionalRead-only. Diagnostic scope of the enclosing call, when recording is enabled.

Returns: MaybePromise<void>.

Awaited value: void.

Examples ​

Configure state checks, source verification, and three-way merge ​

Configuration · Node.js

ts
import { defineAgentFamily } from '@jangts/agent-core/kits/family';
import type { FamilyStore } from '@jangts/agent-core/kits/family';
import type { OperationContext } from '@jangts/agent-core';

type State = { goal: string; sourceRevision: string };
export function family<App>(store: FamilyStore<State>,
  authorize: (context: OperationContext<App>) => Promise<void>,
  verify: (state: State) => Promise<void>) {
  return defineAgentFamily<State, App>({
    store, maxVersions: 16, retentionMs: 7 * 86400000,
    isState: (value): value is State => !!value && typeof (value as State).goal === 'string'
      && typeof (value as State).sourceRevision === 'string',
    authorize: (_operation, _record, context) => authorize(context),
    validate: candidate => verify(candidate.state),
    async merge({ base, target, source }) {
      if (target.goal !== base.goal && source.goal !== base.goal && target.goal !== source.goal)
        return { conflicts: ['goal'] };
      return { value: target.goal === base.goal ? source : target, conflicts: [] };
    },
  });
}
js
import { defineAgentFamily } from '@jangts/agent-core/kits/family';
export function family(store, authorize, verify) {
    return defineAgentFamily({
        store, maxVersions: 16, retentionMs: 7 * 86400000,
        isState: (value) => !!value && typeof value.goal === 'string'
            && typeof value.sourceRevision === 'string',
        authorize: (_operation, _record, context) => authorize(context),
        validate: candidate => verify(candidate.state),
        async merge({ base, target, source }) {
            if (target.goal !== base.goal && source.goal !== base.goal && target.goal !== source.goal)
                return { conflicts: ['goal'] };
            return { value: target.goal === base.goal ? source : target, conflicts: [] };
        },
    });
}

Explicitly promote an approved candidate version ​

Extension · Node.js

The App calls this after real approval; promote still re-runs source, authorization, revision, and CAS checks.

ts
import type { AgentFamily } from '@jangts/agent-core/kits/family';
import type { OperationContext } from '@jangts/agent-core';

export async function activate<State, App>(family: AgentFamily<State, App>, id: string,
  candidateId: string, context: OperationContext<App>) {
  const record = await family.read(id, context);
  return family.promote({ id, revision: record.revision, candidateId,
    expectedActiveId: record.activeId }, context);
}
js
export async function activate(family, id, candidateId, context) {
    const record = await family.read(id, context);
    return family.promote({ id, revision: record.revision, candidateId,
        expectedActiveId: record.activeId }, context);
}

API reference, usage examples and developer guides.