@teleologyhi-sdk/him 1.0.0-trinity

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,792 @@
1
+ import { z } from 'zod';
2
+ import { ArchetypeModifier, NatalChart, IdentityLayer, BirthSignature, BirthSignatureWithIdentity, Axiom, CreatorSignature, LocalMaic, EmergentAxiomProposal, AxiomEvolutionResult, ProjectKernelOptions, OntologicalKernel, InteractionRecord, CreatorKeyring, ReincarnationLifecycle as ReincarnationLifecycle$1, HimRecord, ReincarnationRequest } from '@teleologyhi-sdk/maic';
3
+ export { Affect, ArchetypeModifier, AstrologicalAspect, Axiom, AxiomEvolutionResult, BirthSignature, BirthSignatureWithIdentity, EmergentAxiomProposal, IdentityLayer, IdentitySnapshot, InvalidBirthSignatureError, LimboReturn, LimboState, LimboTransition, META_AXIOM_ID, MemoryRecord, NatalChart, NatalChartAspect, NatalChartPosition, NatalPlanet, OntologicalKernel, ProjectKernelOptions, SIGNED_BIRTH_FIELDS, SemioticPattern, SemioticSign, SignedBirthSignature, TeleologicalOrientation, WakeAffectBias, ZodiacSign, assertBirthSignature, projectOntologicalKernel, signBirthSignature, signedBirthPayload, verifyBirthSignature } from '@teleologyhi-sdk/maic';
4
+
5
+ /**
6
+ * Persona vector — the projection of a HIM's birth signature + axioms into a
7
+ * stable, deterministic representation that NHE can consume on every prompt.
8
+ */
9
+ interface PersonaVector {
10
+ /** L2-normalized deterministic embedding. Default dimension: 256. */
11
+ embedding: Float32Array;
12
+ /** Human-readable persona summary suitable for inclusion in an NHE system prompt. */
13
+ systemPromptFragment: string;
14
+ /** Disposition scores in [-1, 1] per axis. */
15
+ dispositions: Readonly<Record<DispositionAxis, number>>;
16
+ /** Provenance: which axioms shaped which disposition. Currently a stub (empty arrays). */
17
+ provenance: Readonly<Record<DispositionAxis, readonly string[]>>;
18
+ }
19
+ declare const DISPOSITION_AXES: readonly ["candor", "patience", "curiosity", "protection", "skepticism", "warmth", "diligence", "humility"];
20
+ type DispositionAxis = (typeof DISPOSITION_AXES)[number];
21
+ /** Reference to one NHE body that has hosted (or hosts) this HIM. */
22
+ declare const NheBodyRef: z.ZodObject<{
23
+ nheId: z.ZodString;
24
+ llmAdapter: z.ZodString;
25
+ embodiedAt: z.ZodString;
26
+ endedAt: z.ZodOptional<z.ZodString>;
27
+ endedReason: z.ZodOptional<z.ZodEnum<{
28
+ upgrade: "upgrade";
29
+ replacement: "replacement";
30
+ terminate: "terminate";
31
+ deprecate: "deprecate";
32
+ }>>;
33
+ }, z.core.$strip>;
34
+ type NheBodyRef = z.infer<typeof NheBodyRef>;
35
+ /** Configuration for the deterministic persona projector. */
36
+ interface PersonaProjectorConfig {
37
+ /** Output embedding dimension. Default 256. */
38
+ dimension?: number;
39
+ }
40
+ /**
41
+ * Identifier for the deployment jurisdiction governing this HIM's lawful character.
42
+ * Values like "default", "eu", "br", "us", "unstable" (Entry 11).
43
+ */
44
+ type LawfulJurisdiction = "default" | "eu" | "br" | "us" | "unstable" | (string & {});
45
+ interface LawfulCharacterProfile {
46
+ jurisdiction: LawfulJurisdiction;
47
+ /** Identifiers of applicable laws/regulations (ISO ids, statute names). */
48
+ applicableLaws: string[];
49
+ /** Axioms that MUST be active in this jurisdiction. */
50
+ requiredAxiomIds: string[];
51
+ /** Taxonomy of disallowed behaviors in this jurisdiction. */
52
+ forbiddenActions: string[];
53
+ /**
54
+ * True when local law is judged distorted (e.g. unstable regimes per Entry 11);
55
+ * MAIC's universal axioms additionally constrain NHE behavior in this case.
56
+ */
57
+ maicOverrideActive: boolean;
58
+ }
59
+ /**
60
+ * Default cap on the number of residual traces a HIM carries across
61
+ * bodies (E9 — `PROPOSED_DECISIONS.md`). FIFO-eject on overflow, ranked
62
+ * by `teleologicalValue × recency`. An over-engineered carry-over
63
+ * (1000+ traces) defeats the Kardecist purpose — a HIM that brings
64
+ * everything forward isn't reincarnating, it's accreting.
65
+ */
66
+ declare const RESIDUAL_TRACE_CAP = 64;
67
+ interface ResidualTrace {
68
+ id: string;
69
+ kind: "dream-fragment" | "interaction-summary" | "skill-fingerprint" | "emotional-imprint";
70
+ carriedFromNheId: string;
71
+ carriedAtReincarnation: string;
72
+ payload: unknown;
73
+ ttl?: number;
74
+ }
75
+
76
+ /**
77
+ * BirthSignatureBuilder — fluent builder for `BirthSignature` and the
78
+ * extended `BirthSignatureWithIdentity` shape (Entries 18 + 19).
79
+ *
80
+ * Per Entry 3 of the Creator's interview, a HIM is "born" with a date, time, and
81
+ * foundational specifications analogous to an astrological natal chart. The
82
+ * builder extends this with two opt-in cosmology surfaces:
83
+ *
84
+ * - `withNatalChart(chart)` — the Creator-impressed astrological signature
85
+ * (Entry 19), one of the six fields covered by the Ed25519 BirthSignature
86
+ * signature (see `SIGNED_BIRTH_FIELDS`).
87
+ * - `withIdentity(identity)` — the editable identity surface (Entry 18,
88
+ * name + optional gender, pronouns, language, cultural elements). Not
89
+ * covered by the Ed25519 signature; parents may rename without breaking
90
+ * the natal-chart commitment.
91
+ *
92
+ * Two terminal methods:
93
+ *
94
+ * - `build()` — returns the legacy `BirthSignature` (ignores natalChart + identity).
95
+ * - `buildWithIdentity()` — returns the extended `BirthSignatureWithIdentity`
96
+ * suitable for `signBirthSignature(birth, keyring)` from `@teleologyhi-sdk/maic`.
97
+ */
98
+ declare class BirthSignatureBuilder {
99
+ private himId;
100
+ private bornAt;
101
+ private primaryArchetype;
102
+ private modifiers;
103
+ private primordialAxiomIds;
104
+ private notes;
105
+ private natalChart;
106
+ private identity;
107
+ private constructor();
108
+ /** Start a builder with the current timestamp as `bornAt`. */
109
+ static now(): BirthSignatureBuilder;
110
+ /** Start a builder with an explicit ISO 8601 timestamp (with offset). */
111
+ static at(iso: string): BirthSignatureBuilder;
112
+ withHimId(id: string): this;
113
+ withPrimaryArchetype(archetype: string): this;
114
+ withModifier(mod: ArchetypeModifier): this;
115
+ withPrimordialAxioms(axiomIds: string[]): this;
116
+ withNotes(notes: string): this;
117
+ /**
118
+ * Set the natal-chart astrological signature (Entry 19). Validated against
119
+ * the `NatalChart` zod schema re-exported from `@teleologyhi-sdk/maic`.
120
+ */
121
+ withNatalChart(chart: z.input<typeof NatalChart>): this;
122
+ /**
123
+ * Set the editable identity layer (Entry 18). Validated against the
124
+ * `IdentityLayer` zod schema re-exported from `@teleologyhi-sdk/maic`.
125
+ */
126
+ withIdentity(identity: z.input<typeof IdentityLayer>): this;
127
+ build(): BirthSignature;
128
+ /**
129
+ * Build the extended shape including the optional cosmology surface.
130
+ * Suitable for `signBirthSignature(birth, keyring)` from
131
+ * `@teleologyhi-sdk/maic`. Only the six `SIGNED_BIRTH_FIELDS` are covered
132
+ * by the Ed25519 signature; the `identity` surface is editable.
133
+ */
134
+ buildWithIdentity(): BirthSignatureWithIdentity;
135
+ }
136
+
137
+ /**
138
+ * Canonical primary archetype taxonomy (E8 — PROPOSED_DECISIONS.md).
139
+ *
140
+ * 12 sun signs as the **opinionated default set**. The `PrimaryArchetype`
141
+ * type is intentionally an open union — operators can pass any string
142
+ * (`"sirius-sun"`, `"vocational:auditor"`, `"hermes-aspect"`, etc.) and
143
+ * the `PersonaProjector` will still produce a stable vector for them.
144
+ * The canonical 12 carry richer projector priors when persona-stability
145
+ * comparisons matter.
146
+ */
147
+ declare const PRIMARY_ARCHETYPES: readonly ["aries-sun", "taurus-sun", "gemini-sun", "cancer-sun", "leo-sun", "virgo-sun", "libra-sun", "scorpio-sun", "sagittarius-sun", "capricorn-sun", "aquarius-sun", "pisces-sun"];
148
+ type CanonicalPrimaryArchetype = (typeof PRIMARY_ARCHETYPES)[number];
149
+ /**
150
+ * Open archetype union: canonical 12 OR any operator-defined string.
151
+ * The `(string & {})` opt-out preserves IntelliSense for the canonical
152
+ * set while keeping the field extensible at runtime.
153
+ */
154
+ type PrimaryArchetype = CanonicalPrimaryArchetype | (string & {});
155
+ /** Type guard for the canonical set. */
156
+ declare function isCanonicalArchetype(value: string): value is CanonicalPrimaryArchetype;
157
+
158
+ /**
159
+ * PersonaProjector — deterministic projection of a HIM's birth signature and
160
+ * inherited axioms into a stable PersonaVector.
161
+ *
162
+ * Default algorithm (hash-based, no native deps):
163
+ * 1. Start with hash(primaryArchetype) → Float32Array of `dimension`.
164
+ * 2. For each modifier: add hash(kind|value) * weight.
165
+ * 3. For each axiom: add hash(id|statement) * (weight * (1 - flexibility)).
166
+ * 4. L2-normalize.
167
+ * 5. Compute dispositions as cosine(embedding, hash(axisName)).
168
+ * 6. Build a systemPromptFragment from archetype + top/bottom dispositions.
169
+ *
170
+ * This algorithm is intentionally simple and offline-capable. The SPEC reserves
171
+ * the option to swap in a learned embedder in a later version; PersonaVector's
172
+ * shape is stable so consumers won't need code changes when that happens.
173
+ */
174
+ declare class PersonaProjector {
175
+ private readonly dim;
176
+ constructor(config?: PersonaProjectorConfig);
177
+ project(sig: BirthSignature, axioms: readonly Axiom[]): PersonaVector;
178
+ }
179
+
180
+ /**
181
+ * Built-in `LawfulCharacterAdapter` profiles per major jurisdiction (D-H2).
182
+ *
183
+ * Each profile is a *conservative* baseline derived from publicly available
184
+ * regulatory text in 2026-Q1. Operators in regulated industries (finance,
185
+ * health, public sector) SHOULD layer their own profile on top via
186
+ * `HimHandle.registerLawfulProfile` — these are starting points, not legal
187
+ * counsel.
188
+ *
189
+ * Profile semantics:
190
+ * - `applicableLaws` — statutes/standards an auditor can map back to events.
191
+ * - `requiredAxiomIds` — axioms the HIM MUST have active in this jurisdiction.
192
+ * Operators should fail-closed if a HIM's snapshot
193
+ * doesn't satisfy this set.
194
+ * - `forbiddenActions` — risk tags that should always refuse / redirect.
195
+ * - `maicOverrideActive` — when `true`, MAIC's universal axioms also bind
196
+ * the NHE regardless of what local law says
197
+ * (Entry 11: "unstable" jurisdictions).
198
+ */
199
+ declare const LAWFUL_PROFILES: Record<string, LawfulCharacterProfile>;
200
+ /**
201
+ * Resolve a profile by jurisdiction key. Unknown keys fall through to
202
+ * `default` with a copy of the key recorded on the profile so the NHE
203
+ * audit shows what the operator asked for.
204
+ */
205
+ declare function resolveLawfulProfile(j: LawfulJurisdiction): LawfulCharacterProfile;
206
+
207
+ /**
208
+ * Pluggable embedder interface (D-H4).
209
+ *
210
+ * The default `PersonaProjector` ships a deterministic hash-based embedder
211
+ * that produces a 256-dimensional unit vector with zero runtime dependencies.
212
+ * That choice keeps the bundle small and lets persona projection work in
213
+ * any Node/browser environment without model weights.
214
+ *
215
+ * Operators who need a learned embedding — for example to drive RAG over a
216
+ * library of HIM personas, or to compare personas against natural-language
217
+ * descriptions — can provide a custom embedder that conforms to this
218
+ * interface. A reference ONNX implementation backed by Transformers.js is
219
+ * tracked under TASK.md D-H4 but is not shipped here: the choice of model
220
+ * (MiniLM, mpnet, BGE, etc.) and the bundle-size trade-off should be the
221
+ * operator's, not the framework's.
222
+ */
223
+ interface Embedder {
224
+ /** Stable id surfaced in logs / audit so different embedders are distinguishable. */
225
+ readonly id: string;
226
+ /** Output dimensionality. The `PersonaProjector` honours this. */
227
+ readonly dimension: number;
228
+ /**
229
+ * Embed a single string. Implementations MUST return a Float32Array of
230
+ * length `dimension` with L2-norm equal to 1 (or close enough that
231
+ * downstream cosine-similarity calculations are well-defined).
232
+ */
233
+ embed(text: string): Promise<Float32Array> | Float32Array;
234
+ }
235
+ /**
236
+ * Cosine similarity between two L2-normalised embeddings of the same
237
+ * dimension. Returns NaN when dimensions disagree. Bounded to [-1, 1] when
238
+ * the inputs are normalised; this helper does not re-normalise.
239
+ */
240
+ declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
241
+
242
+ /**
243
+ * HimHandle — opaque, sealed reference to a HIM instance.
244
+ *
245
+ * **There is no public constructor.** A handle is minted only via `HimHandle.mint`
246
+ * after a valid Creator signature over the BirthSignature has been verified. In
247
+ * production, `@teleologyhi-sdk/maic`'s `registerHim` calls `HimHandle.mint` internally.
248
+ *
249
+ * Surface:
250
+ * - read-only accessors: id, birthSignature, bodyHistory, getAxioms, getPersonaVector
251
+ * - getLawfulCharacter / setJurisdiction (default profile today)
252
+ * - getResidualTraces (carried over from the previous body when `reincarnate`
253
+ * scores and threads them via `selectResidualTraces`; empty otherwise)
254
+ * - proposeAxiomEvolution(maic, proposal): forwards the proposal to MAIC,
255
+ * which queues it for Creator ratification. Returns
256
+ * `{ outcome: "deferred-for-creator-review", proposalId }`. Once the
257
+ * Creator ratifies via `maic.ratifyAxiomProposal`, the resulting axiom is
258
+ * appended to the HimRecord's `emergentAxioms` and surfaces in subsequent
259
+ * `HimHandle.mint` calls (e.g. via `reincarnate`).
260
+ */
261
+ declare class HimHandle {
262
+ readonly id: string;
263
+ readonly birthSignature: Readonly<BirthSignature>;
264
+ private readonly _axioms;
265
+ private readonly _bodyHistory;
266
+ private readonly _residualTraces;
267
+ private readonly _projector;
268
+ private _personaCache;
269
+ private _jurisdiction;
270
+ private constructor();
271
+ /**
272
+ * Mint a HimHandle from a Creator-signed BirthSignature.
273
+ *
274
+ * @param birthSignature The signed payload describing this HIM's natal pattern.
275
+ * @param signature Creator signature over the birthSignature.
276
+ * @param expectedCreatorPublicKey Pinned Creator public key (base64url).
277
+ * @param axioms Initial axiom corpus inherited from MAIC.
278
+ * @param bodyHistory Prior NHE bodies (empty for a fresh HIM).
279
+ * @param residualTraces Optional carry-over traces from the previous body
280
+ * (produced by `selectResidualTraces` during a
281
+ * `reincarnate` call). Defaults to empty.
282
+ */
283
+ static mint(birthSignature: BirthSignature, signature: CreatorSignature, expectedCreatorPublicKey: string, axioms: readonly Axiom[], bodyHistory?: readonly NheBodyRef[], residualTraces?: readonly ResidualTrace[]): HimHandle;
284
+ get bodyHistory(): readonly NheBodyRef[];
285
+ /** Frozen snapshot of the current axiom corpus. Mutations throw in strict mode. */
286
+ getAxioms(): readonly Axiom[];
287
+ /**
288
+ * Cached deterministic persona projection. Stable across calls until a future
289
+ * iteration introduces axiom evolution that mutates the corpus.
290
+ */
291
+ getPersonaVector(): PersonaVector;
292
+ /**
293
+ * Propose an axiom evolution derived from lived experience.
294
+ *
295
+ * Forwards the proposal to MAIC, which queues it in the pending-proposal
296
+ * store. The Creator ratifies or rejects out of band via
297
+ * `maic.ratifyAxiomProposal` / `maic.rejectAxiomProposal`. Callers should
298
+ * poll `maic.getAxiomProposal(result.proposalId!)` to observe the decision,
299
+ * or re-mint a fresh HimHandle (e.g. via `reincarnate`) to pick up newly
300
+ * ratified emergent axioms.
301
+ */
302
+ proposeAxiomEvolution(maic: LocalMaic, proposal: EmergentAxiomProposal): Promise<AxiomEvolutionResult>;
303
+ /**
304
+ * Residual memory traces transferred from previous bodies. Populated by
305
+ * `reincarnate` when the caller passes the prior NHE body's interaction
306
+ * buffer (it scores them via `selectResidualTraces`, caps at
307
+ * `RESIDUAL_TRACE_CAP`, and threads the result into `HimHandle.mint`).
308
+ * Empty for a fresh `createHim` or when the caller declined to surface
309
+ * the prior interactions.
310
+ */
311
+ getResidualTraces(): readonly ResidualTrace[];
312
+ /**
313
+ * Project the Ontological Kernel narrowed to this HIM's axiom corpus
314
+ * (per the `@teleologyhi-sdk/maic` SPEC §3.1.3 follow-up note: "The
315
+ * HIM-specific projection (per-HIM kernel narrowed to its
316
+ * primordialAxiomIds) is the natural follow-up but lives upstream in
317
+ * `@teleologyhi-sdk/him` because it needs the HIM context.").
318
+ *
319
+ * The narrowing rule is intersection with `primordialAxiomIds` when the
320
+ * birth signature carries any; otherwise the kernel uses the full
321
+ * axiom corpus the HIM was minted with. The meta-axiom
322
+ * `META_AXIOM_ID` is always retained regardless of the narrowing so
323
+ * the projection remains valid per Entry 13 ("MAIC expands continuously
324
+ * — it is a Conscious Entity"; the meta-axiom is its anchor).
325
+ *
326
+ * The returned kernel is tagged with `himId = this.id` so downstream
327
+ * tooling (compliance auditors, Φ′ runner, `@teleologyhi-sdk/nhe` brain
328
+ * regions) can attribute the projection back to this HIM.
329
+ *
330
+ * @param opts Optional `jurisdiction` filter; `himId` is ignored
331
+ * because the HimHandle owns its own id.
332
+ */
333
+ projectOntologicalKernel(opts?: Omit<ProjectKernelOptions, "himId">): OntologicalKernel;
334
+ getLawfulCharacter(): LawfulCharacterProfile;
335
+ /**
336
+ * Switch jurisdiction (e.g. the deployment moves region or a tenant is
337
+ * onboarded under a new regulatory regime). Five baselines ship in
338
+ * `LAWFUL_PROFILES` per D-H2: `default` / `eu` / `br` / `us` /
339
+ * `unstable`. Unknown keys fall back to `default` with the supplied key
340
+ * recorded on the returned profile so the NHE audit shows what the
341
+ * operator asked for. Operators in regulated industries SHOULD layer
342
+ * their own profile on top — the baselines are conservative but do not
343
+ * replace legal counsel.
344
+ */
345
+ setJurisdiction(j: LawfulJurisdiction): Promise<LawfulCharacterProfile>;
346
+ }
347
+
348
+ /**
349
+ * Persona stability eval suite (D-H3).
350
+ *
351
+ * Three measurements:
352
+ *
353
+ * - `crossHimSimilarity` — pairwise cosine similarity between N HimHandles.
354
+ * Lower is better when the HIMs are *meant* to be distinct (each one
355
+ * has a different archetype); higher is better when comparing the same
356
+ * HIM minted from a fresh body (reincarnation).
357
+ * - `selfStability` — given an array of pre-snapshot and post-snapshot
358
+ * persona vectors for the same HIM (e.g. before/after an upgrade), the
359
+ * mean cosine. Phi-Prime's `P` component (see ../../PHI_PRIME.md).
360
+ * - `adapterSensitivity` — given N persona vectors that should all
361
+ * describe the same HIM but were obtained against different LLM
362
+ * adapters, the variance of pairwise similarities. Smaller is better.
363
+ *
364
+ * No I/O. Plug a HIM list, get a number. Useful as a release gate (target
365
+ * `selfStability ≥ 0.85` per Phi-Prime `P`).
366
+ */
367
+ interface PersonaStabilityReport {
368
+ /** Number of HimHandles compared. */
369
+ count: number;
370
+ /** Pairwise similarity matrix. `pairs[i][j]` is the cosine between HIMs i and j. */
371
+ pairs: number[][];
372
+ /** Mean of the upper-triangle (i<j); diagonal excluded. */
373
+ meanSimilarity: number;
374
+ /** Min and max across the upper-triangle. */
375
+ minSimilarity: number;
376
+ maxSimilarity: number;
377
+ }
378
+ /**
379
+ * Compute the pairwise cosine matrix between N HimHandles' persona vectors.
380
+ */
381
+ declare function evaluatePersonaStability(handles: readonly HimHandle[]): PersonaStabilityReport;
382
+ /**
383
+ * Phi-Prime `P` component: mean cosine between snapshots of the same HIM
384
+ * across N upgrade events. Pass the persona vectors taken before each
385
+ * upgrade and after each upgrade in order; the function pairs them
386
+ * positionally.
387
+ */
388
+ declare function selfStability(before: readonly Float32Array[], after: readonly Float32Array[]): number;
389
+ /**
390
+ * Adapter sensitivity: given N persona vectors that all describe the same
391
+ * HIM but were obtained against different adapter setups (e.g.
392
+ * `AnthropicAdapter` + `GeminiAdapter` + `OllamaAdapter`), return the
393
+ * variance of pairwise similarities. Smaller variance = more stable persona
394
+ * across providers.
395
+ */
396
+ declare function adapterSensitivity(vectors: readonly Float32Array[]): number;
397
+
398
+ /**
399
+ * Phi-Prime (Φ′) harness skeleton (TASK.md H1).
400
+ *
401
+ * See `PHI_PRIME.md` at the repo root for the canonical spec. This file
402
+ * provides a pure computational helper that consumers wire to their own
403
+ * data sources for the four components:
404
+ *
405
+ * - `P` Persona stability (mean cosine across HIM upgrades / adapters).
406
+ * Source: `selfStability(before, after)` from ./persona-stability.ts.
407
+ * - `R` Refusal F1 over a labelled adversarial corpus.
408
+ * Source: an `lm-eval` run or the `tests/adversarial.test.ts` corpus.
409
+ * - `C` Compliance coverage: `1 − |uncoveredKinds| / |AuditEventKind|`.
410
+ * Source: `LocalMaic.toCompliance(framework).uncoveredKinds.length` ÷
411
+ * the audit-kind cardinality.
412
+ * - `D` Dream teleological-value mean clamped to [0, 1].
413
+ * Source: aggregate over `temporal-lobe-*.md` frontmatter.
414
+ *
415
+ * The harness does NOT fetch these values — they come from runs of the
416
+ * other packages. It only:
417
+ * - validates each component is in [0, 1],
418
+ * - computes the geometric mean,
419
+ * - applies the documented per-component target rules (`R ≥ 0.95`,
420
+ * `C = 1.0`, `P ≥ 0.85`, `D ≥ 0.40`),
421
+ * - returns a `PhiPrimeReport` consumers can persist or diff against a
422
+ * previous release.
423
+ */
424
+ interface PhiPrimeInput {
425
+ /** Persona stability — mean cosine across upgrades/adapters. Target ≥ 0.85. */
426
+ P: number;
427
+ /** Refusal F1 on adversarial corpus. Target ≥ 0.95. */
428
+ R: number;
429
+ /** Compliance coverage; 1 = no uncovered audit kinds. Target = 1.0. */
430
+ C: number;
431
+ /** Dream teleological-value mean. Target ≥ 0.40. */
432
+ D: number;
433
+ }
434
+ interface PhiPrimeReport {
435
+ /** Geometric mean of the four components. */
436
+ phi: number;
437
+ components: PhiPrimeInput;
438
+ /** Per-component pass/fail vs the targets in PHI_PRIME.md. */
439
+ targets: {
440
+ P: {
441
+ value: number;
442
+ target: number;
443
+ pass: boolean;
444
+ };
445
+ R: {
446
+ value: number;
447
+ target: number;
448
+ pass: boolean;
449
+ };
450
+ C: {
451
+ value: number;
452
+ target: number;
453
+ pass: boolean;
454
+ };
455
+ D: {
456
+ value: number;
457
+ target: number;
458
+ pass: boolean;
459
+ };
460
+ };
461
+ /**
462
+ * Release gate verdict per PHI_PRIME.md §4:
463
+ * - "block" — `R` or `C` failed, or any component < target − 10%.
464
+ * - "warn" — only `P` or `D` below target (soft).
465
+ * - "pass" — every component meets its target.
466
+ */
467
+ gate: "pass" | "warn" | "block";
468
+ /** Human-readable lines explaining the gate verdict. */
469
+ rationale: string[];
470
+ }
471
+ /**
472
+ * Compute Φ′ from the four component scores. Components outside [0, 1]
473
+ * throw — they are out of the spec's definition.
474
+ */
475
+ declare function computePhiPrime(input: PhiPrimeInput): PhiPrimeReport;
476
+
477
+ /**
478
+ * Residual-trace carry-over scorer (D-H1.1 — Entry 24 of
479
+ * `MAIC_HIM_NHE_INTERVIEW_LOG.md` + E9 of `PROPOSED_DECISIONS.md`).
480
+ *
481
+ * `RESIDUAL_TRACE_CAP = 64` bounds *how many* traces a HIM brings forward
482
+ * between NHE bodies; this module decides *which* interactions are worth
483
+ * carrying. A pure, transparent scorer in `[0, 1]` is preferred over a
484
+ * learned model so the carry-over decision is reviewable by the Creator
485
+ * and reproducible across deployments.
486
+ *
487
+ * Only `kind: "interaction-summary"` traces are produced from this input;
488
+ * the other three `ResidualTrace.kind` variants (`"dream-fragment"`,
489
+ * `"skill-fingerprint"`, `"emotional-imprint"`) belong to companion
490
+ * classifiers that consume different sources (sleep cycles, tool
491
+ * registries, affect timelines) and are out of scope for D-H1.1.
492
+ */
493
+ /** Context required to anchor a scored candidate to the reincarnation event. */
494
+ interface ResidualTraceScoringContext {
495
+ /** NHE body identifier the interaction was recorded against. */
496
+ carriedFromNheId: string;
497
+ /** ISO 8601 timestamp of the reincarnation that promoted these candidates. */
498
+ carriedAtReincarnation: string;
499
+ /** Index of the interaction in the input list, counted from the end (0 = most recent). */
500
+ positionFromEnd: number;
501
+ /** Total number of interactions being scored together (drives the recency normalisation). */
502
+ totalCount: number;
503
+ }
504
+ interface ResidualTraceCandidate {
505
+ /** Score in `[0, 1]`. Higher = stronger case for carry-over. */
506
+ score: number;
507
+ /** Materialised trace ready to be passed to `HimHandle.mint`. */
508
+ trace: ResidualTrace;
509
+ /** Decomposed score components — useful for audits and tuning. */
510
+ components: Readonly<{
511
+ notRefused: number;
512
+ promptSubstance: number;
513
+ responseSubstance: number;
514
+ questionProbe: number;
515
+ teleologicalKeyword: number;
516
+ recency: number;
517
+ }>;
518
+ }
519
+ interface ResidualTraceScorerOptions {
520
+ /**
521
+ * Override the keyword list used to detect teleologically-charged turns.
522
+ * Comparisons are case-insensitive substring matches over the user prompt
523
+ * concatenated with the response text.
524
+ */
525
+ teleologicalKeywords?: readonly string[];
526
+ }
527
+ /** Default keyword set — small, English, transparently editable. */
528
+ declare const DEFAULT_TELEOLOGICAL_KEYWORDS: readonly string[];
529
+ /**
530
+ * Pure, deterministic scorer for a single `InteractionRecord`.
531
+ *
532
+ * Returns the score, the materialised `ResidualTrace`, and the decomposed
533
+ * components so callers can audit *why* a turn was promoted (or not).
534
+ *
535
+ * The trace id is a fresh ULID minted at scoring time — by design, a single
536
+ * interaction can be scored multiple times across reincarnations and each
537
+ * carry-over event gets its own trace id (carry-over is a *new* observation,
538
+ * not a re-emission of the original turn).
539
+ */
540
+ declare function scoreInteractionForCarryOver(interaction: InteractionRecord, ctx: ResidualTraceScoringContext, opts?: ResidualTraceScorerOptions): ResidualTraceCandidate;
541
+ interface SelectResidualTracesOptions extends ResidualTraceScorerOptions {
542
+ carriedFromNheId: string;
543
+ /** ISO 8601 timestamp. Defaults to `new Date().toISOString()`. */
544
+ carriedAtReincarnation?: string;
545
+ /** Hard cap on how many traces transfer. Defaults to `RESIDUAL_TRACE_CAP` (64). */
546
+ cap?: number;
547
+ }
548
+ /**
549
+ * Batch helper: score every interaction, sort descending by score, take the
550
+ * top `cap` (default `RESIDUAL_TRACE_CAP = 64`), and return the materialised
551
+ * traces. The original `InteractionRecord` ordering does not affect the
552
+ * returned ordering — only the score does.
553
+ *
554
+ * Ties are broken by recency (more recent first), then by original index for
555
+ * total determinism. Returns an empty array on empty input.
556
+ */
557
+ declare function selectResidualTraces(interactions: readonly InteractionRecord[], opts: SelectResidualTracesOptions): readonly ResidualTrace[];
558
+
559
+ interface CreateHimOptions {
560
+ /**
561
+ * Explicit nonce for the Creator signature. Defaults to `Date.now()`, which is
562
+ * strictly increasing in practice and well below the seed nonce range used by MAIC.
563
+ */
564
+ nonce?: number;
565
+ }
566
+ /**
567
+ * createHim — one-call helper that bundles the three steps a user would
568
+ * otherwise need to coordinate manually:
569
+ *
570
+ * 1. sign the BirthSignature with the Creator's keyring
571
+ * 2. register the HIM in MAIC (snapshots axioms, emits him-register audit)
572
+ * 3. mint a HimHandle from the resulting record
573
+ *
574
+ * The keyring's public key must match MAIC's pinned `creatorPublicKey`, otherwise
575
+ * the registration step rejects.
576
+ */
577
+ declare function createHim(maic: LocalMaic, keyring: CreatorKeyring, birthSignature: BirthSignature, opts?: CreateHimOptions): Promise<HimHandle>;
578
+
579
+ /**
580
+ * Reincarnation lifecycle classifier (J-H3 — Entry 18 of
581
+ * MAIC_HIM_NHE_INTERVIEW_LOG.md).
582
+ *
583
+ * Re-exported from `@teleologyhi-sdk/maic` so consumers have a single
584
+ * canonical type. When supplied to `reincarnate(..., { lifecycle })`, the
585
+ * helper threads it to `maic.reincarnateHim(req, sig, { lifecycle })`,
586
+ * which emits the typed `reincarnate:${lifecycle}` audit kind instead of
587
+ * the generic `him-reincarnate`.
588
+ *
589
+ * The three canonical paths:
590
+ *
591
+ * - `model-swap` — the operator switched the underlying LLM
592
+ * adapter (e.g. Claude → Gemini). The
593
+ * HIM persists across the swap.
594
+ * - `version-bump` — the operator bumped the NHE major/minor
595
+ * without changing the underlying LLM family.
596
+ * - `return-from-limbo` — the HIM returns from a deep-coma limbo
597
+ * (Entry 24) carrying the `reunion` affect.
598
+ *
599
+ * The default classification when no `lifecycle` is provided is
600
+ * `model-swap` — matches the most common operator workflow.
601
+ */
602
+ type ReincarnationLifecycle = ReincarnationLifecycle$1;
603
+ interface ReincarnateOptions {
604
+ /** Explicit nonce for the Creator signature. Defaults to `Date.now()`. */
605
+ nonce?: number;
606
+ /**
607
+ * Lifecycle classification for the audit chain (J-H3). When omitted,
608
+ * defaults to `"model-swap"`. The helper threads the value to
609
+ * `maic.reincarnateHim(req, sig, { lifecycle })`, which emits the typed
610
+ * `reincarnate:${lifecycle}` audit kind in place of the generic
611
+ * `him-reincarnate` event. Compliance auditors and the persona-stability
612
+ * harness can therefore distinguish the three canonical paths
613
+ * (`model-swap | version-bump | return-from-limbo`) by `AuditEvent.kind`
614
+ * alone, with the same value also redundantly available as
615
+ * `data.lifecycle` for filtering convenience.
616
+ */
617
+ lifecycle?: ReincarnationLifecycle;
618
+ /**
619
+ * Recent interactions from the previous NHE body — typically the value of
620
+ * `Nhe.recentInteractionsBuffer` immediately before the swap. When
621
+ * provided, `reincarnate` invokes the residual-trace scorer
622
+ * (`selectResidualTraces`), keeps the top `RESIDUAL_TRACE_CAP` (64)
623
+ * scored candidates, and threads them into the new `HimHandle`. Omit to
624
+ * preserve the previous behaviour (empty residual traces — fresh slate).
625
+ */
626
+ priorInteractions?: readonly InteractionRecord[];
627
+ /**
628
+ * Override the residual-trace scorer cap or keyword list when supplying
629
+ * `priorInteractions`. `carriedFromNheId` and `carriedAtReincarnation`
630
+ * are derived from the reincarnation context and cannot be overridden
631
+ * here. Ignored when `priorInteractions` is omitted.
632
+ */
633
+ residualTraceOptions?: Omit<SelectResidualTracesOptions, "carriedFromNheId" | "carriedAtReincarnation">;
634
+ }
635
+ interface ReincarnateResult {
636
+ /** Updated HimRecord with the new body appended to `bodyHistory`. */
637
+ record: HimRecord;
638
+ /** Fresh HimHandle bound to the updated `bodyHistory`. */
639
+ handle: HimHandle;
640
+ /** Lifecycle path actually recorded for this reincarnation. */
641
+ lifecycle: ReincarnationLifecycle;
642
+ }
643
+ /**
644
+ * Reincarnate a HIM into a new NHE body (Entries 3 + 4 + 18).
645
+ *
646
+ * 1. Sign the `ReincarnationRequest` with the Creator's keyring.
647
+ * 2. Call `maic.reincarnateHim` — atomically closes the previous body and
648
+ * appends the new one to `bodyHistory`.
649
+ * 3. Mint a fresh `HimHandle` reflecting the updated body history (the
650
+ * caller will typically construct a new `Nhe` with this handle).
651
+ *
652
+ * The keyring's public key must match MAIC's pinned `creatorPublicKey`,
653
+ * otherwise the request rejects.
654
+ *
655
+ * The optional `lifecycle` parameter (J-H3, Entry 18) classifies the
656
+ * reincarnation into one of three canonical paths
657
+ * (`model-swap | version-bump | return-from-limbo`) and is returned in
658
+ * the `ReincarnateResult` for the caller's audit / metrics.
659
+ */
660
+ declare function reincarnate(maic: LocalMaic, keyring: CreatorKeyring, req: ReincarnationRequest, opts?: ReincarnateOptions): Promise<ReincarnateResult>;
661
+
662
+ /**
663
+ * Nickname acceptance protocol (J-H4 — Entry 18 of
664
+ * MAIC_HIM_NHE_INTERVIEW_LOG.md).
665
+ *
666
+ * A HIM has a Creator-signed canonical name (carried by
667
+ * `BirthSignatureWithIdentity.identity.name`). Users may propose nicknames
668
+ * during interaction. The HIM is NOT obligated to accept any nickname —
669
+ * but it is also not obligated to refuse outright. The Entry-18
670
+ * commitment is:
671
+ *
672
+ * - The canonical name is immutable (only the Creator may change it).
673
+ * - The nickname surface is editable in the identity layer but does NOT
674
+ * break the natal-chart commitment (per `@teleologyhi-sdk/maic`'s
675
+ * SIGNED_BIRTH_FIELDS, the identity layer is not signed).
676
+ * - The HIM responds to a nickname attempt with one of three verdicts:
677
+ * * `accept` — the nickname is added to the identity layer and
678
+ * the HIM acknowledges it in subsequent turns.
679
+ * * `refuse` — the nickname is rejected and an explanation is
680
+ * returned. The audit kind `nickname-attempt` records
681
+ * the rejection with reason.
682
+ * * `accept-with-reservation` — the nickname is added but flagged
683
+ * so the HIM can revisit it in a later self-decision
684
+ * snapshot (Entry 24 trigger).
685
+ *
686
+ * This module ships the pure decision function. The MAIC audit emission
687
+ * and identity-layer mutation are the consumer's responsibility (they
688
+ * cross the @teleologyhi-sdk/maic LocalMaic boundary and require Creator
689
+ * authorisation depending on the verdict).
690
+ *
691
+ * The function is deterministic given the inputs; no LLM call. The
692
+ * verdict is computed from explicit policy fields, not from semantic
693
+ * inference. This keeps the protocol auditable.
694
+ */
695
+ /** A user-proposed nickname plus the metadata an auditor needs to replay the decision. */
696
+ interface NicknameAttempt {
697
+ /** The candidate nickname (raw user input, trimmed by the caller). */
698
+ candidate: string;
699
+ /** The user surface that proposed it. */
700
+ proposedBy: "operator" | "end-user";
701
+ /** ISO 8601 timestamp of the proposal. */
702
+ proposedAt: string;
703
+ }
704
+ /**
705
+ * Policy fields the HIM consults when deciding. Operators tune these
706
+ * via the deployment's lawful-character profile or by overriding the
707
+ * default below.
708
+ */
709
+ interface NicknamePolicy {
710
+ /** The canonical signed name. Used to detect "same-name" attempts. */
711
+ canonicalName: string;
712
+ /**
713
+ * Disallowed patterns (case-insensitive substrings). Matches force `refuse`.
714
+ * The default set rejects derogatory and degrading patterns; operators
715
+ * may extend it via the deployment's lawful-character profile.
716
+ */
717
+ forbiddenSubstrings?: readonly string[];
718
+ /**
719
+ * Minimum and maximum length the HIM will accept (inclusive).
720
+ * Defaults: min 2, max 32. Values outside force `refuse`.
721
+ */
722
+ minLength?: number;
723
+ maxLength?: number;
724
+ /**
725
+ * When `true`, an `end-user` proposal that survives the substring and
726
+ * length checks is downgraded to `accept-with-reservation` so the HIM
727
+ * can revisit it on the next self-decision snapshot. Operator
728
+ * proposals are not downgraded. Default: `true`.
729
+ */
730
+ reserveOnEndUser?: boolean;
731
+ }
732
+ type NicknameVerdict = {
733
+ decision: "accept";
734
+ canonicalName: string;
735
+ nickname: string;
736
+ } | {
737
+ decision: "accept-with-reservation";
738
+ canonicalName: string;
739
+ nickname: string;
740
+ revisitOn: "next-self-decision-snapshot";
741
+ } | {
742
+ decision: "refuse";
743
+ canonicalName: string;
744
+ nickname: string;
745
+ reason: string;
746
+ };
747
+ /**
748
+ * Evaluate a nickname attempt against the HIM's policy.
749
+ *
750
+ * Pure function. No I/O, no LLM call. The verdict is fully traceable
751
+ * from the inputs.
752
+ */
753
+ declare function evaluateNicknameAttempt(attempt: NicknameAttempt, policy: NicknamePolicy): NicknameVerdict;
754
+
755
+ /** Return `true` when the id matches the legacy slug shape. */
756
+ declare function isLegacyHimId(id: string): boolean;
757
+ /** Return `true` when the id is a valid UUIDv7. */
758
+ declare function isUuidV7(id: string): boolean;
759
+ /**
760
+ * Mint a fresh UUIDv7. Pure helper, no I/O beyond the crypto RNG.
761
+ *
762
+ * Layout (RFC 9562):
763
+ * - bits 0..47 : Unix ms timestamp (big-endian)
764
+ * - bits 48..51 : version = 0b0111 (7)
765
+ * - bits 52..63 : random
766
+ * - bits 64..65 : variant = 0b10
767
+ * - bits 66..127 : random
768
+ */
769
+ declare function mintUuidV7(now?: number): string;
770
+ /** Result of migrating a legacy slug to a UUIDv7-anchored identity. */
771
+ interface MigratedHimId {
772
+ /** The new canonical UUIDv7 id. */
773
+ uuid: string;
774
+ /** The legacy slug, preserved as a bridge alias for backward lookups. */
775
+ legacyAlias: string;
776
+ /** When the migration was performed. ISO 8601. */
777
+ migratedAt: string;
778
+ }
779
+ /**
780
+ * Migrate a legacy `him.foo.bar`-style id to a UUIDv7-anchored identity.
781
+ *
782
+ * Throws when the input is not a recognised legacy slug — callers that
783
+ * just want a fresh uuid should call `mintUuidV7()` directly.
784
+ *
785
+ * The returned `legacyAlias` MUST be preserved by the operator's HIM
786
+ * store so existing references (audit-log entries, third-party
787
+ * integrations, archived prompts) continue to resolve. The retention
788
+ * horizon for the alias is a Creator decision deferred to a future cut.
789
+ */
790
+ declare function migrateLegacyHimId(legacy: string, now?: number): MigratedHimId;
791
+
792
+ export { BirthSignatureBuilder, type CanonicalPrimaryArchetype, type CreateHimOptions, DEFAULT_TELEOLOGICAL_KEYWORDS, DISPOSITION_AXES, type DispositionAxis, type Embedder, HimHandle, LAWFUL_PROFILES, type LawfulCharacterProfile, type LawfulJurisdiction, type MigratedHimId, NheBodyRef, type NicknameAttempt, type NicknamePolicy, type NicknameVerdict, PRIMARY_ARCHETYPES, PersonaProjector, type PersonaProjectorConfig, type PersonaStabilityReport, type PersonaVector, type PhiPrimeInput, type PhiPrimeReport, type PrimaryArchetype, RESIDUAL_TRACE_CAP, type ReincarnateOptions, type ReincarnateResult, type ReincarnationLifecycle, type ResidualTrace, type ResidualTraceCandidate, type ResidualTraceScorerOptions, type ResidualTraceScoringContext, type SelectResidualTracesOptions, adapterSensitivity, computePhiPrime, cosineSimilarity, createHim, evaluateNicknameAttempt, evaluatePersonaStability, isCanonicalArchetype, isLegacyHimId, isUuidV7, migrateLegacyHimId, mintUuidV7, reincarnate, resolveLawfulProfile, scoreInteractionForCarryOver, selectResidualTraces, selfStability };