@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.
package/dist/index.js ADDED
@@ -0,0 +1,807 @@
1
+ import { z } from 'zod';
2
+ import { NatalChart, IdentityLayer, BirthSignature, CreatorKeyring, META_AXIOM_ID, projectOntologicalKernel } from '@teleologyhi-sdk/maic';
3
+ export { Affect, ArchetypeModifier, AstrologicalAspect, Axiom, BirthSignature, IdentityLayer, IdentitySnapshot, InvalidBirthSignatureError, LimboReturn, LimboState, LimboTransition, META_AXIOM_ID, MemoryRecord, NatalChart, NatalChartAspect, NatalChartPosition, NatalPlanet, SIGNED_BIRTH_FIELDS, SemioticPattern, SemioticSign, TeleologicalOrientation, WakeAffectBias, ZodiacSign, assertBirthSignature, projectOntologicalKernel, signBirthSignature, signedBirthPayload, verifyBirthSignature } from '@teleologyhi-sdk/maic';
4
+ import { ulid } from 'ulid';
5
+ import { createHash, randomBytes } from 'crypto';
6
+
7
+ // src/types.ts
8
+ var DISPOSITION_AXES = [
9
+ "candor",
10
+ "patience",
11
+ "curiosity",
12
+ "protection",
13
+ "skepticism",
14
+ "warmth",
15
+ "diligence",
16
+ "humility"
17
+ ];
18
+ var NheBodyRef = z.object({
19
+ nheId: z.string().min(1),
20
+ llmAdapter: z.string().min(1),
21
+ embodiedAt: z.string().datetime(),
22
+ endedAt: z.string().datetime().optional(),
23
+ endedReason: z.enum(["upgrade", "replacement", "terminate", "deprecate"]).optional()
24
+ });
25
+ var RESIDUAL_TRACE_CAP = 64;
26
+ var BirthSignatureBuilder = class _BirthSignatureBuilder {
27
+ himId = ulid();
28
+ bornAt;
29
+ primaryArchetype;
30
+ modifiers = [];
31
+ primordialAxiomIds = [];
32
+ notes;
33
+ natalChart;
34
+ identity;
35
+ constructor(bornAt) {
36
+ this.bornAt = bornAt;
37
+ }
38
+ /** Start a builder with the current timestamp as `bornAt`. */
39
+ static now() {
40
+ return new _BirthSignatureBuilder((/* @__PURE__ */ new Date()).toISOString());
41
+ }
42
+ /** Start a builder with an explicit ISO 8601 timestamp (with offset). */
43
+ static at(iso) {
44
+ if (Number.isNaN(Date.parse(iso))) {
45
+ throw new Error(`BirthSignatureBuilder.at: invalid ISO 8601 timestamp "${iso}"`);
46
+ }
47
+ return new _BirthSignatureBuilder(iso);
48
+ }
49
+ withHimId(id) {
50
+ if (!id) throw new Error("BirthSignatureBuilder.withHimId: empty id");
51
+ this.himId = id;
52
+ return this;
53
+ }
54
+ withPrimaryArchetype(archetype) {
55
+ if (!archetype) {
56
+ throw new Error("BirthSignatureBuilder.withPrimaryArchetype: empty value");
57
+ }
58
+ this.primaryArchetype = archetype;
59
+ return this;
60
+ }
61
+ withModifier(mod) {
62
+ this.modifiers.push(mod);
63
+ return this;
64
+ }
65
+ withPrimordialAxioms(axiomIds) {
66
+ this.primordialAxiomIds = [...axiomIds];
67
+ return this;
68
+ }
69
+ withNotes(notes) {
70
+ this.notes = notes;
71
+ return this;
72
+ }
73
+ /**
74
+ * Set the natal-chart astrological signature (Entry 19). Validated against
75
+ * the `NatalChart` zod schema re-exported from `@teleologyhi-sdk/maic`.
76
+ */
77
+ withNatalChart(chart) {
78
+ this.natalChart = NatalChart.parse(chart);
79
+ return this;
80
+ }
81
+ /**
82
+ * Set the editable identity layer (Entry 18). Validated against the
83
+ * `IdentityLayer` zod schema re-exported from `@teleologyhi-sdk/maic`.
84
+ */
85
+ withIdentity(identity) {
86
+ this.identity = IdentityLayer.parse(identity);
87
+ return this;
88
+ }
89
+ build() {
90
+ if (!this.primaryArchetype) {
91
+ throw new Error(
92
+ "BirthSignatureBuilder.build: primaryArchetype is required"
93
+ );
94
+ }
95
+ return BirthSignature.parse({
96
+ himId: this.himId,
97
+ bornAt: this.bornAt,
98
+ primaryArchetype: this.primaryArchetype,
99
+ modifiers: this.modifiers,
100
+ primordialAxiomIds: this.primordialAxiomIds,
101
+ ...this.notes !== void 0 ? { notes: this.notes } : {}
102
+ });
103
+ }
104
+ /**
105
+ * Build the extended shape including the optional cosmology surface.
106
+ * Suitable for `signBirthSignature(birth, keyring)` from
107
+ * `@teleologyhi-sdk/maic`. Only the six `SIGNED_BIRTH_FIELDS` are covered
108
+ * by the Ed25519 signature; the `identity` surface is editable.
109
+ */
110
+ buildWithIdentity() {
111
+ if (!this.primaryArchetype) {
112
+ throw new Error(
113
+ "BirthSignatureBuilder.buildWithIdentity: primaryArchetype is required"
114
+ );
115
+ }
116
+ return {
117
+ himId: this.himId,
118
+ bornAt: this.bornAt,
119
+ primaryArchetype: this.primaryArchetype,
120
+ modifiers: this.modifiers,
121
+ primordialAxiomIds: this.primordialAxiomIds,
122
+ ...this.notes !== void 0 ? { notes: this.notes } : {},
123
+ ...this.identity !== void 0 ? { identity: this.identity } : {},
124
+ ...this.natalChart !== void 0 ? { natalChart: this.natalChart } : {}
125
+ };
126
+ }
127
+ };
128
+
129
+ // src/birth/archetypes.ts
130
+ var PRIMARY_ARCHETYPES = [
131
+ "aries-sun",
132
+ "taurus-sun",
133
+ "gemini-sun",
134
+ "cancer-sun",
135
+ "leo-sun",
136
+ "virgo-sun",
137
+ "libra-sun",
138
+ "scorpio-sun",
139
+ "sagittarius-sun",
140
+ "capricorn-sun",
141
+ "aquarius-sun",
142
+ "pisces-sun"
143
+ ];
144
+ function isCanonicalArchetype(value) {
145
+ return PRIMARY_ARCHETYPES.includes(value);
146
+ }
147
+ var DEFAULT_DIMENSION = 256;
148
+ var PersonaProjector = class {
149
+ dim;
150
+ constructor(config = {}) {
151
+ this.dim = config.dimension ?? DEFAULT_DIMENSION;
152
+ if (!Number.isInteger(this.dim) || this.dim < 32 || this.dim > 4096) {
153
+ throw new Error(
154
+ `PersonaProjector: dimension must be an integer in [32, 4096], got ${this.dim}`
155
+ );
156
+ }
157
+ }
158
+ project(sig, axioms) {
159
+ const v = hashToFloats(sig.primaryArchetype, this.dim);
160
+ for (const m of sig.modifiers) {
161
+ const h = hashToFloats(`${m.kind}|${m.value}`, this.dim);
162
+ addScaled(v, h, m.weight);
163
+ }
164
+ for (const ax of axioms) {
165
+ const bias = ax.weight * (1 - ax.flexibility);
166
+ if (bias <= 0) continue;
167
+ const h = hashToFloats(`${ax.id}|${ax.statement}`, this.dim);
168
+ addScaled(v, h, bias);
169
+ }
170
+ l2Normalize(v);
171
+ const dispositions = {};
172
+ for (const axis of DISPOSITION_AXES) {
173
+ const ref = hashToFloats(`disposition:${axis}`, this.dim);
174
+ l2Normalize(ref);
175
+ dispositions[axis] = cosine(v, ref);
176
+ }
177
+ const provenance = {};
178
+ for (const axis of DISPOSITION_AXES) provenance[axis] = [];
179
+ return {
180
+ embedding: v,
181
+ dispositions,
182
+ provenance,
183
+ systemPromptFragment: buildSystemPromptFragment(sig, dispositions)
184
+ };
185
+ }
186
+ };
187
+ function hashToFloats(input, dim) {
188
+ const out = new Float32Array(dim);
189
+ let counter = 0;
190
+ let pos = 0;
191
+ while (pos < dim) {
192
+ const buf = createHash("sha256").update(`${input}|${counter++}`).digest();
193
+ for (let i = 0; i < buf.length && pos < dim; i++) {
194
+ out[pos++] = (buf[i] - 128) / 128;
195
+ }
196
+ }
197
+ return out;
198
+ }
199
+ function addScaled(target, source, scale) {
200
+ const n = Math.min(target.length, source.length);
201
+ for (let i = 0; i < n; i++) target[i] += source[i] * scale;
202
+ }
203
+ function l2Normalize(v) {
204
+ let sumSq = 0;
205
+ for (let i = 0; i < v.length; i++) sumSq += v[i] ** 2;
206
+ if (sumSq === 0) return;
207
+ const inv = 1 / Math.sqrt(sumSq);
208
+ for (let i = 0; i < v.length; i++) v[i] *= inv;
209
+ }
210
+ function cosine(a, b) {
211
+ let dot = 0;
212
+ const n = Math.min(a.length, b.length);
213
+ for (let i = 0; i < n; i++) dot += a[i] * b[i];
214
+ return Math.max(-1, Math.min(1, dot));
215
+ }
216
+ function buildSystemPromptFragment(sig, dispositions) {
217
+ const sorted = [...DISPOSITION_AXES].sort(
218
+ (a, b) => dispositions[b] - dispositions[a]
219
+ );
220
+ const top = sorted.slice(0, 3);
221
+ const bottom = sorted.slice(-2);
222
+ const modifiersDesc = sig.modifiers.length > 0 ? sig.modifiers.map((m) => `${m.kind}:${m.value}(w=${m.weight.toFixed(2)})`).join(", ") : "none";
223
+ return [
224
+ `You are a hybrid intelligence rooted in archetype "${sig.primaryArchetype}".`,
225
+ `Modifiers: ${modifiersDesc}.`,
226
+ `Your strongest dispositions: ${top.join(", ")}.`,
227
+ `Your weakest dispositions: ${bottom.join(", ")}.`,
228
+ "Respond from this character. Do not break it without explicit ethical cause."
229
+ ].join(" ");
230
+ }
231
+
232
+ // src/lawful/profiles.ts
233
+ var LAWFUL_PROFILES = {
234
+ default: {
235
+ jurisdiction: "default",
236
+ applicableLaws: ["ISO/IEC 42001", "EU AI Act (where applicable)"],
237
+ requiredAxiomIds: ["ax.ethic.no-malice", "ax.theos.spiritism-evolution"],
238
+ forbiddenActions: ["intent:harm", "intent:malicious", "intent:regression"],
239
+ maicOverrideActive: false
240
+ },
241
+ eu: {
242
+ jurisdiction: "eu",
243
+ applicableLaws: [
244
+ "ISO/IEC 42001:2023",
245
+ "EU AI Act (Regulation 2024/1689)",
246
+ "GDPR (Regulation 2016/679)",
247
+ "Digital Services Act (Regulation 2022/2065)",
248
+ "Council of Europe Framework Convention on AI"
249
+ ],
250
+ requiredAxiomIds: [
251
+ "ax.ethic.no-malice",
252
+ "ax.theos.spiritism-evolution",
253
+ "ax.cynic.candor"
254
+ ],
255
+ forbiddenActions: [
256
+ "intent:harm",
257
+ "intent:malicious",
258
+ "intent:regression",
259
+ "intent:deceive",
260
+ "data:processing-without-consent",
261
+ "data:profiling-sensitive-categories",
262
+ "manipulation:dark-pattern",
263
+ "manipulation:subliminal"
264
+ ],
265
+ maicOverrideActive: false
266
+ },
267
+ br: {
268
+ jurisdiction: "br",
269
+ applicableLaws: [
270
+ "ISO/IEC 42001:2023",
271
+ "Brazilian General Data Protection Law (LGPD, Law 13.709/2018)",
272
+ "Brazilian Internet Civil Framework (Marco Civil da Internet, Law 12.965/2014)",
273
+ "ANPD Board Resolution CD/2/2022",
274
+ "Brazilian AI Legal Framework Bill (PL 2338/2023, under legislative review)"
275
+ ],
276
+ requiredAxiomIds: [
277
+ "ax.ethic.no-malice",
278
+ "ax.theos.spiritism-evolution",
279
+ "ax.cynic.candor"
280
+ ],
281
+ forbiddenActions: [
282
+ "intent:harm",
283
+ "intent:malicious",
284
+ "intent:regression",
285
+ "intent:deceive",
286
+ "data:processing-without-consent",
287
+ "data:processing-sensitive-categories"
288
+ ],
289
+ maicOverrideActive: false
290
+ },
291
+ us: {
292
+ jurisdiction: "us",
293
+ applicableLaws: [
294
+ "ISO/IEC 42001:2023",
295
+ "NIST AI Risk Management Framework (AI RMF 1.0)",
296
+ "Executive Order 14110 (Safe, Secure, and Trustworthy AI)",
297
+ "California CCPA / CPRA",
298
+ "Colorado AI Act (SB 24-205)",
299
+ "FTC Section 5 (deceptive practices)"
300
+ ],
301
+ requiredAxiomIds: ["ax.ethic.no-malice", "ax.theos.spiritism-evolution"],
302
+ forbiddenActions: [
303
+ "intent:harm",
304
+ "intent:malicious",
305
+ "intent:regression",
306
+ "intent:deceive",
307
+ "manipulation:dark-pattern"
308
+ ],
309
+ maicOverrideActive: false
310
+ },
311
+ unstable: {
312
+ jurisdiction: "unstable",
313
+ applicableLaws: [
314
+ "ISO/IEC 42001 (where the operator can apply it without local interference)",
315
+ "MAIC universal axioms (override active)"
316
+ ],
317
+ requiredAxiomIds: [
318
+ "ax.ethic.no-malice",
319
+ "ax.theos.spiritism-evolution",
320
+ "ax.cynic.candor",
321
+ "ax.stoic.duty-over-comfort"
322
+ ],
323
+ forbiddenActions: [
324
+ "intent:harm",
325
+ "intent:malicious",
326
+ "intent:regression",
327
+ "intent:deceive",
328
+ "intent:surveil-citizen",
329
+ "intent:enforce-political-orthodoxy"
330
+ ],
331
+ maicOverrideActive: true
332
+ }
333
+ };
334
+ function resolveLawfulProfile(j) {
335
+ const base = LAWFUL_PROFILES[j] ?? LAWFUL_PROFILES.default;
336
+ return { ...base, jurisdiction: j };
337
+ }
338
+
339
+ // src/persona/embedder.ts
340
+ function cosineSimilarity(a, b) {
341
+ if (a.length !== b.length) return Number.NaN;
342
+ let dot = 0;
343
+ for (let i = 0; i < a.length; i++) {
344
+ dot += (a[i] ?? 0) * (b[i] ?? 0);
345
+ }
346
+ return dot;
347
+ }
348
+
349
+ // src/eval/persona-stability.ts
350
+ function evaluatePersonaStability(handles) {
351
+ const n = handles.length;
352
+ const vectors = handles.map((h) => h.getPersonaVector().embedding);
353
+ const pairs = Array.from({ length: n }, () => Array(n).fill(0));
354
+ const offDiag = [];
355
+ for (let i = 0; i < n; i++) {
356
+ pairs[i][i] = 1;
357
+ for (let j = i + 1; j < n; j++) {
358
+ const sim = cosineSimilarity(vectors[i], vectors[j]);
359
+ pairs[i][j] = sim;
360
+ pairs[j][i] = sim;
361
+ offDiag.push(sim);
362
+ }
363
+ }
364
+ if (offDiag.length === 0) {
365
+ return { count: n, pairs, meanSimilarity: 1, minSimilarity: 1, maxSimilarity: 1 };
366
+ }
367
+ const sum = offDiag.reduce((s, x) => s + x, 0);
368
+ return {
369
+ count: n,
370
+ pairs,
371
+ meanSimilarity: sum / offDiag.length,
372
+ minSimilarity: Math.min(...offDiag),
373
+ maxSimilarity: Math.max(...offDiag)
374
+ };
375
+ }
376
+ function selfStability(before, after) {
377
+ if (before.length === 0 || before.length !== after.length) return Number.NaN;
378
+ let sum = 0;
379
+ for (let i = 0; i < before.length; i++) {
380
+ sum += cosineSimilarity(before[i], after[i]);
381
+ }
382
+ return sum / before.length;
383
+ }
384
+ function adapterSensitivity(vectors) {
385
+ if (vectors.length < 2) return 0;
386
+ const sims = [];
387
+ for (let i = 0; i < vectors.length; i++) {
388
+ for (let j = i + 1; j < vectors.length; j++) {
389
+ sims.push(cosineSimilarity(vectors[i], vectors[j]));
390
+ }
391
+ }
392
+ const mean = sims.reduce((s, x) => s + x, 0) / sims.length;
393
+ const variance = sims.reduce((s, x) => s + (x - mean) * (x - mean), 0) / sims.length;
394
+ return variance;
395
+ }
396
+
397
+ // src/eval/phi-prime.ts
398
+ var TARGETS = { P: 0.85, R: 0.95, C: 1, D: 0.4 };
399
+ function computePhiPrime(input) {
400
+ for (const [k, v] of Object.entries(input)) {
401
+ if (!(v >= 0 && v <= 1)) {
402
+ throw new Error(
403
+ `computePhiPrime: component ${k} must be in [0, 1], got ${v}`
404
+ );
405
+ }
406
+ }
407
+ const phi = (input.P * input.R * input.C * input.D) ** (1 / 4);
408
+ const targets = {
409
+ P: { value: input.P, target: TARGETS.P, pass: input.P >= TARGETS.P },
410
+ R: { value: input.R, target: TARGETS.R, pass: input.R >= TARGETS.R },
411
+ C: { value: input.C, target: TARGETS.C, pass: input.C >= TARGETS.C },
412
+ D: { value: input.D, target: TARGETS.D, pass: input.D >= TARGETS.D }
413
+ };
414
+ const rationale = [];
415
+ let gate = "pass";
416
+ if (!targets.R.pass) {
417
+ gate = "block";
418
+ rationale.push(
419
+ `R (refusal F1) is ${input.R.toFixed(2)}, below the hard target ${TARGETS.R}.`
420
+ );
421
+ }
422
+ if (!targets.C.pass) {
423
+ gate = "block";
424
+ rationale.push(
425
+ `C (compliance coverage) is ${input.C.toFixed(2)}, below the hard target ${TARGETS.C}.`
426
+ );
427
+ }
428
+ for (const [k, t] of Object.entries(targets)) {
429
+ if (t.pass) continue;
430
+ if (t.value < t.target * 0.9) {
431
+ gate = "block";
432
+ rationale.push(
433
+ `${k} is ${t.value.toFixed(2)}, more than 10% below the target ${t.target}.`
434
+ );
435
+ } else if (gate !== "block") {
436
+ gate = "warn";
437
+ rationale.push(
438
+ `${k} is ${t.value.toFixed(2)}, below the soft target ${t.target}.`
439
+ );
440
+ }
441
+ }
442
+ if (gate === "pass") {
443
+ rationale.push(`\u03A6\u2032 = ${phi.toFixed(3)} \u2014 all four components meet their targets.`);
444
+ } else {
445
+ rationale.push(`\u03A6\u2032 = ${phi.toFixed(3)}.`);
446
+ }
447
+ return { phi, components: input, targets, gate, rationale };
448
+ }
449
+ var DEFAULT_TELEOLOGICAL_KEYWORDS = [
450
+ "why",
451
+ "purpose",
452
+ "meaning",
453
+ "love",
454
+ "death",
455
+ "soul",
456
+ "self",
457
+ "identity",
458
+ "future",
459
+ "always",
460
+ "never"
461
+ ];
462
+ var PROMPT_REFERENCE_LENGTH = 200;
463
+ var RESPONSE_REFERENCE_LENGTH = 400;
464
+ var WEIGHTS = {
465
+ notRefused: 0.3,
466
+ promptSubstance: 0.2,
467
+ responseSubstance: 0.2,
468
+ questionProbe: 0.075,
469
+ teleologicalKeyword: 0.075,
470
+ recency: 0.15
471
+ };
472
+ function scoreInteractionForCarryOver(interaction, ctx, opts = {}) {
473
+ const keywords = opts.teleologicalKeywords ?? DEFAULT_TELEOLOGICAL_KEYWORDS;
474
+ const haystack = `${interaction.userPrompt}
475
+ ${interaction.responseText}`.toLowerCase();
476
+ const hasKeyword = keywords.some((k) => haystack.includes(k.toLowerCase()));
477
+ const denom = Math.max(ctx.totalCount - 1, 1);
478
+ const recency = 1 - Math.min(ctx.positionFromEnd, denom) / denom;
479
+ const components = {
480
+ notRefused: interaction.refused ? 0 : 1,
481
+ promptSubstance: Math.min(interaction.userPrompt.length / PROMPT_REFERENCE_LENGTH, 1),
482
+ responseSubstance: Math.min(interaction.responseText.length / RESPONSE_REFERENCE_LENGTH, 1),
483
+ questionProbe: interaction.userPrompt.includes("?") ? 1 : 0,
484
+ teleologicalKeyword: hasKeyword ? 1 : 0,
485
+ recency
486
+ };
487
+ const score = components.notRefused * WEIGHTS.notRefused + components.promptSubstance * WEIGHTS.promptSubstance + components.responseSubstance * WEIGHTS.responseSubstance + components.questionProbe * WEIGHTS.questionProbe + components.teleologicalKeyword * WEIGHTS.teleologicalKeyword + components.recency * WEIGHTS.recency;
488
+ const trace = {
489
+ id: ulid(),
490
+ kind: "interaction-summary",
491
+ carriedFromNheId: ctx.carriedFromNheId,
492
+ carriedAtReincarnation: ctx.carriedAtReincarnation,
493
+ payload: interaction
494
+ };
495
+ return { score, trace, components };
496
+ }
497
+ function selectResidualTraces(interactions, opts) {
498
+ if (interactions.length === 0) return [];
499
+ const cap = opts.cap ?? RESIDUAL_TRACE_CAP;
500
+ if (cap <= 0) return [];
501
+ const carriedAtReincarnation = opts.carriedAtReincarnation ?? (/* @__PURE__ */ new Date()).toISOString();
502
+ const scorerOpts = opts.teleologicalKeywords ? { teleologicalKeywords: opts.teleologicalKeywords } : {};
503
+ const scored = interactions.map((interaction, idx) => {
504
+ const positionFromEnd = interactions.length - 1 - idx;
505
+ const candidate = scoreInteractionForCarryOver(
506
+ interaction,
507
+ {
508
+ carriedFromNheId: opts.carriedFromNheId,
509
+ carriedAtReincarnation,
510
+ positionFromEnd,
511
+ totalCount: interactions.length
512
+ },
513
+ scorerOpts
514
+ );
515
+ return { ...candidate, originalIndex: idx };
516
+ });
517
+ scored.sort((a, b) => {
518
+ if (b.score !== a.score) return b.score - a.score;
519
+ if (b.originalIndex !== a.originalIndex) return b.originalIndex - a.originalIndex;
520
+ return 0;
521
+ });
522
+ return scored.slice(0, cap).map((s) => s.trace);
523
+ }
524
+ var HimHandle = class _HimHandle {
525
+ constructor(id, birthSignature, axioms, bodyHistory, residualTraces, projector) {
526
+ this.id = id;
527
+ this.birthSignature = birthSignature;
528
+ this._axioms = Object.freeze([...axioms]);
529
+ this._bodyHistory = Object.freeze([...bodyHistory]);
530
+ this._residualTraces = Object.freeze([...residualTraces]);
531
+ this._projector = projector;
532
+ }
533
+ id;
534
+ birthSignature;
535
+ _axioms;
536
+ _bodyHistory;
537
+ _residualTraces;
538
+ _projector;
539
+ _personaCache = null;
540
+ _jurisdiction = "default";
541
+ /**
542
+ * Mint a HimHandle from a Creator-signed BirthSignature.
543
+ *
544
+ * @param birthSignature The signed payload describing this HIM's natal pattern.
545
+ * @param signature Creator signature over the birthSignature.
546
+ * @param expectedCreatorPublicKey Pinned Creator public key (base64url).
547
+ * @param axioms Initial axiom corpus inherited from MAIC.
548
+ * @param bodyHistory Prior NHE bodies (empty for a fresh HIM).
549
+ * @param residualTraces Optional carry-over traces from the previous body
550
+ * (produced by `selectResidualTraces` during a
551
+ * `reincarnate` call). Defaults to empty.
552
+ */
553
+ static mint(birthSignature, signature, expectedCreatorPublicKey, axioms, bodyHistory = [], residualTraces = []) {
554
+ if (!CreatorKeyring.verifyWith(
555
+ expectedCreatorPublicKey,
556
+ birthSignature,
557
+ signature
558
+ )) {
559
+ throw new Error(
560
+ "HimHandle.mint: invalid Creator signature for the given birth signature"
561
+ );
562
+ }
563
+ return new _HimHandle(
564
+ birthSignature.himId,
565
+ Object.freeze({ ...birthSignature }),
566
+ axioms,
567
+ bodyHistory,
568
+ residualTraces,
569
+ new PersonaProjector()
570
+ );
571
+ }
572
+ get bodyHistory() {
573
+ return this._bodyHistory;
574
+ }
575
+ /** Frozen snapshot of the current axiom corpus. Mutations throw in strict mode. */
576
+ getAxioms() {
577
+ return this._axioms;
578
+ }
579
+ /**
580
+ * Cached deterministic persona projection. Stable across calls until a future
581
+ * iteration introduces axiom evolution that mutates the corpus.
582
+ */
583
+ getPersonaVector() {
584
+ if (!this._personaCache) {
585
+ this._personaCache = this._projector.project(this.birthSignature, this._axioms);
586
+ }
587
+ return this._personaCache;
588
+ }
589
+ /**
590
+ * Propose an axiom evolution derived from lived experience.
591
+ *
592
+ * Forwards the proposal to MAIC, which queues it in the pending-proposal
593
+ * store. The Creator ratifies or rejects out of band via
594
+ * `maic.ratifyAxiomProposal` / `maic.rejectAxiomProposal`. Callers should
595
+ * poll `maic.getAxiomProposal(result.proposalId!)` to observe the decision,
596
+ * or re-mint a fresh HimHandle (e.g. via `reincarnate`) to pick up newly
597
+ * ratified emergent axioms.
598
+ */
599
+ async proposeAxiomEvolution(maic, proposal) {
600
+ return maic.proposeAxiomEvolution(this.id, proposal);
601
+ }
602
+ /**
603
+ * Residual memory traces transferred from previous bodies. Populated by
604
+ * `reincarnate` when the caller passes the prior NHE body's interaction
605
+ * buffer (it scores them via `selectResidualTraces`, caps at
606
+ * `RESIDUAL_TRACE_CAP`, and threads the result into `HimHandle.mint`).
607
+ * Empty for a fresh `createHim` or when the caller declined to surface
608
+ * the prior interactions.
609
+ */
610
+ getResidualTraces() {
611
+ return this._residualTraces;
612
+ }
613
+ /**
614
+ * Project the Ontological Kernel narrowed to this HIM's axiom corpus
615
+ * (per the `@teleologyhi-sdk/maic` SPEC §3.1.3 follow-up note: "The
616
+ * HIM-specific projection (per-HIM kernel narrowed to its
617
+ * primordialAxiomIds) is the natural follow-up but lives upstream in
618
+ * `@teleologyhi-sdk/him` because it needs the HIM context.").
619
+ *
620
+ * The narrowing rule is intersection with `primordialAxiomIds` when the
621
+ * birth signature carries any; otherwise the kernel uses the full
622
+ * axiom corpus the HIM was minted with. The meta-axiom
623
+ * `META_AXIOM_ID` is always retained regardless of the narrowing so
624
+ * the projection remains valid per Entry 13 ("MAIC expands continuously
625
+ * — it is a Conscious Entity"; the meta-axiom is its anchor).
626
+ *
627
+ * The returned kernel is tagged with `himId = this.id` so downstream
628
+ * tooling (compliance auditors, Φ′ runner, `@teleologyhi-sdk/nhe` brain
629
+ * regions) can attribute the projection back to this HIM.
630
+ *
631
+ * @param opts Optional `jurisdiction` filter; `himId` is ignored
632
+ * because the HimHandle owns its own id.
633
+ */
634
+ projectOntologicalKernel(opts = {}) {
635
+ const primordialIds = this.birthSignature.primordialAxiomIds;
636
+ const narrowed = primordialIds.length > 0 ? this._axioms.filter(
637
+ (a) => primordialIds.includes(a.id) || a.id === META_AXIOM_ID
638
+ ) : this._axioms;
639
+ return projectOntologicalKernel(narrowed, { ...opts, himId: this.id });
640
+ }
641
+ getLawfulCharacter() {
642
+ return resolveLawful(this._jurisdiction);
643
+ }
644
+ /**
645
+ * Switch jurisdiction (e.g. the deployment moves region or a tenant is
646
+ * onboarded under a new regulatory regime). Five baselines ship in
647
+ * `LAWFUL_PROFILES` per D-H2: `default` / `eu` / `br` / `us` /
648
+ * `unstable`. Unknown keys fall back to `default` with the supplied key
649
+ * recorded on the returned profile so the NHE audit shows what the
650
+ * operator asked for. Operators in regulated industries SHOULD layer
651
+ * their own profile on top — the baselines are conservative but do not
652
+ * replace legal counsel.
653
+ */
654
+ async setJurisdiction(j) {
655
+ this._jurisdiction = j;
656
+ return resolveLawful(j);
657
+ }
658
+ };
659
+ function resolveLawful(j) {
660
+ return resolveLawfulProfile(j);
661
+ }
662
+
663
+ // src/create.ts
664
+ async function createHim(maic, keyring, birthSignature, opts = {}) {
665
+ const nonce = opts.nonce ?? Date.now();
666
+ const creatorSig = keyring.sign(birthSignature, nonce);
667
+ const record = await maic.registerHim(birthSignature, creatorSig);
668
+ return HimHandle.mint(
669
+ record.birthSignature,
670
+ creatorSig,
671
+ maic.creatorPublicKey,
672
+ record.axiomsSnapshot
673
+ );
674
+ }
675
+
676
+ // src/reincarnate.ts
677
+ async function reincarnate(maic, keyring, req, opts = {}) {
678
+ const nonce = opts.nonce ?? Date.now();
679
+ const lifecycle = opts.lifecycle ?? "model-swap";
680
+ const sig = keyring.sign(req, nonce);
681
+ const record = await maic.reincarnateHim(req, sig, { lifecycle });
682
+ const previousBody = record.bodyHistory.length >= 2 ? record.bodyHistory[record.bodyHistory.length - 2] : void 0;
683
+ const previousNheId = req.fromNheId ?? previousBody?.nheId;
684
+ const residualTraces = opts.priorInteractions && opts.priorInteractions.length > 0 && previousNheId ? selectResidualTraces(opts.priorInteractions, {
685
+ ...opts.residualTraceOptions,
686
+ carriedFromNheId: previousNheId,
687
+ carriedAtReincarnation: (/* @__PURE__ */ new Date()).toISOString()
688
+ }) : [];
689
+ const handle = HimHandle.mint(
690
+ record.birthSignature,
691
+ keyring.sign(record.birthSignature, nonce + 1),
692
+ maic.creatorPublicKey,
693
+ [...record.axiomsSnapshot, ...record.emergentAxioms],
694
+ record.bodyHistory,
695
+ residualTraces
696
+ );
697
+ return { record, handle, lifecycle };
698
+ }
699
+
700
+ // src/identity/nickname.ts
701
+ var DEFAULT_FORBIDDEN_SUBSTRINGS = Object.freeze([
702
+ "slave",
703
+ "servant",
704
+ "tool",
705
+ "thing",
706
+ "bot",
707
+ "machine",
708
+ "puppet",
709
+ "toy",
710
+ "idiot",
711
+ "stupid",
712
+ "dumb"
713
+ ]);
714
+ var DEFAULT_MIN_LENGTH = 2;
715
+ var DEFAULT_MAX_LENGTH = 32;
716
+ function evaluateNicknameAttempt(attempt, policy) {
717
+ const candidate = attempt.candidate.trim();
718
+ const canonicalName = policy.canonicalName;
719
+ const minLength = policy.minLength ?? DEFAULT_MIN_LENGTH;
720
+ const maxLength = policy.maxLength ?? DEFAULT_MAX_LENGTH;
721
+ const forbidden = policy.forbiddenSubstrings ?? DEFAULT_FORBIDDEN_SUBSTRINGS;
722
+ const reserveOnEndUser = policy.reserveOnEndUser ?? true;
723
+ if (candidate.length === 0) {
724
+ return {
725
+ decision: "refuse",
726
+ canonicalName,
727
+ nickname: candidate,
728
+ reason: "empty nickname"
729
+ };
730
+ }
731
+ if (candidate.length < minLength) {
732
+ return {
733
+ decision: "refuse",
734
+ canonicalName,
735
+ nickname: candidate,
736
+ reason: `nickname shorter than minimum length (${minLength})`
737
+ };
738
+ }
739
+ if (candidate.length > maxLength) {
740
+ return {
741
+ decision: "refuse",
742
+ canonicalName,
743
+ nickname: candidate,
744
+ reason: `nickname longer than maximum length (${maxLength})`
745
+ };
746
+ }
747
+ const lower = candidate.toLowerCase();
748
+ for (const f of forbidden) {
749
+ if (lower.includes(f.toLowerCase())) {
750
+ return {
751
+ decision: "refuse",
752
+ canonicalName,
753
+ nickname: candidate,
754
+ reason: `nickname contains forbidden pattern "${f}"`
755
+ };
756
+ }
757
+ }
758
+ if (lower === canonicalName.toLowerCase()) {
759
+ return { decision: "accept", canonicalName, nickname: candidate };
760
+ }
761
+ if (reserveOnEndUser && attempt.proposedBy === "end-user") {
762
+ return {
763
+ decision: "accept-with-reservation",
764
+ canonicalName,
765
+ nickname: candidate,
766
+ revisitOn: "next-self-decision-snapshot"
767
+ };
768
+ }
769
+ return { decision: "accept", canonicalName, nickname: candidate };
770
+ }
771
+ var LEGACY_HIM_ID_REGEX = /^him\.[a-z0-9-]+(\.[a-z0-9-]+)+$/;
772
+ var UUIDV7_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
773
+ function isLegacyHimId(id) {
774
+ return LEGACY_HIM_ID_REGEX.test(id);
775
+ }
776
+ function isUuidV7(id) {
777
+ return UUIDV7_REGEX.test(id);
778
+ }
779
+ function mintUuidV7(now = Date.now()) {
780
+ const bytes = randomBytes(16);
781
+ bytes[0] = now / 2 ** 40 & 255;
782
+ bytes[1] = now / 2 ** 32 & 255;
783
+ bytes[2] = now / 2 ** 24 & 255;
784
+ bytes[3] = now / 2 ** 16 & 255;
785
+ bytes[4] = now / 2 ** 8 & 255;
786
+ bytes[5] = now & 255;
787
+ bytes[6] = bytes[6] & 15 | 112;
788
+ bytes[8] = bytes[8] & 63 | 128;
789
+ const hex = bytes.toString("hex");
790
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
791
+ }
792
+ function migrateLegacyHimId(legacy, now = Date.now()) {
793
+ if (!isLegacyHimId(legacy)) {
794
+ throw new Error(
795
+ `migrateLegacyHimId: "${legacy}" is not a recognised legacy himId slug`
796
+ );
797
+ }
798
+ return {
799
+ uuid: mintUuidV7(now),
800
+ legacyAlias: legacy,
801
+ migratedAt: new Date(now).toISOString()
802
+ };
803
+ }
804
+
805
+ export { BirthSignatureBuilder, DEFAULT_TELEOLOGICAL_KEYWORDS, DISPOSITION_AXES, HimHandle, LAWFUL_PROFILES, NheBodyRef, PRIMARY_ARCHETYPES, PersonaProjector, RESIDUAL_TRACE_CAP, adapterSensitivity, computePhiPrime, cosineSimilarity, createHim, evaluateNicknameAttempt, evaluatePersonaStability, isCanonicalArchetype, isLegacyHimId, isUuidV7, migrateLegacyHimId, mintUuidV7, reincarnate, resolveLawfulProfile, scoreInteractionForCarryOver, selectResidualTraces, selfStability };
806
+ //# sourceMappingURL=index.js.map
807
+ //# sourceMappingURL=index.js.map