@nextera.one/axis-server-sdk 2.1.5 → 2.1.7

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.mjs CHANGED
@@ -143,8 +143,10 @@ var init_capsule_policy_decorator = __esm({
143
143
  var intent_policy_decorator_exports = {};
144
144
  __export(intent_policy_decorator_exports, {
145
145
  AXIS_ANONYMOUS_KEY: () => AXIS_ANONYMOUS_KEY,
146
+ AXIS_META_KEY: () => AXIS_META_KEY,
146
147
  AXIS_PUBLIC_KEY: () => AXIS_PUBLIC_KEY,
147
148
  AXIS_RATE_LIMIT_KEY: () => AXIS_RATE_LIMIT_KEY,
149
+ Axis: () => Axis,
148
150
  AxisAnonymous: () => AxisAnonymous,
149
151
  AxisPublic: () => AxisPublic,
150
152
  AxisRateLimit: () => AxisRateLimit,
@@ -258,6 +260,11 @@ function Witness() {
258
260
  }
259
261
  });
260
262
  }
263
+ function Axis() {
264
+ return (target) => {
265
+ Reflect.defineMetadata(AXIS_META_KEY, { entry: true }, target);
266
+ };
267
+ }
261
268
  function AxisPublic() {
262
269
  return (target, propertyKey, descriptor) => {
263
270
  if (descriptor) {
@@ -284,9 +291,10 @@ function AxisRateLimit(config) {
284
291
  return descriptor;
285
292
  };
286
293
  }
287
- var SENSITIVITY_METADATA_KEY, CONTRACT_METADATA_KEY, REQUIRED_PROOF_METADATA_KEY, AXIS_PUBLIC_KEY, AXIS_ANONYMOUS_KEY, AXIS_RATE_LIMIT_KEY;
294
+ var AXIS_META_KEY, SENSITIVITY_METADATA_KEY, CONTRACT_METADATA_KEY, REQUIRED_PROOF_METADATA_KEY, AXIS_PUBLIC_KEY, AXIS_ANONYMOUS_KEY, AXIS_RATE_LIMIT_KEY;
288
295
  var init_intent_policy_decorator = __esm({
289
296
  "src/decorators/intent-policy.decorator.ts"() {
297
+ AXIS_META_KEY = "axis:axis";
290
298
  SENSITIVITY_METADATA_KEY = "axis:sensitivity";
291
299
  CONTRACT_METADATA_KEY = "axis:contract";
292
300
  REQUIRED_PROOF_METADATA_KEY = "axis:required_proof";
@@ -342,7 +350,8 @@ function Intent(action, options) {
342
350
  chain: options?.chain,
343
351
  bodyProfile: options?.bodyProfile,
344
352
  tlv: options?.tlv,
345
- dto: options?.dto
353
+ dto: options?.dto,
354
+ is: options?.is
346
355
  });
347
356
  Reflect.defineMetadata(INTENT_ROUTES_KEY, routes, target.constructor);
348
357
  };
@@ -497,76 +506,90 @@ var init_sensor_decorator = __esm({
497
506
  });
498
507
 
499
508
  // src/decorators/tlv-field.decorator.ts
500
- var tlv_field_decorator_exports = {};
501
- __export(tlv_field_decorator_exports, {
502
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
503
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
504
- TlvEnum: () => TlvEnum,
505
- TlvField: () => TlvField,
506
- TlvMinLen: () => TlvMinLen,
507
- TlvRange: () => TlvRange,
508
- TlvUtf8Pattern: () => TlvUtf8Pattern,
509
- TlvValidate: () => TlvValidate
510
- });
511
- import "reflect-metadata";
512
- function TlvField(tag, options) {
513
- return (target, propertyKey) => {
514
- const existing = Reflect.getOwnMetadata(TLV_FIELDS_KEY, target.constructor) || [];
515
- existing.push({
516
- property: String(propertyKey),
517
- tag,
518
- options
519
- });
520
- Reflect.defineMetadata(TLV_FIELDS_KEY, existing, target.constructor);
521
- };
522
- }
523
- function TlvValidate(validator) {
524
- return (target, propertyKey) => {
525
- const existing = Reflect.getOwnMetadata(TLV_VALIDATORS_KEY, target.constructor) || [];
526
- const prop = String(propertyKey);
527
- let entry = existing.find((e) => e.property === prop);
528
- if (!entry) {
529
- entry = { property: prop, tag: 0, validators: [] };
530
- existing.push(entry);
509
+ var require_tlv_field_decorator = __commonJS({
510
+ "src/decorators/tlv-field.decorator.ts"(exports) {
511
+ "use strict";
512
+ Object.defineProperty(exports, "__esModule", { value: true });
513
+ exports.TLV_VALIDATORS_KEY = exports.TLV_FIELDS_KEY = void 0;
514
+ exports.TlvField = TlvField2;
515
+ exports.TlvValidate = TlvValidate2;
516
+ exports.TlvUtf8Pattern = TlvUtf8Pattern2;
517
+ exports.TlvMinLen = TlvMinLen2;
518
+ exports.TlvEnum = TlvEnum2;
519
+ exports.TlvRange = TlvRange2;
520
+ __require("reflect-metadata");
521
+ exports.TLV_FIELDS_KEY = "axis:tlv:fields";
522
+ exports.TLV_VALIDATORS_KEY = "axis:tlv:validators";
523
+ var textDecoder = new TextDecoder();
524
+ function assertUniqueFieldMetadata(existing, property, tag) {
525
+ const duplicateProperty = existing.find((item) => item.property === property);
526
+ if (duplicateProperty) {
527
+ throw new Error(`Duplicate @TlvField for property ${property}`);
528
+ }
529
+ const duplicateTag = existing.find((item) => item.tag === tag);
530
+ if (duplicateTag) {
531
+ throw new Error(`Duplicate @TlvField tag ${tag} for ${property}; already used by ${duplicateTag.property}`);
532
+ }
531
533
  }
532
- entry.validators.push(validator);
533
- Reflect.defineMetadata(TLV_VALIDATORS_KEY, existing, target.constructor);
534
- };
535
- }
536
- function TlvUtf8Pattern(pattern, message) {
537
- return TlvValidate((val, prop) => {
538
- const str = new TextDecoder().decode(val);
539
- return pattern.test(str) ? null : message || `${prop}: failed pattern check`;
540
- });
541
- }
542
- function TlvMinLen(min, message) {
543
- return TlvValidate((val, prop) => {
544
- return val.length >= min ? null : message || `${prop}: too short (${val.length} < ${min})`;
545
- });
546
- }
547
- function TlvEnum(allowed, message) {
548
- const set = new Set(allowed);
549
- return TlvValidate((val, prop) => {
550
- const str = new TextDecoder().decode(val);
551
- return set.has(str) ? null : message || `${prop}: must be one of [${allowed.join(", ")}]`;
552
- });
553
- }
554
- function TlvRange(min, max, message) {
555
- return TlvValidate((val, prop) => {
556
- if (val.length !== 8) return `${prop}: u64 must be 8 bytes`;
557
- let n = 0n;
558
- for (const b of val) n = n << 8n | BigInt(b);
559
- if (n < min || n > max) {
560
- return message || `${prop}: value ${n} out of range [${min}, ${max}]`;
534
+ function TlvField2(tag, options) {
535
+ return (target, propertyKey) => {
536
+ const existing = Reflect.getOwnMetadata(exports.TLV_FIELDS_KEY, target.constructor) || [];
537
+ const property = String(propertyKey);
538
+ assertUniqueFieldMetadata(existing, property, tag);
539
+ existing.push({
540
+ property,
541
+ tag,
542
+ options
543
+ });
544
+ Reflect.defineMetadata(exports.TLV_FIELDS_KEY, existing, target.constructor);
545
+ };
546
+ }
547
+ function TlvValidate2(validator) {
548
+ return (target, propertyKey) => {
549
+ const existing = Reflect.getOwnMetadata(exports.TLV_VALIDATORS_KEY, target.constructor) || [];
550
+ const prop = String(propertyKey);
551
+ let entry = existing.find((e) => e.property === prop);
552
+ if (!entry) {
553
+ entry = { property: prop, tag: 0, validators: [] };
554
+ existing.push(entry);
555
+ }
556
+ entry.validators.push(validator);
557
+ Reflect.defineMetadata(exports.TLV_VALIDATORS_KEY, existing, target.constructor);
558
+ };
559
+ }
560
+ function TlvUtf8Pattern2(pattern, message) {
561
+ const matcher = new RegExp(pattern.source, pattern.flags);
562
+ return TlvValidate2((val, prop) => {
563
+ const str = textDecoder.decode(val);
564
+ matcher.lastIndex = 0;
565
+ return matcher.test(str) ? null : message || `${prop}: failed pattern check`;
566
+ });
567
+ }
568
+ function TlvMinLen2(min, message) {
569
+ return TlvValidate2((val, prop) => {
570
+ return val.length >= min ? null : message || `${prop}: too short (${val.length} < ${min})`;
571
+ });
572
+ }
573
+ function TlvEnum2(allowed, message) {
574
+ const set = new Set(allowed);
575
+ return TlvValidate2((val, prop) => {
576
+ const str = textDecoder.decode(val);
577
+ return set.has(str) ? null : message || `${prop}: must be one of [${allowed.join(", ")}]`;
578
+ });
579
+ }
580
+ function TlvRange2(min, max, message) {
581
+ return TlvValidate2((val, prop) => {
582
+ if (val.length !== 8)
583
+ return `${prop}: u64 must be 8 bytes`;
584
+ let n = 0n;
585
+ for (const b of val)
586
+ n = n << 8n | BigInt(b);
587
+ if (n < min || n > max) {
588
+ return message || `${prop}: value ${n} out of range [${min}, ${max}]`;
589
+ }
590
+ return null;
591
+ });
561
592
  }
562
- return null;
563
- });
564
- }
565
- var TLV_FIELDS_KEY, TLV_VALIDATORS_KEY;
566
- var init_tlv_field_decorator = __esm({
567
- "src/decorators/tlv-field.decorator.ts"() {
568
- TLV_FIELDS_KEY = "axis:tlv:fields";
569
- TLV_VALIDATORS_KEY = "axis:tlv:validators";
570
593
  }
571
594
  });
572
595
 
@@ -601,7 +624,7 @@ var require_dto_schema_util = __commonJS({
601
624
  exports.extractDtoSchema = extractDtoSchema2;
602
625
  exports.buildDtoDecoder = buildDtoDecoder2;
603
626
  __require("reflect-metadata");
604
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
627
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
605
628
  var tlv_1 = (init_tlv(), __toCommonJS(tlv_exports));
606
629
  function extractDtoSchema2(dto) {
607
630
  const fieldMetas = Reflect.getMetadata(tlv_field_decorator_1.TLV_FIELDS_KEY, dto) || [];
@@ -710,7 +733,7 @@ var require_axis_id_dto = __commonJS({
710
733
  };
711
734
  Object.defineProperty(exports, "__esModule", { value: true });
712
735
  exports.AxisIdDto = void 0;
713
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
736
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
714
737
  var axis_tlv_dto_1 = (init_axis_tlv_dto(), __toCommonJS(axis_tlv_dto_exports));
715
738
  var AxisIdDto2 = class extends axis_tlv_dto_1.AxisTlvDto {
716
739
  };
@@ -728,25 +751,26 @@ import "reflect-metadata";
728
751
  function AxisPartialType(BaseDto) {
729
752
  class PartialDto extends BaseDto {
730
753
  }
731
- const fields = Reflect.getOwnMetadata(TLV_FIELDS_KEY, BaseDto) || [];
754
+ const fields = Reflect.getOwnMetadata(import_tlv_field.TLV_FIELDS_KEY, BaseDto) || [];
732
755
  const partialFields = fields.map((f) => ({
733
756
  property: f.property,
734
757
  tag: f.tag,
735
758
  options: { ...f.options, required: false }
736
759
  }));
737
- Reflect.defineMetadata(TLV_FIELDS_KEY, partialFields, PartialDto);
738
- const validators = Reflect.getOwnMetadata(TLV_VALIDATORS_KEY, BaseDto) || [];
760
+ Reflect.defineMetadata(import_tlv_field.TLV_FIELDS_KEY, partialFields, PartialDto);
761
+ const validators = Reflect.getOwnMetadata(import_tlv_field.TLV_VALIDATORS_KEY, BaseDto) || [];
739
762
  if (validators.length > 0) {
740
- Reflect.defineMetadata(TLV_VALIDATORS_KEY, [...validators], PartialDto);
763
+ Reflect.defineMetadata(import_tlv_field.TLV_VALIDATORS_KEY, [...validators], PartialDto);
741
764
  }
742
765
  Object.defineProperty(PartialDto, "name", {
743
766
  value: `Partial${BaseDto.name}`
744
767
  });
745
768
  return PartialDto;
746
769
  }
770
+ var import_tlv_field;
747
771
  var init_axis_partial_type = __esm({
748
772
  "src/base/axis-partial-type.ts"() {
749
- init_tlv_field_decorator();
773
+ import_tlv_field = __toESM(require_tlv_field_decorator());
750
774
  }
751
775
  });
752
776
 
@@ -765,7 +789,7 @@ var require_axis_response_dto = __commonJS({
765
789
  };
766
790
  Object.defineProperty(exports, "__esModule", { value: true });
767
791
  exports.AxisResponseDto = exports.RESPONSE_TAG_UPDATED_BY = exports.RESPONSE_TAG_CREATED_BY = exports.RESPONSE_TAG_UPDATED_AT = exports.RESPONSE_TAG_CREATED_AT = exports.RESPONSE_TAG_ID = void 0;
768
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
792
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
769
793
  var axis_tlv_dto_1 = (init_axis_tlv_dto(), __toCommonJS(axis_tlv_dto_exports));
770
794
  exports.RESPONSE_TAG_ID = 1;
771
795
  exports.RESPONSE_TAG_CREATED_AT = 2;
@@ -2131,6 +2155,121 @@ var init_inline_capsule = __esm({
2131
2155
  }
2132
2156
  });
2133
2157
 
2158
+ // src/engine/registry/sensor.registry.ts
2159
+ var require_sensor_registry = __commonJS({
2160
+ "src/engine/registry/sensor.registry.ts"(exports) {
2161
+ "use strict";
2162
+ var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
2163
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2164
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2165
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2166
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2167
+ };
2168
+ var __metadata = exports && exports.__metadata || function(k, v) {
2169
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2170
+ };
2171
+ var SensorRegistry_1;
2172
+ var _a;
2173
+ Object.defineProperty(exports, "__esModule", { value: true });
2174
+ exports.SensorRegistry = void 0;
2175
+ var common_1 = __require("@nestjs/common");
2176
+ var config_1 = __require("@nestjs/config");
2177
+ var SensorRegistry2 = SensorRegistry_1 = class SensorRegistry {
2178
+ constructor(configService) {
2179
+ this.configService = configService;
2180
+ this.sensors = [];
2181
+ this.sensorsByName = /* @__PURE__ */ new Map();
2182
+ this.sensorsByType = /* @__PURE__ */ new Map();
2183
+ this.logger = new common_1.Logger(SensorRegistry_1.name);
2184
+ }
2185
+ register(sensor) {
2186
+ if (!sensor.name) {
2187
+ throw new Error("AxisSensor must have a name");
2188
+ }
2189
+ const enabledSensorsStr = this.configService.get("ENABLED_SENSORS");
2190
+ const disabledSensorsStr = this.configService.get("DISABLED_SENSORS");
2191
+ const enabledSensors = enabledSensorsStr ? enabledSensorsStr.split(",").map((s) => s.trim()) : null;
2192
+ const disabledSensors = disabledSensorsStr ? disabledSensorsStr.split(",").map((s) => s.trim()) : [];
2193
+ if (enabledSensors && !enabledSensors.includes(sensor.name)) {
2194
+ this.logger.log(`Skipping disabled sensor (not in ENABLED_SENSORS): ${sensor.name}`);
2195
+ return;
2196
+ }
2197
+ if (disabledSensors.includes(sensor.name)) {
2198
+ this.logger.log(`Skipping disabled sensor (in DISABLED_SENSORS): ${sensor.name}`);
2199
+ return;
2200
+ }
2201
+ if (sensor.order === void 0) {
2202
+ throw new Error(`AxisSensor "${sensor.name}" must have an order field`);
2203
+ }
2204
+ const isPreDecodeSensor = this.isPreDecodeSensor(sensor);
2205
+ const isPostDecodeSensor = this.isPostDecodeSensor(sensor);
2206
+ if (isPreDecodeSensor && sensor.order >= 40) {
2207
+ this.logger.warn(`AxisSensor "${sensor.name}" is marked as PRE_DECODE but has order ${sensor.order} (should be < 40)`);
2208
+ }
2209
+ if (isPostDecodeSensor && sensor.order < 40) {
2210
+ this.logger.warn(`AxisSensor "${sensor.name}" is marked as POST_DECODE but has order ${sensor.order} (should be >= 40)`);
2211
+ }
2212
+ this.sensors.push(sensor);
2213
+ this.indexSensor(sensor);
2214
+ const phaseLabel = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase || "UNKNOWN";
2215
+ this.logger.debug(`Registered sensor: ${sensor.name} (order: ${sensor.order}, phase: ${phaseLabel})`);
2216
+ }
2217
+ list() {
2218
+ return [...this.sensors].sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
2219
+ }
2220
+ resolve(ref) {
2221
+ if (typeof ref === "string") {
2222
+ return this.sensorsByName.get(ref);
2223
+ }
2224
+ return this.sensorsByType.get(ref) ?? this.sensorsByName.get(ref.name);
2225
+ }
2226
+ getByName(name) {
2227
+ return this.sensorsByName.get(name);
2228
+ }
2229
+ getPreDecodeSensors() {
2230
+ return this.list().filter((s) => (s.order ?? 999) < 40);
2231
+ }
2232
+ getPostDecodeSensors() {
2233
+ return this.list().filter((s) => (s.order ?? 999) >= 40);
2234
+ }
2235
+ isPreDecodeSensor(sensor) {
2236
+ const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
2237
+ return phase === "PRE_DECODE" || (sensor.order ?? 999) < 40;
2238
+ }
2239
+ isPostDecodeSensor(sensor) {
2240
+ const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
2241
+ return phase === "POST_DECODE" || (sensor.order ?? 999) >= 40;
2242
+ }
2243
+ getSensorCountByPhase() {
2244
+ return {
2245
+ preDecodeCount: this.getPreDecodeSensors().length,
2246
+ postDecodeCount: this.getPostDecodeSensors().length
2247
+ };
2248
+ }
2249
+ clear() {
2250
+ this.sensors = [];
2251
+ this.sensorsByName.clear();
2252
+ this.sensorsByType.clear();
2253
+ }
2254
+ indexSensor(sensor) {
2255
+ this.sensorsByName.set(sensor.name, sensor);
2256
+ const sensorType = sensor.constructor;
2257
+ if (!sensorType)
2258
+ return;
2259
+ this.sensorsByType.set(sensorType, sensor);
2260
+ if (!this.sensorsByName.has(sensorType.name)) {
2261
+ this.sensorsByName.set(sensorType.name, sensor);
2262
+ }
2263
+ }
2264
+ };
2265
+ exports.SensorRegistry = SensorRegistry2;
2266
+ exports.SensorRegistry = SensorRegistry2 = SensorRegistry_1 = __decorate([
2267
+ (0, common_1.Injectable)(),
2268
+ __metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
2269
+ ], SensorRegistry2);
2270
+ }
2271
+ });
2272
+
2134
2273
  // src/engine/intent.router.ts
2135
2274
  var require_intent_router = __commonJS({
2136
2275
  "src/engine/intent.router.ts"(exports) {
@@ -2152,6 +2291,7 @@ var require_intent_router = __commonJS({
2152
2291
  var IntentRouter_1;
2153
2292
  var _a;
2154
2293
  var _b;
2294
+ var _c;
2155
2295
  Object.defineProperty(exports, "__esModule", { value: true });
2156
2296
  exports.IntentRouter = void 0;
2157
2297
  var common_1 = __require("@nestjs/common");
@@ -2172,11 +2312,33 @@ var require_intent_router = __commonJS({
2172
2312
  var observer_decorator_1 = (init_observer_decorator(), __toCommonJS(observer_decorator_exports));
2173
2313
  var inline_capsule_1 = (init_inline_capsule(), __toCommonJS(inline_capsule_exports));
2174
2314
  var axis_sensor_1 = (init_axis_sensor(), __toCommonJS(axis_sensor_exports));
2315
+ var sensor_registry_1 = require_sensor_registry();
2175
2316
  var axis_execution_context_1 = (init_axis_execution_context(), __toCommonJS(axis_execution_context_exports));
2176
2317
  var observer_dispatcher_service_1 = require_observer_dispatcher_service();
2177
2318
  function observerRefKey(ref) {
2178
2319
  return typeof ref === "string" ? ref : ref.name;
2179
2320
  }
2321
+ function sensorRefKey(ref) {
2322
+ return typeof ref === "string" ? ref : ref.name;
2323
+ }
2324
+ function mergeIntentSensorRefs(...sensorGroups) {
2325
+ const merged = /* @__PURE__ */ new Map();
2326
+ for (const group of sensorGroups) {
2327
+ if (!Array.isArray(group))
2328
+ continue;
2329
+ for (const ref of group) {
2330
+ const key = sensorRefKey(ref);
2331
+ const existing = merged.get(key);
2332
+ if (!existing || typeof existing === "string" && typeof ref !== "string") {
2333
+ merged.set(key, ref);
2334
+ }
2335
+ }
2336
+ }
2337
+ return Array.from(merged.values());
2338
+ }
2339
+ function isAxisSensorInstance(value) {
2340
+ return !!value && typeof value.name === "string" && typeof value.run === "function";
2341
+ }
2180
2342
  function mergeObserverBindings(bindings) {
2181
2343
  const merged = /* @__PURE__ */ new Map();
2182
2344
  for (const binding of bindings) {
@@ -2213,9 +2375,10 @@ var require_intent_router = __commonJS({
2213
2375
  };
2214
2376
  }
2215
2377
  var IntentRouter2 = IntentRouter_1 = class IntentRouter {
2216
- constructor(moduleRef, observerDispatcher) {
2378
+ constructor(moduleRef, observerDispatcher, sensorRegistry) {
2217
2379
  this.moduleRef = moduleRef;
2218
2380
  this.observerDispatcher = observerDispatcher;
2381
+ this.sensorRegistry = sensorRegistry;
2219
2382
  this.logger = new common_1.Logger(IntentRouter_1.name);
2220
2383
  this.decoder = new TextDecoder();
2221
2384
  this.encoder = new TextEncoder();
@@ -2383,9 +2546,9 @@ var require_intent_router = __commonJS({
2383
2546
  if (!handler) {
2384
2547
  throw new Error(`Intent not found: ${intent}`);
2385
2548
  }
2386
- const sensorClasses = this.intentSensors.get(intent);
2387
- if (sensorClasses && sensorClasses.length > 0) {
2388
- await this.runIntentSensors(sensorClasses, intent, frame);
2549
+ const sensorRefs = this.intentSensors.get(intent);
2550
+ if (sensorRefs && sensorRefs.length > 0) {
2551
+ await this.runIntentSensors(sensorRefs, intent, frame);
2389
2552
  }
2390
2553
  const decoder = this.intentDecoders.get(intent);
2391
2554
  let decodedBody = frame.body;
@@ -2456,10 +2619,8 @@ var require_intent_router = __commonJS({
2456
2619
  this.intentDecoders.set(intent, decoder);
2457
2620
  }
2458
2621
  const intentSensors = Reflect.getMetadata(intent_sensors_decorator_1.INTENT_SENSORS_KEY, proto, methodName);
2459
- const combined = [
2460
- ...handlerSensors || [],
2461
- ...Array.isArray(intentSensors) ? intentSensors : []
2462
- ];
2622
+ const meta = Reflect.getMetadata(intent_decorator_1.INTENT_METADATA_KEY, proto, methodName);
2623
+ const combined = mergeIntentSensorRefs(handlerSensors, Array.isArray(intentSensors) ? intentSensors : void 0, Array.isArray(meta?.is) ? meta.is : void 0);
2463
2624
  if (combined.length > 0) {
2464
2625
  this.intentSensors.set(intent, combined);
2465
2626
  }
@@ -2477,7 +2638,6 @@ var require_intent_router = __commonJS({
2477
2638
  if (capsulePolicy) {
2478
2639
  this.intentCapsulePolicies.set(intent, capsulePolicy);
2479
2640
  }
2480
- const meta = Reflect.getMetadata(intent_decorator_1.INTENT_METADATA_KEY, proto, methodName);
2481
2641
  if (meta) {
2482
2642
  this.storeSchema({ ...meta, intent });
2483
2643
  if (meta.kind) {
@@ -2545,23 +2705,26 @@ var require_intent_router = __commonJS({
2545
2705
  return;
2546
2706
  await this.observerDispatcher.dispatch(bindings, context);
2547
2707
  }
2548
- async runIntentSensors(sensorClasses, intent, frame) {
2549
- if (!this.moduleRef)
2550
- return;
2551
- for (const SensorClass of sensorClasses) {
2552
- let sensor;
2553
- try {
2554
- sensor = this.moduleRef.get(SensorClass, { strict: false });
2555
- } catch {
2556
- this.logger.warn(`@IntentSensors: could not resolve ${SensorClass.name} for ${intent}`);
2557
- continue;
2708
+ async runIntentSensors(sensorRefs, intent, frame) {
2709
+ for (const sensorRef of sensorRefs) {
2710
+ const sensor = this.resolveIntentSensor(sensorRef);
2711
+ const sensorName = sensorRefKey(sensorRef);
2712
+ if (!sensor) {
2713
+ this.logger.error(`Intent sensor ${sensorName} is not registered for ${intent}`);
2714
+ throw new Error(`SENSOR_MISSING:${sensorName}`);
2558
2715
  }
2559
2716
  const sensorInput = {
2560
2717
  rawBytes: frame.body,
2561
2718
  intent,
2562
2719
  body: frame.body,
2563
2720
  headerTLVs: frame.headers,
2564
- metadata: { phase: "intent", intent }
2721
+ frameBody: frame.body,
2722
+ metadata: {
2723
+ phase: "intent",
2724
+ intent,
2725
+ schema: this.getSchema(intent),
2726
+ validators: this.getValidators(intent)
2727
+ }
2565
2728
  };
2566
2729
  if (sensor.supports && !sensor.supports(sensorInput))
2567
2730
  continue;
@@ -2573,6 +2736,21 @@ var require_intent_router = __commonJS({
2573
2736
  }
2574
2737
  }
2575
2738
  }
2739
+ resolveIntentSensor(ref) {
2740
+ const registered = this.sensorRegistry?.resolve(ref);
2741
+ if (registered) {
2742
+ return registered;
2743
+ }
2744
+ if (!this.moduleRef || typeof ref === "string") {
2745
+ return void 0;
2746
+ }
2747
+ try {
2748
+ const resolved = this.moduleRef.get(ref, { strict: false });
2749
+ return isAxisSensorInstance(resolved) ? resolved : void 0;
2750
+ } catch {
2751
+ return void 0;
2752
+ }
2753
+ }
2576
2754
  getEffectiveCapsulePolicy(intent, frame) {
2577
2755
  const registeredPolicy = this.intentCapsulePolicies.get(intent);
2578
2756
  const chainConfig = this.intentChains.get(intent);
@@ -2888,7 +3066,8 @@ var require_intent_router = __commonJS({
2888
3066
  (0, common_1.Injectable)(),
2889
3067
  __param(0, (0, common_1.Optional)()),
2890
3068
  __param(1, (0, common_1.Optional)()),
2891
- __metadata("design:paramtypes", [typeof (_a = typeof core_1.ModuleRef !== "undefined" && core_1.ModuleRef) === "function" ? _a : Object, typeof (_b = typeof observer_dispatcher_service_1.ObserverDispatcherService !== "undefined" && observer_dispatcher_service_1.ObserverDispatcherService) === "function" ? _b : Object])
3069
+ __param(2, (0, common_1.Optional)()),
3070
+ __metadata("design:paramtypes", [typeof (_a = typeof core_1.ModuleRef !== "undefined" && core_1.ModuleRef) === "function" ? _a : Object, typeof (_b = typeof observer_dispatcher_service_1.ObserverDispatcherService !== "undefined" && observer_dispatcher_service_1.ObserverDispatcherService) === "function" ? _b : Object, typeof (_c = typeof sensor_registry_1.SensorRegistry !== "undefined" && sensor_registry_1.SensorRegistry) === "function" ? _c : Object])
2892
3071
  ], IntentRouter2);
2893
3072
  }
2894
3073
  });
@@ -3526,6 +3705,213 @@ var init_observation_hash = __esm({
3526
3705
  }
3527
3706
  });
3528
3707
 
3708
+ // src/engine/observation/truth-scoring.ts
3709
+ function scoreTruth(obs, expected) {
3710
+ const anomalies = [];
3711
+ let passedChecks = 0;
3712
+ let totalChecks = 0;
3713
+ totalChecks++;
3714
+ if (obs.endMs && obs.decision) {
3715
+ passedChecks++;
3716
+ } else {
3717
+ anomalies.push({
3718
+ code: "OBS_NOT_FINALIZED",
3719
+ level: "critical",
3720
+ message: "Observation was not finalized"
3721
+ });
3722
+ }
3723
+ totalChecks++;
3724
+ if (obs.stages.length > 0) {
3725
+ passedChecks++;
3726
+ } else {
3727
+ anomalies.push({
3728
+ code: "OBS_NO_STAGES",
3729
+ level: "warning",
3730
+ message: "Observation has no execution stages"
3731
+ });
3732
+ }
3733
+ totalChecks++;
3734
+ const failedStages = obs.stages.filter((s) => s.status === "fail");
3735
+ if (failedStages.length === 0 || obs.decision === "DENY") {
3736
+ passedChecks++;
3737
+ } else {
3738
+ for (const stage of failedStages) {
3739
+ anomalies.push({
3740
+ code: "STAGE_FAILED",
3741
+ level: "warning",
3742
+ message: `Stage '${stage.name}' failed: ${stage.reason ?? "unknown"}`,
3743
+ field: `stages.${stage.name}`
3744
+ });
3745
+ }
3746
+ }
3747
+ totalChecks++;
3748
+ const invalidSensors = obs.sensors.filter((s) => s.durationMs < 0);
3749
+ if (invalidSensors.length === 0) {
3750
+ passedChecks++;
3751
+ } else {
3752
+ anomalies.push({
3753
+ code: "SENSOR_INVALID_TIMING",
3754
+ level: "warning",
3755
+ message: `${invalidSensors.length} sensor(s) have negative duration`
3756
+ });
3757
+ }
3758
+ totalChecks++;
3759
+ if (obs.durationMs !== void 0 && obs.durationMs >= 0 && obs.durationMs < 3e5) {
3760
+ passedChecks++;
3761
+ } else {
3762
+ anomalies.push({
3763
+ code: "OBS_DURATION_ANOMALY",
3764
+ level: "warning",
3765
+ message: `Observation duration ${obs.durationMs}ms is suspicious`,
3766
+ actual: obs.durationMs
3767
+ });
3768
+ }
3769
+ if (expected) {
3770
+ if (expected.decision !== void 0) {
3771
+ totalChecks++;
3772
+ if (obs.decision === expected.decision) {
3773
+ passedChecks++;
3774
+ } else {
3775
+ anomalies.push({
3776
+ code: "DECISION_MISMATCH",
3777
+ level: "critical",
3778
+ message: `Expected decision '${expected.decision}', got '${obs.decision}'`,
3779
+ field: "decision",
3780
+ expected: expected.decision,
3781
+ actual: obs.decision
3782
+ });
3783
+ }
3784
+ }
3785
+ if (expected.statusCode !== void 0) {
3786
+ totalChecks++;
3787
+ if (obs.statusCode === expected.statusCode) {
3788
+ passedChecks++;
3789
+ } else {
3790
+ anomalies.push({
3791
+ code: "STATUS_MISMATCH",
3792
+ level: "warning",
3793
+ message: `Expected status ${expected.statusCode}, got ${obs.statusCode}`,
3794
+ field: "statusCode",
3795
+ expected: expected.statusCode,
3796
+ actual: obs.statusCode
3797
+ });
3798
+ }
3799
+ }
3800
+ if (expected.effect !== void 0) {
3801
+ totalChecks++;
3802
+ if (obs.resultCode === expected.effect || obs.facts?.effect === expected.effect) {
3803
+ passedChecks++;
3804
+ } else {
3805
+ anomalies.push({
3806
+ code: "EFFECT_MISMATCH",
3807
+ level: "warning",
3808
+ message: `Expected effect '${expected.effect}', got '${obs.resultCode}'`,
3809
+ field: "resultCode",
3810
+ expected: expected.effect,
3811
+ actual: obs.resultCode
3812
+ });
3813
+ }
3814
+ }
3815
+ if (expected.maxDurationMs !== void 0) {
3816
+ totalChecks++;
3817
+ if (obs.durationMs !== void 0 && obs.durationMs <= expected.maxDurationMs) {
3818
+ passedChecks++;
3819
+ } else {
3820
+ anomalies.push({
3821
+ code: "DURATION_EXCEEDED",
3822
+ level: "warning",
3823
+ message: `Execution took ${obs.durationMs}ms, max allowed ${expected.maxDurationMs}ms`,
3824
+ field: "durationMs",
3825
+ expected: expected.maxDurationMs,
3826
+ actual: obs.durationMs
3827
+ });
3828
+ }
3829
+ }
3830
+ if (expected.minSensorsPassed !== void 0) {
3831
+ totalChecks++;
3832
+ const passed = obs.sensors.filter((s) => s.allowed).length;
3833
+ if (passed >= expected.minSensorsPassed) {
3834
+ passedChecks++;
3835
+ } else {
3836
+ anomalies.push({
3837
+ code: "INSUFFICIENT_SENSORS",
3838
+ level: "warning",
3839
+ message: `Only ${passed} sensors passed, minimum required ${expected.minSensorsPassed}`,
3840
+ field: "sensors",
3841
+ expected: expected.minSensorsPassed,
3842
+ actual: passed
3843
+ });
3844
+ }
3845
+ }
3846
+ if (expected.assertions) {
3847
+ for (const [key, expectedValue] of Object.entries(expected.assertions)) {
3848
+ totalChecks++;
3849
+ const actualValue = obs.facts[key];
3850
+ if (deepEqual(actualValue, expectedValue)) {
3851
+ passedChecks++;
3852
+ } else {
3853
+ anomalies.push({
3854
+ code: "ASSERTION_FAILED",
3855
+ level: "warning",
3856
+ message: `Assertion failed for facts.${key}`,
3857
+ field: `facts.${key}`,
3858
+ expected: expectedValue,
3859
+ actual: actualValue
3860
+ });
3861
+ }
3862
+ }
3863
+ }
3864
+ }
3865
+ const confidence = totalChecks > 0 ? passedChecks / totalChecks : 0;
3866
+ const hasCritical = anomalies.some((a) => a.level === "critical");
3867
+ const status = computeTruthStatus(confidence, hasCritical, anomalies.length);
3868
+ const isDeed = status === "confirmed" || status === "partial" && !hasCritical;
3869
+ return {
3870
+ status,
3871
+ confidence,
3872
+ anomalies,
3873
+ passedChecks,
3874
+ totalChecks,
3875
+ verifiedAt: Date.now(),
3876
+ isDeed
3877
+ };
3878
+ }
3879
+ function computeTruthStatus(confidence, hasCritical, anomalyCount) {
3880
+ if (hasCritical) return "failed";
3881
+ if (confidence === 1) return "confirmed";
3882
+ if (confidence >= 0.8) return "partial";
3883
+ if (confidence >= 0.5) return "uncertain";
3884
+ return "disputed";
3885
+ }
3886
+ function verifyObservation(obs, expected) {
3887
+ const verdict = scoreTruth(obs, expected);
3888
+ return { observation: obs, verdict };
3889
+ }
3890
+ function deepEqual(a, b) {
3891
+ if (a === b) return true;
3892
+ if (a === null || b === null) return false;
3893
+ if (typeof a !== typeof b) return false;
3894
+ if (typeof a !== "object") return String(a) === String(b);
3895
+ if (Array.isArray(a) && Array.isArray(b)) {
3896
+ if (a.length !== b.length) return false;
3897
+ return a.every((v, i) => deepEqual(v, b[i]));
3898
+ }
3899
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
3900
+ const aKeys = Object.keys(a);
3901
+ const bKeys = Object.keys(b);
3902
+ if (aKeys.length !== bKeys.length) return false;
3903
+ return aKeys.every(
3904
+ (key) => deepEqual(
3905
+ a[key],
3906
+ b[key]
3907
+ )
3908
+ );
3909
+ }
3910
+ var init_truth_scoring = __esm({
3911
+ "src/engine/observation/truth-scoring.ts"() {
3912
+ }
3913
+ });
3914
+
3529
3915
  // src/engine/observation/response-observer.ts
3530
3916
  function verifyResponse(ctx, response) {
3531
3917
  if (!response.effect || typeof response.effect !== "string") {
@@ -3600,92 +3986,14 @@ __export(axis_bin_exports, {
3600
3986
  getSignTarget: () => getSignTarget
3601
3987
  });
3602
3988
  import * as z from "zod";
3603
- function encodeFrame(frame) {
3604
- const hdrBytes = encodeTLVs(
3605
- Array.from(frame.headers.entries()).map(([t, v]) => ({
3606
- type: t,
3607
- value: v
3608
- }))
3609
- );
3610
- if (hdrBytes.length > MAX_HDR_LEN) throw new Error("Header too large");
3611
- if (frame.body.length > MAX_BODY_LEN) throw new Error("Body too large");
3612
- if (frame.sig.length > MAX_SIG_LEN) throw new Error("Signature too large");
3613
- const hdrLenBytes = encodeVarint(hdrBytes.length);
3614
- const bodyLenBytes = encodeVarint(frame.body.length);
3615
- const sigLenBytes = encodeVarint(frame.sig.length);
3616
- const totalLen = 5 + // Magic (AXIS1)
3617
- 1 + // Version
3618
- 1 + // Flags
3619
- hdrLenBytes.length + bodyLenBytes.length + sigLenBytes.length + hdrBytes.length + frame.body.length + frame.sig.length;
3620
- if (totalLen > MAX_FRAME_LEN) throw new Error("Total frame too large");
3621
- const buf = new Uint8Array(totalLen);
3622
- let offset = 0;
3623
- buf.set(AXIS_MAGIC, offset);
3624
- offset += 5;
3625
- buf[offset++] = AXIS_VERSION;
3626
- buf[offset++] = frame.flags;
3627
- buf.set(hdrLenBytes, offset);
3628
- offset += hdrLenBytes.length;
3629
- buf.set(bodyLenBytes, offset);
3630
- offset += bodyLenBytes.length;
3631
- buf.set(sigLenBytes, offset);
3632
- offset += sigLenBytes.length;
3633
- buf.set(hdrBytes, offset);
3634
- offset += hdrBytes.length;
3635
- buf.set(frame.body, offset);
3636
- offset += frame.body.length;
3637
- buf.set(frame.sig, offset);
3638
- offset += frame.sig.length;
3639
- return buf;
3640
- }
3641
- function decodeFrame(buf) {
3642
- let offset = 0;
3643
- if (offset + 5 > buf.length) throw new Error("Packet too short");
3644
- for (let i = 0; i < 5; i++) {
3645
- if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error("Invalid Magic");
3646
- }
3647
- offset += 5;
3648
- const ver = buf[offset++];
3649
- if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);
3650
- const flags = buf[offset++];
3651
- const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);
3652
- offset += hlLen;
3653
- if (hdrLen > MAX_HDR_LEN) throw new Error("Header limit exceeded");
3654
- const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);
3655
- offset += blLen;
3656
- if (bodyLen > MAX_BODY_LEN) throw new Error("Body limit exceeded");
3657
- const { value: sigLen, length: slLen } = decodeVarint(buf, offset);
3658
- offset += slLen;
3659
- if (sigLen > MAX_SIG_LEN) throw new Error("Signature limit exceeded");
3660
- if (offset + hdrLen + bodyLen + sigLen > buf.length) {
3661
- throw new Error("Frame truncated");
3662
- }
3663
- const hdrBytes = buf.slice(offset, offset + hdrLen);
3664
- offset += hdrLen;
3665
- const bodyBytes = buf.slice(offset, offset + bodyLen);
3666
- offset += bodyLen;
3667
- const sigBytes = buf.slice(offset, offset + sigLen);
3668
- offset += sigLen;
3669
- const headers = decodeTLVs(hdrBytes);
3670
- return {
3671
- flags,
3672
- headers,
3673
- body: bodyBytes,
3674
- sig: sigBytes
3675
- };
3676
- }
3677
- function getSignTarget(frame) {
3678
- return encodeFrame({
3679
- ...frame,
3680
- sig: new Uint8Array(0)
3681
- });
3682
- }
3989
+ import {
3990
+ decodeFrame,
3991
+ encodeFrame,
3992
+ getSignTarget
3993
+ } from "@nextera.one/axis-protocol";
3683
3994
  var AxisFrameZ;
3684
3995
  var init_axis_bin = __esm({
3685
3996
  "src/core/axis-bin.ts"() {
3686
- init_constants();
3687
- init_tlv();
3688
- init_varint();
3689
3997
  AxisFrameZ = z.object({
3690
3998
  /** Flag bits for protocol control (e.g., encryption, compression) */
3691
3999
  flags: z.number().int().nonnegative(),
@@ -3705,12 +4013,7 @@ var init_axis_bin = __esm({
3705
4013
  // src/core/signature.ts
3706
4014
  import * as crypto2 from "crypto";
3707
4015
  function computeSignaturePayload(frame) {
3708
- const frameWithoutSig = {
3709
- ...frame,
3710
- sig: new Uint8Array(0)
3711
- };
3712
- const encoded = encodeFrame(frameWithoutSig);
3713
- return Buffer.from(encoded);
4016
+ return Buffer.from(getSignTarget(frame));
3714
4017
  }
3715
4018
  function signFrame(frame, privateKey) {
3716
4019
  const payload = computeSignaturePayload(frame);
@@ -4591,11 +4894,12 @@ var init_tlv_encode = __esm({
4591
4894
  });
4592
4895
 
4593
4896
  // src/codec/axis1.encode.ts
4897
+ import { AXIS_MAGIC as AXIS_MAGIC2, AXIS_VERSION as AXIS_VERSION2 } from "@nextera.one/axis-protocol";
4594
4898
  function encodeAxis1Frame(f) {
4595
4899
  if (!Buffer.isBuffer(f.hdr) || !Buffer.isBuffer(f.body) || !Buffer.isBuffer(f.sig)) {
4596
4900
  throw new Error("AXIS1_BAD_BUFFERS");
4597
4901
  }
4598
- if (f.ver !== 1) throw new Error("AXIS1_BAD_VER");
4902
+ if (f.ver !== AXIS_VERSION2) throw new Error("AXIS1_BAD_VER");
4599
4903
  const hdrLen = encVarint(BigInt(f.hdr.length));
4600
4904
  const bodyLen = encVarint(BigInt(f.body.length));
4601
4905
  const sigLen = encVarint(BigInt(f.sig.length));
@@ -4615,13 +4919,14 @@ var MAGIC;
4615
4919
  var init_axis1_encode = __esm({
4616
4920
  "src/codec/axis1.encode.ts"() {
4617
4921
  init_tlv_encode();
4618
- MAGIC = Buffer.from("AXIS1", "ascii");
4922
+ MAGIC = Buffer.from(AXIS_MAGIC2);
4619
4923
  }
4620
4924
  });
4621
4925
 
4622
4926
  // src/codec/axis1.signing.ts
4927
+ import { AXIS_MAGIC as AXIS_MAGIC3, AXIS_VERSION as AXIS_VERSION3 } from "@nextera.one/axis-protocol";
4623
4928
  function axis1SigningBytes(params) {
4624
- if (params.ver !== 1) throw new Error("AXIS1_BAD_VER");
4929
+ if (params.ver !== AXIS_VERSION3) throw new Error("AXIS1_BAD_VER");
4625
4930
  const hdrLen = encVarint(BigInt(params.hdr.length));
4626
4931
  const bodyLen = encVarint(BigInt(params.body.length));
4627
4932
  const sigLenZero = encVarint(0n);
@@ -4640,7 +4945,7 @@ var MAGIC2;
4640
4945
  var init_axis1_signing = __esm({
4641
4946
  "src/codec/axis1.signing.ts"() {
4642
4947
  init_tlv_encode();
4643
- MAGIC2 = Buffer.from("AXIS1", "ascii");
4948
+ MAGIC2 = Buffer.from(AXIS_MAGIC3);
4644
4949
  }
4645
4950
  });
4646
4951
 
@@ -4940,6 +5245,7 @@ var init_tlv2 = __esm({
4940
5245
  });
4941
5246
 
4942
5247
  // src/types/frame.ts
5248
+ import { AXIS_MAGIC as AXIS_MAGIC4 } from "@nextera.one/axis-protocol";
4943
5249
  function decodeAxis1Frame(buf) {
4944
5250
  let off = 0;
4945
5251
  const magic = buf.subarray(off, off + 5);
@@ -4974,7 +5280,7 @@ var MAGIC3;
4974
5280
  var init_frame = __esm({
4975
5281
  "src/types/frame.ts"() {
4976
5282
  init_tlv2();
4977
- MAGIC3 = Buffer.from("AXIS1", "ascii");
5283
+ MAGIC3 = Buffer.from(AXIS_MAGIC4);
4978
5284
  }
4979
5285
  });
4980
5286
 
@@ -5097,7 +5403,52 @@ var init_capabilities = __esm({
5097
5403
  }
5098
5404
  });
5099
5405
 
5406
+ // src/law/law.types.ts
5407
+ function buildAxisLawEvaluationContext(input) {
5408
+ const metadata = input.metadata ?? {};
5409
+ const packet = input.packet;
5410
+ const packetBody = input.frameBody ?? packet?.body ?? packet?.args ?? void 0;
5411
+ const capsuleId = metadata.capsule_id ?? metadata.capsuleId ?? packet?.capsuleId ?? input.clientId;
5412
+ const audience = input.aud ?? metadata.audience ?? packet?.aud;
5413
+ const tps = metadata.tps ?? packet?.tps ?? packet?.tickTps;
5414
+ return {
5415
+ actorId: input.actorId,
5416
+ intent: input.intent,
5417
+ audience,
5418
+ tps,
5419
+ country: input.country,
5420
+ ip: input.ip,
5421
+ path: input.path,
5422
+ clientId: input.clientId,
5423
+ deviceId: input.deviceId,
5424
+ sessionId: input.sessionId,
5425
+ capsuleId,
5426
+ metadata,
5427
+ packet,
5428
+ frameBody: packetBody
5429
+ };
5430
+ }
5431
+ var init_law_types = __esm({
5432
+ "src/law/law.types.ts"() {
5433
+ }
5434
+ });
5435
+
5436
+ // src/law/index.ts
5437
+ var law_exports = {};
5438
+ __export(law_exports, {
5439
+ buildAxisLawEvaluationContext: () => buildAxisLawEvaluationContext
5440
+ });
5441
+ var init_law = __esm({
5442
+ "src/law/index.ts"() {
5443
+ init_law_types();
5444
+ }
5445
+ });
5446
+
5100
5447
  // src/risk/index.ts
5448
+ var risk_exports = {};
5449
+ __export(risk_exports, {
5450
+ RiskDecision: () => RiskDecision
5451
+ });
5101
5452
  var RiskDecision;
5102
5453
  var init_risk = __esm({
5103
5454
  "src/risk/index.ts"() {
@@ -5840,9 +6191,9 @@ var require_handler_discovery_service = __commonJS({
5840
6191
  }
5841
6192
  });
5842
6193
 
5843
- // src/engine/registry/sensor.registry.ts
5844
- var require_sensor_registry = __commonJS({
5845
- "src/engine/registry/sensor.registry.ts"(exports) {
6194
+ // src/engine/sensor-discovery.service.ts
6195
+ var require_sensor_discovery_service = __commonJS({
6196
+ "src/engine/sensor-discovery.service.ts"(exports) {
5846
6197
  "use strict";
5847
6198
  var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
5848
6199
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -5853,103 +6204,12 @@ var require_sensor_registry = __commonJS({
5853
6204
  var __metadata = exports && exports.__metadata || function(k, v) {
5854
6205
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5855
6206
  };
5856
- var SensorRegistry_1;
6207
+ var SensorDiscoveryService_1;
5857
6208
  var _a;
6209
+ var _b;
6210
+ var _c;
5858
6211
  Object.defineProperty(exports, "__esModule", { value: true });
5859
- exports.SensorRegistry = void 0;
5860
- var common_1 = __require("@nestjs/common");
5861
- var config_1 = __require("@nestjs/config");
5862
- var SensorRegistry2 = SensorRegistry_1 = class SensorRegistry {
5863
- constructor(configService) {
5864
- this.configService = configService;
5865
- this.sensors = [];
5866
- this.logger = new common_1.Logger(SensorRegistry_1.name);
5867
- }
5868
- register(sensor) {
5869
- if (!sensor.name) {
5870
- throw new Error("AxisSensor must have a name");
5871
- }
5872
- const enabledSensorsStr = this.configService.get("ENABLED_SENSORS");
5873
- const disabledSensorsStr = this.configService.get("DISABLED_SENSORS");
5874
- const enabledSensors = enabledSensorsStr ? enabledSensorsStr.split(",").map((s) => s.trim()) : null;
5875
- const disabledSensors = disabledSensorsStr ? disabledSensorsStr.split(",").map((s) => s.trim()) : [];
5876
- if (enabledSensors && !enabledSensors.includes(sensor.name)) {
5877
- this.logger.log(`Skipping disabled sensor (not in ENABLED_SENSORS): ${sensor.name}`);
5878
- return;
5879
- }
5880
- if (disabledSensors.includes(sensor.name)) {
5881
- this.logger.log(`Skipping disabled sensor (in DISABLED_SENSORS): ${sensor.name}`);
5882
- return;
5883
- }
5884
- if (sensor.order === void 0) {
5885
- throw new Error(`AxisSensor "${sensor.name}" must have an order field`);
5886
- }
5887
- const isPreDecodeSensor = this.isPreDecodeSensor(sensor);
5888
- const isPostDecodeSensor = this.isPostDecodeSensor(sensor);
5889
- if (isPreDecodeSensor && sensor.order >= 40) {
5890
- this.logger.warn(`AxisSensor "${sensor.name}" is marked as PRE_DECODE but has order ${sensor.order} (should be < 40)`);
5891
- }
5892
- if (isPostDecodeSensor && sensor.order < 40) {
5893
- this.logger.warn(`AxisSensor "${sensor.name}" is marked as POST_DECODE but has order ${sensor.order} (should be >= 40)`);
5894
- }
5895
- this.sensors.push(sensor);
5896
- const phaseLabel = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase || "UNKNOWN";
5897
- this.logger.debug(`Registered sensor: ${sensor.name} (order: ${sensor.order}, phase: ${phaseLabel})`);
5898
- }
5899
- list() {
5900
- return [...this.sensors].sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
5901
- }
5902
- getPreDecodeSensors() {
5903
- return this.list().filter((s) => (s.order ?? 999) < 40);
5904
- }
5905
- getPostDecodeSensors() {
5906
- return this.list().filter((s) => (s.order ?? 999) >= 40);
5907
- }
5908
- isPreDecodeSensor(sensor) {
5909
- const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
5910
- return phase === "PRE_DECODE" || (sensor.order ?? 999) < 40;
5911
- }
5912
- isPostDecodeSensor(sensor) {
5913
- const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
5914
- return phase === "POST_DECODE" || (sensor.order ?? 999) >= 40;
5915
- }
5916
- getSensorCountByPhase() {
5917
- return {
5918
- preDecodeCount: this.getPreDecodeSensors().length,
5919
- postDecodeCount: this.getPostDecodeSensors().length
5920
- };
5921
- }
5922
- clear() {
5923
- this.sensors = [];
5924
- }
5925
- };
5926
- exports.SensorRegistry = SensorRegistry2;
5927
- exports.SensorRegistry = SensorRegistry2 = SensorRegistry_1 = __decorate([
5928
- (0, common_1.Injectable)(),
5929
- __metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
5930
- ], SensorRegistry2);
5931
- }
5932
- });
5933
-
5934
- // src/engine/sensor-discovery.service.ts
5935
- var require_sensor_discovery_service = __commonJS({
5936
- "src/engine/sensor-discovery.service.ts"(exports) {
5937
- "use strict";
5938
- var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
5939
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5940
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5941
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5942
- return c > 3 && r && Object.defineProperty(target, key, r), r;
5943
- };
5944
- var __metadata = exports && exports.__metadata || function(k, v) {
5945
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5946
- };
5947
- var SensorDiscoveryService_1;
5948
- var _a;
5949
- var _b;
5950
- var _c;
5951
- Object.defineProperty(exports, "__esModule", { value: true });
5952
- exports.SensorDiscoveryService = void 0;
6212
+ exports.SensorDiscoveryService = void 0;
5953
6213
  var common_1 = __require("@nestjs/common");
5954
6214
  var core_1 = __require("@nestjs/core");
5955
6215
  var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
@@ -6168,6 +6428,374 @@ var require_axis_sensor_chain_service = __commonJS({
6168
6428
  }
6169
6429
  });
6170
6430
 
6431
+ // src/timeline/timeline.engine.ts
6432
+ import { createHash as createHash5, randomBytes as randomBytes6 } from "crypto";
6433
+ function generateId(prefix) {
6434
+ return `${prefix}_${randomBytes6(16).toString("hex")}`;
6435
+ }
6436
+ function sha2566(data) {
6437
+ return createHash5("sha256").update(data).digest("hex");
6438
+ }
6439
+ function hashPayload2(payload) {
6440
+ return sha2566(JSON.stringify(payload));
6441
+ }
6442
+ function diffObjects(a, b) {
6443
+ const diffs = [];
6444
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
6445
+ for (const key of allKeys) {
6446
+ const va = a[key];
6447
+ const vb = b[key];
6448
+ if (JSON.stringify(va) !== JSON.stringify(vb)) {
6449
+ diffs.push({ field: key, original: va, replayed: vb });
6450
+ }
6451
+ }
6452
+ return diffs;
6453
+ }
6454
+ var TimelineEngine;
6455
+ var init_timeline_engine = __esm({
6456
+ "src/timeline/timeline.engine.ts"() {
6457
+ TimelineEngine = class {
6458
+ constructor(store) {
6459
+ this.store = store;
6460
+ this.handlers = /* @__PURE__ */ new Map();
6461
+ }
6462
+ /** Register an intent handler for timeline execution */
6463
+ registerHandler(handler) {
6464
+ this.handlers.set(handler.intent, handler);
6465
+ }
6466
+ // ──────────────────────────────────────────────────────────────────────
6467
+ // Record (store a real execution as a timeline event)
6468
+ // ──────────────────────────────────────────────────────────────────────
6469
+ async recordEvent(intent, actorId, payload, result, options = {}) {
6470
+ const event = {
6471
+ event_id: generateId("evt"),
6472
+ timeline_id: options.timelineId ?? "prime",
6473
+ branch_id: options.branchId ?? "main",
6474
+ parent_event_id: options.parentEventId ?? null,
6475
+ intent,
6476
+ actor_id: actorId,
6477
+ capsule_id: options.capsuleId,
6478
+ tps_coordinate: options.tpsCoordinate,
6479
+ payload_hash: hashPayload2(payload),
6480
+ result_hash: hashPayload2(result),
6481
+ status: "executed",
6482
+ domain: "prime",
6483
+ determinism: options.determinism ?? "deterministic",
6484
+ witness_id: options.witnessId,
6485
+ created_at: Date.now(),
6486
+ metadata: { payload, result }
6487
+ };
6488
+ await this.store.saveEvent(event);
6489
+ return event;
6490
+ }
6491
+ // ──────────────────────────────────────────────────────────────────────
6492
+ // Replay
6493
+ // ──────────────────────────────────────────────────────────────────────
6494
+ async replay(request) {
6495
+ const originalEvent = await this.store.getEvent(request.source_event_id);
6496
+ if (!originalEvent) {
6497
+ throw new Error(`Event ${request.source_event_id} not found`);
6498
+ }
6499
+ const handler = this.handlers.get(originalEvent.intent);
6500
+ if (!handler) {
6501
+ throw new Error(`No handler registered for intent '${originalEvent.intent}'`);
6502
+ }
6503
+ const originalPayload = originalEvent.metadata?.payload ?? {};
6504
+ const replayPayload = request.mode === "analytical" && request.override_payload ? request.override_payload : originalPayload;
6505
+ const snapshot = await this.store.getSnapshotByEvent(originalEvent.event_id);
6506
+ const context = {
6507
+ event_id: generateId("evt"),
6508
+ timeline_id: originalEvent.timeline_id,
6509
+ branch_id: `replay_${originalEvent.branch_id}`,
6510
+ domain: "audit",
6511
+ actor_id: originalEvent.actor_id,
6512
+ tps_coordinate: originalEvent.tps_coordinate,
6513
+ snapshot: snapshot ?? void 0,
6514
+ is_replay: true,
6515
+ is_simulation: false
6516
+ };
6517
+ const startMs = Date.now();
6518
+ const handlerResult = await handler.execute(replayPayload, context);
6519
+ const durationMs = Date.now() - startMs;
6520
+ const replayedEvent = {
6521
+ event_id: context.event_id,
6522
+ timeline_id: originalEvent.timeline_id,
6523
+ branch_id: context.branch_id,
6524
+ parent_event_id: originalEvent.event_id,
6525
+ intent: originalEvent.intent,
6526
+ actor_id: originalEvent.actor_id,
6527
+ capsule_id: originalEvent.capsule_id,
6528
+ tps_coordinate: originalEvent.tps_coordinate,
6529
+ payload_hash: hashPayload2(replayPayload),
6530
+ result_hash: hashPayload2(handlerResult.result_data),
6531
+ status: "replayed",
6532
+ domain: "audit",
6533
+ determinism: originalEvent.determinism,
6534
+ created_at: Date.now(),
6535
+ metadata: { payload: replayPayload, result: handlerResult.result_data }
6536
+ };
6537
+ await this.store.saveEvent(replayedEvent);
6538
+ const originalResult = originalEvent.metadata?.result ?? {};
6539
+ const differences = diffObjects(originalResult, handlerResult.result_data);
6540
+ const deterministicMatch = originalEvent.result_hash === replayedEvent.result_hash;
6541
+ return {
6542
+ original_event: originalEvent,
6543
+ replayed_event: replayedEvent,
6544
+ mode: request.mode,
6545
+ deterministic_match: deterministicMatch,
6546
+ differences,
6547
+ duration_ms: durationMs
6548
+ };
6549
+ }
6550
+ // ──────────────────────────────────────────────────────────────────────
6551
+ // Fork
6552
+ // ──────────────────────────────────────────────────────────────────────
6553
+ async fork(request) {
6554
+ const sourceEvent = await this.store.getEvent(request.source_event_id);
6555
+ if (!sourceEvent) {
6556
+ throw new Error(`Event ${request.source_event_id} not found`);
6557
+ }
6558
+ const handler = this.handlers.get(sourceEvent.intent);
6559
+ if (!handler) {
6560
+ throw new Error(`No handler registered for intent '${sourceEvent.intent}'`);
6561
+ }
6562
+ const branch = {
6563
+ branch_id: generateId("branch"),
6564
+ timeline_id: generateId("timeline"),
6565
+ origin_timeline_id: sourceEvent.timeline_id,
6566
+ origin_event_id: sourceEvent.event_id,
6567
+ branch_type: "fork",
6568
+ creator_subject_id: request.actor_id,
6569
+ purpose: request.purpose,
6570
+ status: "active"
6571
+ };
6572
+ await this.store.saveBranch(branch);
6573
+ const snapshot = {
6574
+ snapshot_id: generateId("snap"),
6575
+ timeline_id: sourceEvent.timeline_id,
6576
+ event_id: sourceEvent.event_id,
6577
+ tps_coordinate: sourceEvent.tps_coordinate,
6578
+ state_hash: hashPayload2(
6579
+ sourceEvent.metadata?.result ?? {}
6580
+ ),
6581
+ state_data: sourceEvent.metadata?.result ?? {},
6582
+ created_at: Date.now()
6583
+ };
6584
+ await this.store.saveSnapshot(snapshot);
6585
+ const context = {
6586
+ event_id: generateId("evt"),
6587
+ timeline_id: branch.timeline_id,
6588
+ branch_id: branch.branch_id,
6589
+ domain: "fork",
6590
+ actor_id: request.actor_id,
6591
+ tps_coordinate: sourceEvent.tps_coordinate,
6592
+ snapshot,
6593
+ is_replay: false,
6594
+ is_simulation: false
6595
+ };
6596
+ const handlerResult = await handler.execute(request.new_payload, context);
6597
+ const forkedEvent = {
6598
+ event_id: context.event_id,
6599
+ timeline_id: branch.timeline_id,
6600
+ branch_id: branch.branch_id,
6601
+ parent_event_id: sourceEvent.event_id,
6602
+ intent: sourceEvent.intent,
6603
+ actor_id: request.actor_id,
6604
+ tps_coordinate: sourceEvent.tps_coordinate,
6605
+ payload_hash: hashPayload2(request.new_payload),
6606
+ result_hash: hashPayload2(handlerResult.result_data),
6607
+ status: "forked",
6608
+ domain: "fork",
6609
+ determinism: sourceEvent.determinism,
6610
+ created_at: Date.now(),
6611
+ metadata: {
6612
+ payload: request.new_payload,
6613
+ result: handlerResult.result_data
6614
+ }
6615
+ };
6616
+ await this.store.saveEvent(forkedEvent);
6617
+ return { branch, forked_event: forkedEvent, snapshot };
6618
+ }
6619
+ // ──────────────────────────────────────────────────────────────────────
6620
+ // Simulate
6621
+ // ──────────────────────────────────────────────────────────────────────
6622
+ async simulate(request) {
6623
+ const handler = this.handlers.get(request.intent);
6624
+ if (!handler) {
6625
+ throw new Error(`No handler registered for intent '${request.intent}'`);
6626
+ }
6627
+ let snapshot;
6628
+ if (request.from_snapshot_id) {
6629
+ const loaded = await this.store.getSnapshot(request.from_snapshot_id);
6630
+ if (!loaded) {
6631
+ throw new Error(`Snapshot ${request.from_snapshot_id} not found`);
6632
+ }
6633
+ snapshot = loaded;
6634
+ }
6635
+ const branch = {
6636
+ branch_id: generateId("branch"),
6637
+ timeline_id: generateId("timeline"),
6638
+ origin_timeline_id: "prime",
6639
+ origin_event_id: "simulation_origin",
6640
+ branch_type: "simulation",
6641
+ created_at_tps: request.at_tps,
6642
+ creator_subject_id: request.actor_id,
6643
+ purpose: request.purpose,
6644
+ status: "active"
6645
+ };
6646
+ await this.store.saveBranch(branch);
6647
+ const context = {
6648
+ event_id: generateId("evt"),
6649
+ timeline_id: branch.timeline_id,
6650
+ branch_id: branch.branch_id,
6651
+ domain: "shadow",
6652
+ actor_id: request.actor_id,
6653
+ tps_coordinate: request.at_tps,
6654
+ snapshot,
6655
+ is_replay: false,
6656
+ is_simulation: true
6657
+ };
6658
+ const startMs = Date.now();
6659
+ const handlerResult = await handler.execute(request.payload, context);
6660
+ const durationMs = Date.now() - startMs;
6661
+ const simulatedEvent = {
6662
+ event_id: context.event_id,
6663
+ timeline_id: branch.timeline_id,
6664
+ branch_id: branch.branch_id,
6665
+ parent_event_id: null,
6666
+ intent: request.intent,
6667
+ actor_id: request.actor_id,
6668
+ tps_coordinate: request.at_tps,
6669
+ payload_hash: hashPayload2(request.payload),
6670
+ result_hash: hashPayload2(handlerResult.result_data),
6671
+ status: "simulated",
6672
+ domain: "shadow",
6673
+ determinism: "bounded_nondeterministic",
6674
+ created_at: Date.now(),
6675
+ metadata: { payload: request.payload, result: handlerResult.result_data }
6676
+ };
6677
+ await this.store.saveEvent(simulatedEvent);
6678
+ branch.status = "completed";
6679
+ await this.store.saveBranch(branch);
6680
+ return {
6681
+ branch,
6682
+ simulated_event: simulatedEvent,
6683
+ predicted_outcome: handlerResult.result_data,
6684
+ side_effects: handlerResult.side_effects ?? [],
6685
+ duration_ms: durationMs
6686
+ };
6687
+ }
6688
+ // ──────────────────────────────────────────────────────────────────────
6689
+ // Compare timelines
6690
+ // ──────────────────────────────────────────────────────────────────────
6691
+ async compare(timelineIdA, timelineIdB) {
6692
+ const eventsA = await this.store.getEventsByTimeline(timelineIdA);
6693
+ const eventsB = await this.store.getEventsByTimeline(timelineIdB);
6694
+ eventsA.sort((a, b) => a.created_at - b.created_at);
6695
+ eventsB.sort((a, b) => a.created_at - b.created_at);
6696
+ const maxLen = Math.max(eventsA.length, eventsB.length);
6697
+ const eventPairs = [];
6698
+ let divergencePoint;
6699
+ for (let i = 0; i < maxLen; i++) {
6700
+ const a = eventsA[i];
6701
+ const b = eventsB[i];
6702
+ if (!a || !b) {
6703
+ if (!divergencePoint) {
6704
+ divergencePoint = a?.event_id ?? b?.event_id;
6705
+ }
6706
+ continue;
6707
+ }
6708
+ const match = a.result_hash === b.result_hash;
6709
+ const resultA = a.metadata?.result ?? {};
6710
+ const resultB = b.metadata?.result ?? {};
6711
+ const differences = match ? [] : diffObjects(resultA, resultB);
6712
+ if (!match && !divergencePoint) {
6713
+ divergencePoint = a.event_id;
6714
+ }
6715
+ eventPairs.push({ event_a: a, event_b: b, match, differences });
6716
+ }
6717
+ return {
6718
+ timeline_a: timelineIdA,
6719
+ timeline_b: timelineIdB,
6720
+ event_pairs: eventPairs,
6721
+ divergence_point: divergencePoint
6722
+ };
6723
+ }
6724
+ // ──────────────────────────────────────────────────────────────────────
6725
+ // State snapshot management
6726
+ // ──────────────────────────────────────────────────────────────────────
6727
+ async createSnapshot(eventId, stateData) {
6728
+ const event = await this.store.getEvent(eventId);
6729
+ if (!event) {
6730
+ throw new Error(`Event ${eventId} not found`);
6731
+ }
6732
+ const snapshot = {
6733
+ snapshot_id: generateId("snap"),
6734
+ timeline_id: event.timeline_id,
6735
+ event_id: eventId,
6736
+ tps_coordinate: event.tps_coordinate,
6737
+ state_hash: hashPayload2(stateData),
6738
+ state_data: stateData,
6739
+ created_at: Date.now()
6740
+ };
6741
+ await this.store.saveSnapshot(snapshot);
6742
+ return snapshot;
6743
+ }
6744
+ async restoreSnapshot(snapshotId) {
6745
+ const snapshot = await this.store.getSnapshot(snapshotId);
6746
+ if (!snapshot) {
6747
+ throw new Error(`Snapshot ${snapshotId} not found`);
6748
+ }
6749
+ return snapshot;
6750
+ }
6751
+ };
6752
+ }
6753
+ });
6754
+
6755
+ // src/timeline/timeline.store.ts
6756
+ var InMemoryTimelineStore;
6757
+ var init_timeline_store = __esm({
6758
+ "src/timeline/timeline.store.ts"() {
6759
+ InMemoryTimelineStore = class {
6760
+ constructor() {
6761
+ this.events = /* @__PURE__ */ new Map();
6762
+ this.branches = /* @__PURE__ */ new Map();
6763
+ this.snapshots = /* @__PURE__ */ new Map();
6764
+ }
6765
+ async saveEvent(event) {
6766
+ this.events.set(event.event_id, event);
6767
+ }
6768
+ async getEvent(eventId) {
6769
+ return this.events.get(eventId) ?? null;
6770
+ }
6771
+ async getEventsByTimeline(timelineId) {
6772
+ return [...this.events.values()].filter((e) => e.timeline_id === timelineId);
6773
+ }
6774
+ async getEventsByBranch(branchId) {
6775
+ return [...this.events.values()].filter((e) => e.branch_id === branchId);
6776
+ }
6777
+ async saveBranch(branch) {
6778
+ this.branches.set(branch.branch_id, branch);
6779
+ }
6780
+ async getBranch(branchId) {
6781
+ return this.branches.get(branchId) ?? null;
6782
+ }
6783
+ async getBranchesByTimeline(timelineId) {
6784
+ return [...this.branches.values()].filter((b) => b.timeline_id === timelineId);
6785
+ }
6786
+ async saveSnapshot(snapshot) {
6787
+ this.snapshots.set(snapshot.snapshot_id, snapshot);
6788
+ }
6789
+ async getSnapshot(snapshotId) {
6790
+ return this.snapshots.get(snapshotId) ?? null;
6791
+ }
6792
+ async getSnapshotByEvent(eventId) {
6793
+ return [...this.snapshots.values()].find((s) => s.event_id === eventId) ?? null;
6794
+ }
6795
+ };
6796
+ }
6797
+ });
6798
+
6171
6799
  // src/utils/axis-tlv-codec.ts
6172
6800
  function encodeAxisTlvDto(dtoClass, data) {
6173
6801
  const schema = (0, import_dto_schema.extractDtoSchema)(dtoClass);
@@ -6226,37 +6854,1749 @@ var init_axis_tlv_codec = __esm({
6226
6854
  }
6227
6855
  });
6228
6856
 
6229
- // src/loom/loom.types.ts
6230
- function deriveAnchorReflection(softid, context = "openlogs", scope = "loom") {
6231
- return `ar:${context}:${scope}:${softid}`;
6232
- }
6233
- function canonicalizeWrit(writ) {
6234
- const ordered = {
6235
- head: { tid: writ.head.tid, seq: writ.head.seq },
6236
- body: {
6237
- who: writ.body.who,
6238
- act: writ.body.act,
6239
- res: writ.body.res,
6240
- law: writ.body.law
6241
- },
6242
- meta: { iat: writ.meta.iat, exp: writ.meta.exp, prev: writ.meta.prev }
6243
- };
6244
- return JSON.stringify(ordered);
6245
- }
6246
- function canonicalizeGrant(grant) {
6247
- const ordered = {
6248
- grant_id: grant.grant_id,
6249
- issuer: grant.issuer,
6250
- subject: grant.subject,
6251
- grant_type: grant.grant_type,
6252
- caps: grant.caps,
6253
- meta: grant.meta
6254
- };
6255
- return JSON.stringify(ordered);
6256
- }
6257
- var init_loom_types = __esm({
6258
- "src/loom/loom.types.ts"() {
6259
- init_constants();
6857
+ // src/loom/loom.types.ts
6858
+ function deriveAnchorReflection(softid, context = "openlogs", scope = "loom") {
6859
+ return `ar:${context}:${scope}:${softid}`;
6860
+ }
6861
+ function canonicalizeWrit(writ) {
6862
+ const ordered = {
6863
+ head: { tid: writ.head.tid, seq: writ.head.seq },
6864
+ body: {
6865
+ who: writ.body.who,
6866
+ act: writ.body.act,
6867
+ res: writ.body.res,
6868
+ law: writ.body.law
6869
+ },
6870
+ meta: { iat: writ.meta.iat, exp: writ.meta.exp, prev: writ.meta.prev }
6871
+ };
6872
+ return JSON.stringify(ordered);
6873
+ }
6874
+ function canonicalizeGrant(grant) {
6875
+ const ordered = {
6876
+ grant_id: grant.grant_id,
6877
+ issuer: grant.issuer,
6878
+ subject: grant.subject,
6879
+ grant_type: grant.grant_type,
6880
+ caps: grant.caps,
6881
+ meta: grant.meta
6882
+ };
6883
+ return JSON.stringify(ordered);
6884
+ }
6885
+ var init_loom_types = __esm({
6886
+ "src/loom/loom.types.ts"() {
6887
+ init_constants();
6888
+ }
6889
+ });
6890
+
6891
+ // src/loom/loom.engine.ts
6892
+ import { createHash as createHash6, randomBytes as randomBytes7 } from "crypto";
6893
+ import { sign as sign2 } from "tweetnacl";
6894
+ function sha2567(data) {
6895
+ return createHash6("sha256").update(data).digest("hex");
6896
+ }
6897
+ function hexToUint8(hex) {
6898
+ const bytes2 = new Uint8Array(hex.length / 2);
6899
+ for (let i = 0; i < hex.length; i += 2) {
6900
+ bytes2[i / 2] = parseInt(hex.substring(i, i + 2), 16);
6901
+ }
6902
+ return bytes2;
6903
+ }
6904
+ function uint8ToHex(bytes2) {
6905
+ return Array.from(bytes2).map((b) => b.toString(16).padStart(2, "0")).join("");
6906
+ }
6907
+ function b64ToUint8(b64) {
6908
+ const bin = Buffer.from(b64, "base64");
6909
+ return new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength);
6910
+ }
6911
+ function uint8ToB64(bytes2) {
6912
+ return Buffer.from(bytes2).toString("base64");
6913
+ }
6914
+ function createPresenceChallenge(declaration, ttlMs = DEFAULT_PRESENCE_TTL_MS) {
6915
+ const now = Date.now();
6916
+ const nonce = randomBytes7(32).toString("hex");
6917
+ const challengeId = sha2567(`${declaration.softid}:${nonce}:${now}`);
6918
+ return {
6919
+ challenge_id: challengeId,
6920
+ nonce,
6921
+ temporal_anchor: now,
6922
+ ttl_ms: ttlMs,
6923
+ expires_at: now + ttlMs
6924
+ };
6925
+ }
6926
+ function presenceSigningData(challenge, deviceMeta) {
6927
+ return JSON.stringify({
6928
+ nonce: challenge.nonce,
6929
+ temporal_anchor: challenge.temporal_anchor,
6930
+ device_meta: deviceMeta ?? null
6931
+ });
6932
+ }
6933
+ function signPresenceChallenge(challenge, privateKeyHex, publicKeyHex, declaration, kid) {
6934
+ const data = presenceSigningData(challenge, declaration.device_meta);
6935
+ const msgBytes = new TextEncoder().encode(data);
6936
+ const secretKey = hexToUint8(privateKeyHex);
6937
+ const signature = sign2.detached(msgBytes, secretKey);
6938
+ return {
6939
+ challenge_id: challenge.challenge_id,
6940
+ signature: uint8ToHex(signature),
6941
+ public_key: publicKeyHex,
6942
+ kid
6943
+ };
6944
+ }
6945
+ function verifyPresenceProof(challenge, proof, declaration, durationMs = DEFAULT_PRESENCE_DURATION_MS) {
6946
+ if (Date.now() > challenge.expires_at) {
6947
+ return { valid: false, error: "Challenge expired", code: "CHALLENGE_EXPIRED" };
6948
+ }
6949
+ if (proof.challenge_id !== challenge.challenge_id) {
6950
+ return { valid: false, error: "Challenge ID mismatch", code: "CHALLENGE_MISMATCH" };
6951
+ }
6952
+ const data = presenceSigningData(challenge, declaration.device_meta);
6953
+ const msgBytes = new TextEncoder().encode(data);
6954
+ const sigBytes = hexToUint8(proof.signature);
6955
+ const pubBytes = hexToUint8(proof.public_key);
6956
+ let isValid;
6957
+ try {
6958
+ isValid = sign2.detached.verify(msgBytes, sigBytes, pubBytes);
6959
+ } catch {
6960
+ return { valid: false, error: "Signature verification failed", code: "SIG_INVALID" };
6961
+ }
6962
+ if (!isValid) {
6963
+ return { valid: false, error: "Invalid signature", code: "SIG_INVALID" };
6964
+ }
6965
+ const now = Date.now();
6966
+ const presenceId = sha2567(
6967
+ `${proof.public_key}:${challenge.nonce}:${challenge.temporal_anchor}`
6968
+ );
6969
+ const anchorReflection = sha2567(
6970
+ `ar:openlogs:loom:${proof.public_key}`
6971
+ );
6972
+ const receipt = {
6973
+ presence_id: presenceId,
6974
+ softid: declaration.softid,
6975
+ anchor_reflection: anchorReflection,
6976
+ scope: {
6977
+ device_fingerprint: declaration.device_meta?.fingerprint
6978
+ },
6979
+ issued_at: now,
6980
+ expires_at: now + durationMs
6981
+ };
6982
+ return { valid: true, presence: receipt };
6983
+ }
6984
+ function getPresenceStatus(receipt) {
6985
+ const now = Date.now();
6986
+ if (now > receipt.expires_at) return "expired";
6987
+ return "active";
6988
+ }
6989
+ function renewPresence(receipt, extensionMs = DEFAULT_PRESENCE_DURATION_MS) {
6990
+ const now = Date.now();
6991
+ return {
6992
+ ...receipt,
6993
+ renewed_at: now,
6994
+ expires_at: now + extensionMs
6995
+ };
6996
+ }
6997
+ function createWrit(body, meta, thread, privateKeyHex, kid) {
6998
+ const head = { tid: thread.tid, seq: thread.seq };
6999
+ const writMeta = { ...meta, prev: thread.prevHash };
7000
+ const unsigned = { head, body, meta: writMeta };
7001
+ const canonical = canonicalizeWrit(unsigned);
7002
+ const msgBytes = new TextEncoder().encode(canonical);
7003
+ const secretKey = hexToUint8(privateKeyHex);
7004
+ const signature = sign2.detached(msgBytes, secretKey);
7005
+ const sig = {
7006
+ alg: "ed25519",
7007
+ value: uint8ToB64(signature),
7008
+ kid
7009
+ };
7010
+ return { head, body, meta: writMeta, sig };
7011
+ }
7012
+ function validateWrit(writ, publicKeyHex, threadState, grants) {
7013
+ const now = Math.floor(Date.now() / 1e3);
7014
+ if (now < writ.meta.iat) {
7015
+ return {
7016
+ valid: false,
7017
+ error: "Writ not yet valid (iat in future)",
7018
+ code: "TEMPORAL_NOT_YET",
7019
+ gate_failed: "temporal"
7020
+ };
7021
+ }
7022
+ if (now > writ.meta.exp) {
7023
+ return {
7024
+ valid: false,
7025
+ error: "Writ expired",
7026
+ code: "TEMPORAL_EXPIRED",
7027
+ gate_failed: "temporal"
7028
+ };
7029
+ }
7030
+ if (threadState) {
7031
+ if (writ.head.tid !== threadState.thread_id) {
7032
+ return {
7033
+ valid: false,
7034
+ error: "Thread ID mismatch",
7035
+ code: "CAUSAL_TID",
7036
+ gate_failed: "causal"
7037
+ };
7038
+ }
7039
+ if (writ.head.seq !== threadState.sequence + 1) {
7040
+ return {
7041
+ valid: false,
7042
+ error: `Expected seq ${threadState.sequence + 1}, got ${writ.head.seq}`,
7043
+ code: "CAUSAL_SEQ",
7044
+ gate_failed: "causal"
7045
+ };
7046
+ }
7047
+ if (writ.meta.prev !== threadState.last_receipt_hash) {
7048
+ return {
7049
+ valid: false,
7050
+ error: "Previous receipt hash mismatch",
7051
+ code: "CAUSAL_PREV",
7052
+ gate_failed: "causal"
7053
+ };
7054
+ }
7055
+ } else {
7056
+ if (writ.head.seq !== 1) {
7057
+ return {
7058
+ valid: false,
7059
+ error: "First writ in thread must have seq=1",
7060
+ code: "CAUSAL_FIRST_SEQ",
7061
+ gate_failed: "causal"
7062
+ };
7063
+ }
7064
+ if (writ.meta.prev !== "") {
7065
+ return {
7066
+ valid: false,
7067
+ error: "First writ must have empty prev hash",
7068
+ code: "CAUSAL_FIRST_PREV",
7069
+ gate_failed: "causal"
7070
+ };
7071
+ }
7072
+ }
7073
+ if (writ.body.law !== "self") {
7074
+ const matchingGrant = grants.find(
7075
+ (g) => g.grant_id === writ.body.law && g.subject === writ.body.who && grantCoversAction(g, writ.body.act, writ.body.res, now)
7076
+ );
7077
+ if (!matchingGrant) {
7078
+ return {
7079
+ valid: false,
7080
+ error: `No valid grant found for law=${writ.body.law}`,
7081
+ code: "LEGAL_NO_GRANT",
7082
+ gate_failed: "legal"
7083
+ };
7084
+ }
7085
+ }
7086
+ const unsigned = {
7087
+ head: writ.head,
7088
+ body: writ.body,
7089
+ meta: writ.meta
7090
+ };
7091
+ const canonical = canonicalizeWrit(unsigned);
7092
+ const msgBytes = new TextEncoder().encode(canonical);
7093
+ const sigBytes = b64ToUint8(writ.sig.value);
7094
+ const pubBytes = hexToUint8(publicKeyHex);
7095
+ let sigValid;
7096
+ try {
7097
+ sigValid = sign2.detached.verify(msgBytes, sigBytes, pubBytes);
7098
+ } catch {
7099
+ return {
7100
+ valid: false,
7101
+ error: "Signature verification failed",
7102
+ code: "AUTH_SIG_FAIL",
7103
+ gate_failed: "authentic"
7104
+ };
7105
+ }
7106
+ if (!sigValid) {
7107
+ return {
7108
+ valid: false,
7109
+ error: "Invalid signature",
7110
+ code: "AUTH_SIG_INVALID",
7111
+ gate_failed: "authentic"
7112
+ };
7113
+ }
7114
+ return { valid: true, writ };
7115
+ }
7116
+ function grantCoversAction(grant, action, resource, nowUnix) {
7117
+ if (nowUnix < grant.meta.iat || nowUnix > grant.meta.exp) {
7118
+ return false;
7119
+ }
7120
+ return grant.caps.some(
7121
+ (cap) => matchOec(cap.oec, action) && matchScope(cap.scope, resource)
7122
+ );
7123
+ }
7124
+ function matchOec(pattern, action) {
7125
+ if (pattern === "*") return true;
7126
+ if (pattern === action) return true;
7127
+ if (pattern.endsWith(".*")) {
7128
+ const prefix = pattern.slice(0, -2);
7129
+ return action.startsWith(prefix + ".");
7130
+ }
7131
+ return false;
7132
+ }
7133
+ function matchScope(pattern, resource) {
7134
+ if (pattern === "*") return true;
7135
+ if (pattern === resource) return true;
7136
+ if (pattern.includes("*")) {
7137
+ const regex = new RegExp(
7138
+ "^" + pattern.replace(/\./g, "\\.").replace(/\*/g, "[^:]*") + "$"
7139
+ );
7140
+ return regex.test(resource);
7141
+ }
7142
+ return false;
7143
+ }
7144
+ function getGrantStatus(grant, revocations) {
7145
+ const now = Math.floor(Date.now() / 1e3);
7146
+ const revoked = revocations.find(
7147
+ (r) => r.target_type === "grant" && r.target_id === grant.grant_id
7148
+ );
7149
+ if (revoked && revoked.effective_at <= now * 1e3) {
7150
+ return "revoked";
7151
+ }
7152
+ if (now > grant.meta.exp) return "expired";
7153
+ return "active";
7154
+ }
7155
+ function validateGrant(grant, issuerPublicKeyHex) {
7156
+ const unsigned = {
7157
+ grant_id: grant.grant_id,
7158
+ issuer: grant.issuer,
7159
+ subject: grant.subject,
7160
+ grant_type: grant.grant_type,
7161
+ caps: grant.caps,
7162
+ meta: grant.meta
7163
+ };
7164
+ const canonical = canonicalizeGrant(unsigned);
7165
+ const msgBytes = new TextEncoder().encode(canonical);
7166
+ const sigBytes = b64ToUint8(grant.sig.value);
7167
+ const pubBytes = hexToUint8(issuerPublicKeyHex);
7168
+ let valid;
7169
+ try {
7170
+ valid = sign2.detached.verify(msgBytes, sigBytes, pubBytes);
7171
+ } catch {
7172
+ return { valid: false, error: "Grant signature verification failed", code: "GRANT_SIG_FAIL" };
7173
+ }
7174
+ if (!valid) {
7175
+ return { valid: false, error: "Invalid grant signature", code: "GRANT_SIG_INVALID" };
7176
+ }
7177
+ return { valid: true, grant };
7178
+ }
7179
+ function createGrant(grantId, issuer, subject, grantType, caps, meta, privateKeyHex, kid) {
7180
+ const unsigned = {
7181
+ grant_id: grantId,
7182
+ issuer,
7183
+ subject,
7184
+ grant_type: grantType,
7185
+ caps,
7186
+ meta
7187
+ };
7188
+ const canonical = canonicalizeGrant(unsigned);
7189
+ const msgBytes = new TextEncoder().encode(canonical);
7190
+ const secretKey = hexToUint8(privateKeyHex);
7191
+ const signature = sign2.detached(msgBytes, secretKey);
7192
+ return {
7193
+ ...unsigned,
7194
+ sig: {
7195
+ alg: "ed25519",
7196
+ value: uint8ToB64(signature),
7197
+ kid
7198
+ }
7199
+ };
7200
+ }
7201
+ function createReceipt(writ, effect, prevReceipt, metadata) {
7202
+ const now = Date.now();
7203
+ const sequence = prevReceipt ? prevReceipt.sequence + 1 : 1;
7204
+ const prevHash = prevReceipt?.hash ?? null;
7205
+ const writHash = sha2567(canonicalizeWrit({
7206
+ head: writ.head,
7207
+ body: writ.body,
7208
+ meta: writ.meta
7209
+ }));
7210
+ const hashInput = [
7211
+ prevHash ?? "",
7212
+ writHash,
7213
+ writ.head.tid,
7214
+ String(sequence),
7215
+ effect,
7216
+ String(now)
7217
+ ].join(":");
7218
+ const receiptHash = sha2567(hashInput);
7219
+ const receiptId = sha2567(`receipt:${receiptHash}:${now}`);
7220
+ return {
7221
+ receipt_id: receiptId,
7222
+ writ_hash: writHash,
7223
+ thread_id: writ.head.tid,
7224
+ sequence,
7225
+ effect,
7226
+ hash: receiptHash,
7227
+ prev_hash: prevHash,
7228
+ executed_at: now,
7229
+ metadata
7230
+ };
7231
+ }
7232
+ function verifyReceiptChain(receipts) {
7233
+ if (receipts.length === 0) return { valid: true };
7234
+ const sorted = [...receipts].sort((a, b) => a.sequence - b.sequence);
7235
+ if (sorted[0].prev_hash !== null) {
7236
+ return {
7237
+ valid: false,
7238
+ brokenAt: 0,
7239
+ error: "First receipt must have null prev_hash"
7240
+ };
7241
+ }
7242
+ for (let i = 1; i < sorted.length; i++) {
7243
+ if (sorted[i].prev_hash !== sorted[i - 1].hash) {
7244
+ return {
7245
+ valid: false,
7246
+ brokenAt: i,
7247
+ error: `Receipt ${i} prev_hash does not match receipt ${i - 1} hash`
7248
+ };
7249
+ }
7250
+ }
7251
+ return { valid: true };
7252
+ }
7253
+ function updateThreadState(receipt, softid) {
7254
+ return {
7255
+ thread_id: receipt.thread_id,
7256
+ softid,
7257
+ last_receipt_hash: receipt.hash,
7258
+ sequence: receipt.sequence,
7259
+ updated_at: receipt.executed_at
7260
+ };
7261
+ }
7262
+ function createRevocation(targetType, targetId, issuerSoftid, privateKeyHex, reason) {
7263
+ const now = Date.now();
7264
+ const revocationId = sha2567(`revoke:${targetType}:${targetId}:${now}`);
7265
+ const payload = JSON.stringify({
7266
+ revocation_id: revocationId,
7267
+ target_type: targetType,
7268
+ target_id: targetId,
7269
+ issuer_softid: issuerSoftid,
7270
+ effective_at: now,
7271
+ reason: reason ?? null
7272
+ });
7273
+ const msgBytes = new TextEncoder().encode(payload);
7274
+ const secretKey = hexToUint8(privateKeyHex);
7275
+ const signature = sign2.detached(msgBytes, secretKey);
7276
+ return {
7277
+ revocation_id: revocationId,
7278
+ target_type: targetType,
7279
+ target_id: targetId,
7280
+ issuer_softid: issuerSoftid,
7281
+ reason,
7282
+ effective_at: now,
7283
+ sig_value: uint8ToHex(signature)
7284
+ };
7285
+ }
7286
+ function isRevoked(targetType, targetId, revocations) {
7287
+ const now = Date.now();
7288
+ return revocations.some(
7289
+ (r) => r.target_type === targetType && r.target_id === targetId && r.effective_at <= now
7290
+ );
7291
+ }
7292
+ function executeLoomPipeline(writ, publicKeyHex, presence, threadState, grants, revocations, prevReceipt) {
7293
+ const presenceStatus = getPresenceStatus(presence);
7294
+ if (presenceStatus !== "active") {
7295
+ return { valid: false, error: "Presence not active", code: "PRESENCE_INACTIVE" };
7296
+ }
7297
+ if (isRevoked("presence", presence.presence_id, revocations)) {
7298
+ return { valid: false, error: "Presence revoked", code: "PRESENCE_REVOKED" };
7299
+ }
7300
+ const activeGrants = grants.filter(
7301
+ (g) => getGrantStatus(g, revocations) === "active"
7302
+ );
7303
+ const writResult = validateWrit(writ, publicKeyHex, threadState, activeGrants);
7304
+ if (!writResult.valid) {
7305
+ return { valid: false, error: writResult.error, code: writResult.code };
7306
+ }
7307
+ const receipt = createReceipt(writ, "ALLOW", prevReceipt);
7308
+ const newThreadState = updateThreadState(receipt, writ.body.who);
7309
+ return {
7310
+ receipt,
7311
+ threadState: newThreadState,
7312
+ writValidation: writResult
7313
+ };
7314
+ }
7315
+ var DEFAULT_PRESENCE_TTL_MS, DEFAULT_PRESENCE_DURATION_MS;
7316
+ var init_loom_engine = __esm({
7317
+ "src/loom/loom.engine.ts"() {
7318
+ init_loom_types();
7319
+ DEFAULT_PRESENCE_TTL_MS = 5e3;
7320
+ DEFAULT_PRESENCE_DURATION_MS = 30 * 60 * 1e3;
7321
+ }
7322
+ });
7323
+
7324
+ // src/idel/idel.compiler.ts
7325
+ function validateType(value, expectedType) {
7326
+ switch (expectedType) {
7327
+ case "string":
7328
+ return typeof value === "string";
7329
+ case "number":
7330
+ return typeof value === "number" && Number.isFinite(value);
7331
+ case "boolean":
7332
+ return typeof value === "boolean";
7333
+ case "object":
7334
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7335
+ case "array":
7336
+ return Array.isArray(value);
7337
+ default:
7338
+ return true;
7339
+ }
7340
+ }
7341
+ function assessRisk(schema, proposal, constraints) {
7342
+ const factors = [];
7343
+ let score = 0;
7344
+ const baseRiskMap = {
7345
+ none: 0,
7346
+ low: 0.1,
7347
+ medium: 0.3,
7348
+ high: 0.6,
7349
+ critical: 0.9
7350
+ };
7351
+ score = baseRiskMap[schema.risk_level] ?? 0;
7352
+ if (schema.risk_level !== "none") {
7353
+ factors.push(`Base risk: ${schema.risk_level}`);
7354
+ }
7355
+ if (schema.has_side_effects) {
7356
+ score += 0.1;
7357
+ factors.push("Has side effects");
7358
+ }
7359
+ if (!schema.reversible) {
7360
+ score += 0.1;
7361
+ factors.push("Not reversible");
7362
+ }
7363
+ const failed = constraints.filter((c) => !c.satisfied);
7364
+ if (failed.length > 0) {
7365
+ score += 0.05 * failed.length;
7366
+ factors.push(`${failed.length} unsatisfied constraint(s)`);
7367
+ }
7368
+ score = Math.min(score, 1);
7369
+ let level;
7370
+ if (score <= 0) level = "none";
7371
+ else if (score <= 0.2) level = "low";
7372
+ else if (score <= 0.5) level = "medium";
7373
+ else if (score <= 0.8) level = "high";
7374
+ else level = "critical";
7375
+ return { level, score, factors };
7376
+ }
7377
+ var IdelSchemaRegistry, IdelCompiler;
7378
+ var init_idel_compiler = __esm({
7379
+ "src/idel/idel.compiler.ts"() {
7380
+ IdelSchemaRegistry = class {
7381
+ constructor() {
7382
+ this.schemas = /* @__PURE__ */ new Map();
7383
+ this.aliases = /* @__PURE__ */ new Map();
7384
+ }
7385
+ register(schema) {
7386
+ this.schemas.set(schema.intent, schema);
7387
+ }
7388
+ registerAlias(alias, intent) {
7389
+ this.aliases.set(alias.toLowerCase(), intent);
7390
+ }
7391
+ get(intent) {
7392
+ return this.schemas.get(intent);
7393
+ }
7394
+ resolve(raw) {
7395
+ const exact = this.schemas.get(raw);
7396
+ if (exact) return exact;
7397
+ const aliased = this.aliases.get(raw.toLowerCase());
7398
+ if (aliased) return this.schemas.get(aliased);
7399
+ const candidates = [...this.schemas.keys()].filter(
7400
+ (k) => k.startsWith(raw + ".") || k.toLowerCase().includes(raw.toLowerCase())
7401
+ );
7402
+ if (candidates.length === 1) {
7403
+ return this.schemas.get(candidates[0]);
7404
+ }
7405
+ return void 0;
7406
+ }
7407
+ /**
7408
+ * Find all schemas that partially match the raw input.
7409
+ * Returns scored candidates for ambiguity resolution.
7410
+ */
7411
+ findCandidates(raw) {
7412
+ const normalized = raw.toLowerCase().trim();
7413
+ const results = [];
7414
+ for (const [key, schema] of this.schemas) {
7415
+ let score = 0;
7416
+ if (key === raw) {
7417
+ score = 1;
7418
+ } else if (key.toLowerCase() === normalized) {
7419
+ score = 0.95;
7420
+ } else if (this.aliases.get(normalized) === key) {
7421
+ score = 0.9;
7422
+ } else if (key.toLowerCase().startsWith(normalized)) {
7423
+ score = 0.7;
7424
+ } else if (key.toLowerCase().includes(normalized)) {
7425
+ score = 0.5;
7426
+ } else if (schema.tags?.some((t) => t.toLowerCase().includes(normalized))) {
7427
+ score = 0.4;
7428
+ } else if (schema.description.toLowerCase().includes(normalized)) {
7429
+ score = 0.3;
7430
+ }
7431
+ if (score > 0) {
7432
+ results.push({ schema, score });
7433
+ }
7434
+ }
7435
+ return results.sort((a, b) => b.score - a.score);
7436
+ }
7437
+ list() {
7438
+ return [...this.schemas.values()];
7439
+ }
7440
+ };
7441
+ IdelCompiler = class {
7442
+ constructor(registry) {
7443
+ this.registry = registry;
7444
+ }
7445
+ /**
7446
+ * Compile a raw intent proposal into a validated, executable structure.
7447
+ */
7448
+ compile(proposal) {
7449
+ const errors = [];
7450
+ const candidates = this.registry.findCandidates(proposal.raw);
7451
+ if (candidates.length === 0) {
7452
+ return {
7453
+ ok: false,
7454
+ errors: [{
7455
+ code: "IDEL_UNKNOWN_INTENT",
7456
+ message: `No intent found matching '${proposal.raw}'`
7457
+ }]
7458
+ };
7459
+ }
7460
+ const best = candidates[0];
7461
+ const schema = best.schema;
7462
+ const alternatives = candidates.slice(1, 4).filter((c) => c.score >= 0.3).map((c) => ({
7463
+ intent: c.schema.intent,
7464
+ confidence: c.score,
7465
+ reason: c.schema.description
7466
+ }));
7467
+ const constraints = [];
7468
+ const clarifications = [];
7469
+ const params = { ...proposal.params };
7470
+ for (const paramSchema of schema.params) {
7471
+ const value = params[paramSchema.name];
7472
+ if (paramSchema.required && value === void 0) {
7473
+ if (paramSchema.default !== void 0) {
7474
+ params[paramSchema.name] = paramSchema.default;
7475
+ constraints.push({
7476
+ kind: "required_param",
7477
+ field: paramSchema.name,
7478
+ description: `Defaulted to ${JSON.stringify(paramSchema.default)}`,
7479
+ satisfied: true,
7480
+ value: paramSchema.default
7481
+ });
7482
+ } else {
7483
+ constraints.push({
7484
+ kind: "required_param",
7485
+ field: paramSchema.name,
7486
+ description: `Required parameter '${paramSchema.name}' is missing`,
7487
+ satisfied: false
7488
+ });
7489
+ clarifications.push({
7490
+ id: `clarify_${paramSchema.name}`,
7491
+ question: paramSchema.description ?? `What is the ${paramSchema.name}?`,
7492
+ field: paramSchema.name,
7493
+ options: paramSchema.enum?.map(String),
7494
+ required: true
7495
+ });
7496
+ }
7497
+ continue;
7498
+ }
7499
+ if (value === void 0) continue;
7500
+ const typeValid = validateType(value, paramSchema.type);
7501
+ constraints.push({
7502
+ kind: "type_check",
7503
+ field: paramSchema.name,
7504
+ description: `Must be ${paramSchema.type}`,
7505
+ satisfied: typeValid,
7506
+ value,
7507
+ expected: paramSchema.type
7508
+ });
7509
+ if (!typeValid) {
7510
+ errors.push({
7511
+ code: "IDEL_TYPE_ERROR",
7512
+ message: `Parameter '${paramSchema.name}' must be ${paramSchema.type}, got ${typeof value}`,
7513
+ field: paramSchema.name
7514
+ });
7515
+ }
7516
+ if (paramSchema.min !== void 0 || paramSchema.max !== void 0) {
7517
+ const numVal = typeof value === "number" ? value : Number(value);
7518
+ const inRange = (paramSchema.min === void 0 || numVal >= paramSchema.min) && (paramSchema.max === void 0 || numVal <= paramSchema.max);
7519
+ constraints.push({
7520
+ kind: "range",
7521
+ field: paramSchema.name,
7522
+ description: `Must be between ${paramSchema.min ?? "-\u221E"} and ${paramSchema.max ?? "\u221E"}`,
7523
+ satisfied: inRange,
7524
+ value: numVal
7525
+ });
7526
+ }
7527
+ if (paramSchema.pattern) {
7528
+ const matches = new RegExp(paramSchema.pattern).test(String(value));
7529
+ constraints.push({
7530
+ kind: "pattern",
7531
+ field: paramSchema.name,
7532
+ description: `Must match ${paramSchema.pattern}`,
7533
+ satisfied: matches,
7534
+ value,
7535
+ expected: paramSchema.pattern
7536
+ });
7537
+ }
7538
+ if (paramSchema.enum) {
7539
+ const inEnum = paramSchema.enum.some(
7540
+ (e) => JSON.stringify(e) === JSON.stringify(value)
7541
+ );
7542
+ constraints.push({
7543
+ kind: "custom",
7544
+ field: paramSchema.name,
7545
+ description: `Must be one of: ${paramSchema.enum.join(", ")}`,
7546
+ satisfied: inEnum,
7547
+ value,
7548
+ expected: paramSchema.enum
7549
+ });
7550
+ }
7551
+ }
7552
+ const risk = assessRisk(schema, proposal, constraints);
7553
+ const unsatisfied = constraints.filter((c) => !c.satisfied);
7554
+ const needsClarification = clarifications.length > 0;
7555
+ let confidence = best.score;
7556
+ if (unsatisfied.length > 0) {
7557
+ confidence *= 1 - unsatisfied.length / Math.max(constraints.length, 1) * 0.5;
7558
+ }
7559
+ if (errors.length > 0) {
7560
+ confidence *= 0.5;
7561
+ }
7562
+ const compiled = {
7563
+ intent: schema.intent,
7564
+ actor_id: proposal.actor_id,
7565
+ target: proposal.target,
7566
+ params,
7567
+ constraints,
7568
+ confidence,
7569
+ alternatives,
7570
+ needs_clarification: needsClarification,
7571
+ clarifications,
7572
+ expected_outcome: schema.description,
7573
+ fallback: schema.related?.[0],
7574
+ risk,
7575
+ metadata: {
7576
+ schema_intent: schema.intent,
7577
+ resolved_from: proposal.raw,
7578
+ has_side_effects: schema.has_side_effects,
7579
+ reversible: schema.reversible
7580
+ }
7581
+ };
7582
+ return {
7583
+ ok: errors.length === 0 && !needsClarification,
7584
+ compiled,
7585
+ errors
7586
+ };
7587
+ }
7588
+ /**
7589
+ * Apply clarification answers and re-compile.
7590
+ */
7591
+ applyClarifications(compiled, answers) {
7592
+ const proposal = {
7593
+ raw: compiled.intent,
7594
+ actor_id: compiled.actor_id,
7595
+ target: compiled.target,
7596
+ params: { ...compiled.params, ...answers }
7597
+ };
7598
+ return this.compile(proposal);
7599
+ }
7600
+ };
7601
+ }
7602
+ });
7603
+
7604
+ // src/needle/needle.engine.ts
7605
+ import { randomBytes as randomBytes8 } from "crypto";
7606
+ function assembleNeedle(params) {
7607
+ return {
7608
+ needle_id: randomBytes8(16).toString("hex"),
7609
+ phase: "created",
7610
+ tps_coordinate: params.tps_coordinate,
7611
+ intent: params.intent,
7612
+ presence: params.presence,
7613
+ writ: params.writ,
7614
+ grants: params.grants,
7615
+ created_at: Date.now()
7616
+ };
7617
+ }
7618
+ function classifyStitch(observation, verdict) {
7619
+ if (verdict.status === "failed" || verdict.status === "disputed") {
7620
+ return "torn";
7621
+ }
7622
+ if (observation.decision === "DENY") {
7623
+ return "silent";
7624
+ }
7625
+ if (verdict.isDeed) {
7626
+ return "deed";
7627
+ }
7628
+ return "silent";
7629
+ }
7630
+ function formStitch(needle, observation, verdict, receipt) {
7631
+ return {
7632
+ stitch_id: needle.needle_id,
7633
+ kind: classifyStitch(observation, verdict),
7634
+ intent: needle.intent.intent,
7635
+ actor_id: needle.intent.actor_id,
7636
+ tps_coordinate: needle.tps_coordinate,
7637
+ observation,
7638
+ verdict,
7639
+ receipt,
7640
+ thread_id: receipt.thread_id,
7641
+ sequence: receipt.sequence,
7642
+ stitched_at: Date.now()
7643
+ };
7644
+ }
7645
+ async function runNeedlePipeline(needle, config, threadState, prevReceipt, expectedOutcome) {
7646
+ const obs = createObservation("http");
7647
+ obs.intent = needle.intent.intent;
7648
+ obs.actorId = needle.intent.actor_id;
7649
+ needle.phase = "validated";
7650
+ let stage = startStage(obs, "loom.validate");
7651
+ const validation = validateWrit(
7652
+ needle.writ,
7653
+ config.public_key,
7654
+ threadState,
7655
+ needle.grants
7656
+ );
7657
+ if (!validation.valid) {
7658
+ endStage(stage, "fail", validation.error);
7659
+ return failNeedle(needle, obs, "validated", "LOOM_VALIDATION_FAILED", validation.error ?? "Writ validation failed");
7660
+ }
7661
+ endStage(stage, "ok");
7662
+ if (config.sensors && config.sensors.length > 0) {
7663
+ stage = startStage(obs, "sensors.evaluate");
7664
+ const sensorInput = {
7665
+ intent: needle.intent.intent,
7666
+ actorId: needle.intent.actor_id,
7667
+ metadata: {
7668
+ observation: obs,
7669
+ needle_id: needle.needle_id,
7670
+ tps_coordinate: needle.tps_coordinate,
7671
+ writ: needle.writ,
7672
+ grants: needle.grants,
7673
+ params: needle.intent.params
7674
+ }
7675
+ };
7676
+ for (const sensor of config.sensors) {
7677
+ if (sensor.supports && !sensor.supports(sensorInput)) continue;
7678
+ const t0 = Date.now();
7679
+ let decision;
7680
+ try {
7681
+ const rawDecision = await sensor.run(sensorInput);
7682
+ decision = normalizeSensorDecision(rawDecision);
7683
+ } catch (err) {
7684
+ const msg = err instanceof Error ? err.message : String(err);
7685
+ recordSensor(obs, sensor.name, false, 100, Date.now() - t0, [`sensor_error:${msg}`]);
7686
+ endStage(stage, "fail", `Sensor ${sensor.name} threw: ${msg}`);
7687
+ return failNeedle(needle, obs, "validated", "SENSOR_ERROR", `Sensor ${sensor.name} failed: ${msg}`);
7688
+ }
7689
+ recordSensor(obs, sensor.name, decision.allow, decision.riskScore, Date.now() - t0, decision.reasons);
7690
+ if (!decision.allow) {
7691
+ endStage(stage, "fail", `Sensor ${sensor.name} denied`);
7692
+ return failNeedle(needle, obs, "validated", "SENSOR_DENY", decision.reasons[0] ?? `Denied by ${sensor.name}`);
7693
+ }
7694
+ }
7695
+ endStage(stage, "ok");
7696
+ }
7697
+ needle.phase = "executing";
7698
+ stage = startStage(obs, "handler.execute");
7699
+ const handler = config.handlers.get(needle.intent.intent);
7700
+ if (!handler) {
7701
+ endStage(stage, "fail", `No handler for intent '${needle.intent.intent}'`);
7702
+ return failNeedle(needle, obs, "executing", "NO_HANDLER", `No handler registered for intent '${needle.intent.intent}'`);
7703
+ }
7704
+ const handlerCtx = {
7705
+ needle_id: needle.needle_id,
7706
+ actor_id: needle.intent.actor_id,
7707
+ presence_id: needle.presence.presence_id,
7708
+ writ: needle.writ,
7709
+ grants: needle.grants,
7710
+ tps_coordinate: needle.tps_coordinate
7711
+ };
7712
+ let handlerResult;
7713
+ try {
7714
+ handlerResult = await handler(needle.intent, handlerCtx);
7715
+ } catch (err) {
7716
+ const msg = err instanceof Error ? err.message : String(err);
7717
+ endStage(stage, "fail", msg);
7718
+ return failNeedle(needle, obs, "executing", "HANDLER_ERROR", msg);
7719
+ }
7720
+ if (!handlerResult.ok) {
7721
+ endStage(stage, "fail", handlerResult.effect);
7722
+ obs.decision = "DENY";
7723
+ obs.resultCode = handlerResult.effect;
7724
+ obs.statusCode = handlerResult.status_code ?? 400;
7725
+ } else {
7726
+ endStage(stage, "ok");
7727
+ obs.decision = "ALLOW";
7728
+ obs.resultCode = handlerResult.effect;
7729
+ obs.statusCode = handlerResult.status_code ?? 200;
7730
+ }
7731
+ if (handlerResult.data) {
7732
+ obs.facts = { ...obs.facts, ...handlerResult.data };
7733
+ }
7734
+ needle.phase = "observed";
7735
+ finalizeObservation(obs, obs.decision ?? "DENY", obs.statusCode ?? 500, obs.resultCode);
7736
+ needle.observation = obs;
7737
+ const verdict = scoreTruth(obs, expectedOutcome);
7738
+ needle.verdict = verdict;
7739
+ needle.phase = "stitched";
7740
+ stage = startStage(obs, "stitch.form");
7741
+ const receipt = createReceipt(
7742
+ needle.writ,
7743
+ obs.decision ?? "DENY",
7744
+ prevReceipt
7745
+ );
7746
+ needle.receipt = receipt;
7747
+ const newThreadState = updateThreadState(
7748
+ receipt,
7749
+ needle.intent.actor_id
7750
+ );
7751
+ const stitch = formStitch(needle, obs, verdict, receipt);
7752
+ needle.completed_at = Date.now();
7753
+ endStage(stage, "ok");
7754
+ return {
7755
+ ok: handlerResult.ok,
7756
+ needle,
7757
+ stitch,
7758
+ thread_state: newThreadState
7759
+ };
7760
+ }
7761
+ function failNeedle(needle, obs, phase, code, message) {
7762
+ needle.phase = "failed";
7763
+ needle.error = { phase, code, message };
7764
+ needle.completed_at = Date.now();
7765
+ obs.decision = obs.decision ?? "DENY";
7766
+ obs.statusCode = obs.statusCode ?? 500;
7767
+ finalizeObservation(obs, obs.decision, obs.statusCode, obs.resultCode);
7768
+ needle.observation = obs;
7769
+ const verdict = scoreTruth(obs);
7770
+ needle.verdict = verdict;
7771
+ return {
7772
+ ok: false,
7773
+ needle
7774
+ };
7775
+ }
7776
+ var init_needle_engine = __esm({
7777
+ "src/needle/needle.engine.ts"() {
7778
+ init_axis_observation();
7779
+ init_truth_scoring();
7780
+ init_loom_engine();
7781
+ init_axis_sensor();
7782
+ }
7783
+ });
7784
+
7785
+ // src/needle/knot.engine.ts
7786
+ import { createHash as createHash8, randomBytes as randomBytes9 } from "crypto";
7787
+ function openKnot(params) {
7788
+ const isIrreversible = params.type === "irreversible";
7789
+ return {
7790
+ knot_id: `knot_${randomBytes9(16).toString("hex")}`,
7791
+ type: params.type,
7792
+ status: "open",
7793
+ stitch_ids: [],
7794
+ thread_id: params.thread_id,
7795
+ tps_anchor: params.tps_anchor,
7796
+ irreversible: isIrreversible,
7797
+ capsule_id: params.capsule_id,
7798
+ law_ref: params.law_ref,
7799
+ branch_ids: [],
7800
+ required_count: params.required_count,
7801
+ all_or_nothing: params.all_or_nothing ?? (params.type === "authority" || isIrreversible),
7802
+ actor_id: params.actor_id,
7803
+ created_at: Date.now()
7804
+ };
7805
+ }
7806
+ function addStitchToKnot(knot, stitch) {
7807
+ if (knot.status !== "open") {
7808
+ return `Knot ${knot.knot_id} is ${knot.status}, cannot add stitches`;
7809
+ }
7810
+ if (stitch.thread_id !== knot.thread_id) {
7811
+ return `Stitch thread ${stitch.thread_id} does not match knot thread ${knot.thread_id}`;
7812
+ }
7813
+ if (knot.stitch_ids.includes(stitch.stitch_id)) {
7814
+ return `Stitch ${stitch.stitch_id} already in knot`;
7815
+ }
7816
+ if (knot.type === "authority" && knot.capsule_id) {
7817
+ if (stitch.observation.capsuleId && stitch.observation.capsuleId !== knot.capsule_id) {
7818
+ return `Stitch capsule ${stitch.observation.capsuleId} does not match knot capsule ${knot.capsule_id}`;
7819
+ }
7820
+ }
7821
+ knot.stitch_ids.push(stitch.stitch_id);
7822
+ return null;
7823
+ }
7824
+ function validateKnot(knot, stitches) {
7825
+ const errors = [];
7826
+ const passedIds = [];
7827
+ const failedIds = [];
7828
+ const stitchMap = new Map(stitches.map((s) => [s.stitch_id, s]));
7829
+ for (const sid of knot.stitch_ids) {
7830
+ const stitch = stitchMap.get(sid);
7831
+ if (!stitch) {
7832
+ failedIds.push(sid);
7833
+ errors.push({
7834
+ code: "KNOT_MISSING_STITCH",
7835
+ message: `Stitch ${sid} not found`,
7836
+ stitch_id: sid
7837
+ });
7838
+ continue;
7839
+ }
7840
+ if (stitch.kind === "torn") {
7841
+ failedIds.push(sid);
7842
+ errors.push({
7843
+ code: "KNOT_TORN_STITCH",
7844
+ message: `Stitch ${sid} is torn (failed/disputed)`,
7845
+ stitch_id: sid
7846
+ });
7847
+ continue;
7848
+ }
7849
+ if (knot.type === "irreversible" && stitch.kind !== "deed") {
7850
+ failedIds.push(sid);
7851
+ errors.push({
7852
+ code: "KNOT_REQUIRES_DEED",
7853
+ message: `Irreversible knot requires deed stitch, got '${stitch.kind}'`,
7854
+ stitch_id: sid
7855
+ });
7856
+ continue;
7857
+ }
7858
+ passedIds.push(sid);
7859
+ }
7860
+ if (knot.required_count !== void 0 && knot.stitch_ids.length < knot.required_count) {
7861
+ errors.push({
7862
+ code: "KNOT_INSUFFICIENT_STITCHES",
7863
+ message: `Knot requires ${knot.required_count} stitches, has ${knot.stitch_ids.length}`
7864
+ });
7865
+ }
7866
+ const allPassed = failedIds.length === 0;
7867
+ const canTie = knot.all_or_nothing ? allPassed && (knot.required_count === void 0 || knot.stitch_ids.length >= knot.required_count) : passedIds.length > 0 && (knot.required_count === void 0 || passedIds.length >= knot.required_count);
7868
+ return {
7869
+ valid: allPassed && errors.length === 0,
7870
+ passed_stitch_ids: passedIds,
7871
+ failed_stitch_ids: failedIds,
7872
+ can_tie: canTie,
7873
+ errors
7874
+ };
7875
+ }
7876
+ function tieKnot(knot, stitches) {
7877
+ const validation = validateKnot(knot, stitches);
7878
+ if (!validation.can_tie) {
7879
+ return { ...validation, knot };
7880
+ }
7881
+ const receiptHashes = validation.passed_stitch_ids.map((sid) => stitches.find((s) => s.stitch_id === sid)).sort((a, b) => a.sequence - b.sequence).map((s) => s.receipt.hash);
7882
+ const witnessPayload = receiptHashes.join(":");
7883
+ knot.witness_hash = createHash8("sha256").update(witnessPayload).digest("hex");
7884
+ knot.status = "tied";
7885
+ knot.tied_at = Date.now();
7886
+ return { ...validation, knot };
7887
+ }
7888
+ function breakKnot(knot, request) {
7889
+ if (knot.status === "broken") {
7890
+ return { ok: false, error: "Knot is already broken" };
7891
+ }
7892
+ if (knot.status === "open") {
7893
+ knot.status = "broken";
7894
+ knot.broken_at = Date.now();
7895
+ knot.break_reason = request.reason;
7896
+ return { ok: true };
7897
+ }
7898
+ if (knot.status === "tied") {
7899
+ if (!request.reason) {
7900
+ return { ok: false, error: "Breaking a tied knot requires a reason" };
7901
+ }
7902
+ if ((knot.irreversible || knot.type === "law") && !request.override_grant_id) {
7903
+ return {
7904
+ ok: false,
7905
+ error: `Breaking ${knot.type} knot requires override_grant_id from higher authority`
7906
+ };
7907
+ }
7908
+ knot.status = "broken";
7909
+ knot.broken_at = Date.now();
7910
+ knot.break_reason = request.reason;
7911
+ return { ok: true };
7912
+ }
7913
+ return { ok: false, error: `Cannot break knot in status '${knot.status}'` };
7914
+ }
7915
+ function forkFromKnot(knot, branchId, decisionStitchId) {
7916
+ if (knot.status !== "tied" && knot.status !== "open") {
7917
+ return { ok: false, error: `Cannot fork from knot in status '${knot.status}'` };
7918
+ }
7919
+ if (decisionStitchId) {
7920
+ if (!knot.stitch_ids.includes(decisionStitchId)) {
7921
+ return { ok: false, error: `Decision stitch ${decisionStitchId} is not part of this knot` };
7922
+ }
7923
+ knot.decision_stitch_id = decisionStitchId;
7924
+ }
7925
+ knot.branch_ids.push(branchId);
7926
+ knot.status = "forked";
7927
+ return { ok: true };
7928
+ }
7929
+ function isKnotOpen(knot) {
7930
+ return knot.status === "open";
7931
+ }
7932
+ function isPointOfNoReturn(knot) {
7933
+ return knot.irreversible && knot.status === "tied";
7934
+ }
7935
+ function findKnotsForStitch(stitchId, knots) {
7936
+ return knots.filter((k) => k.stitch_ids.includes(stitchId));
7937
+ }
7938
+ function getIrreversibleKnots(knots) {
7939
+ return knots.filter((k) => k.irreversible && k.status === "tied");
7940
+ }
7941
+ function getDecisionPoints(knots) {
7942
+ return knots.filter((k) => k.type === "decision" || k.status === "forked");
7943
+ }
7944
+ var init_knot_engine = __esm({
7945
+ "src/needle/knot.engine.ts"() {
7946
+ }
7947
+ });
7948
+
7949
+ // src/needle/fabric.engine.ts
7950
+ import { createHash as createHash9, randomBytes as randomBytes10 } from "crypto";
7951
+ function createFabric() {
7952
+ return {
7953
+ fabric_id: `fab_${randomBytes10(16).toString("hex")}`,
7954
+ state_hash: hashState(/* @__PURE__ */ new Map()),
7955
+ cells: /* @__PURE__ */ new Map(),
7956
+ thread_ids: [],
7957
+ stitch_count: 0,
7958
+ knot_count: 0,
7959
+ computed_at: Date.now(),
7960
+ version: 0
7961
+ };
7962
+ }
7963
+ function applyStitch(fabric, stitch, effect) {
7964
+ for (const [key, value] of Object.entries(effect.mutations)) {
7965
+ if (value === null) {
7966
+ fabric.cells.delete(key);
7967
+ } else {
7968
+ const existing = fabric.cells.get(key);
7969
+ if (existing?.locked) {
7970
+ continue;
7971
+ }
7972
+ fabric.cells.set(key, {
7973
+ key,
7974
+ value,
7975
+ last_stitch_id: stitch.stitch_id,
7976
+ last_tps: stitch.tps_coordinate,
7977
+ write_count: (existing?.write_count ?? 0) + 1,
7978
+ locked: false
7979
+ });
7980
+ }
7981
+ }
7982
+ if (!fabric.thread_ids.includes(stitch.thread_id)) {
7983
+ fabric.thread_ids.push(stitch.thread_id);
7984
+ }
7985
+ fabric.stitch_count++;
7986
+ fabric.version++;
7987
+ fabric.projected_at_tps = stitch.tps_coordinate ?? fabric.projected_at_tps;
7988
+ fabric.computed_at = Date.now();
7989
+ fabric.state_hash = hashState(fabric.cells);
7990
+ }
7991
+ function weave(stitches, resolver, knots) {
7992
+ const fabric = createFabric();
7993
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
7994
+ for (const stitch of sorted) {
7995
+ if (stitch.kind === "torn") continue;
7996
+ const effect = resolver(stitch);
7997
+ applyStitch(fabric, stitch, effect);
7998
+ }
7999
+ if (knots) {
8000
+ for (const knot of knots) {
8001
+ if (knot.irreversible && knot.status === "tied") {
8002
+ lockCellsByKnot(fabric, knot, stitches, resolver);
8003
+ fabric.knot_count++;
8004
+ }
8005
+ }
8006
+ }
8007
+ return fabric;
8008
+ }
8009
+ function projectAt(stitches, resolver, tpsFilter, knots) {
8010
+ const filtered = stitches.filter((s) => tpsFilter(s.tps_coordinate));
8011
+ return weave(filtered, resolver, knots);
8012
+ }
8013
+ function lockCellsByKnot(fabric, knot, stitches, resolver) {
8014
+ const knotStitchIds = new Set(knot.stitch_ids);
8015
+ const knotStitches = stitches.filter((s) => knotStitchIds.has(s.stitch_id));
8016
+ for (const stitch of knotStitches) {
8017
+ const effect = resolver(stitch);
8018
+ for (const key of Object.keys(effect.mutations)) {
8019
+ const cell = fabric.cells.get(key);
8020
+ if (cell) {
8021
+ cell.locked = true;
8022
+ cell.locked_by_knot = knot.knot_id;
8023
+ }
8024
+ }
8025
+ }
8026
+ }
8027
+ function lockCells(fabric, keys, knotId) {
8028
+ for (const key of keys) {
8029
+ const cell = fabric.cells.get(key);
8030
+ if (cell) {
8031
+ cell.locked = true;
8032
+ cell.locked_by_knot = knotId;
8033
+ }
8034
+ }
8035
+ }
8036
+ function queryFabric(fabric, query) {
8037
+ let results = [...fabric.cells.values()];
8038
+ if (query.keys) {
8039
+ const keySet = new Set(query.keys);
8040
+ results = results.filter((c) => keySet.has(c.key));
8041
+ }
8042
+ if (query.prefix) {
8043
+ const prefix = query.prefix;
8044
+ results = results.filter((c) => c.key.startsWith(prefix));
8045
+ }
8046
+ if (query.locked_only) {
8047
+ results = results.filter((c) => c.locked);
8048
+ }
8049
+ return results;
8050
+ }
8051
+ function getFabricValue(fabric, key) {
8052
+ return fabric.cells.get(key)?.value;
8053
+ }
8054
+ function diffFabrics(a, b) {
8055
+ const entries = [];
8056
+ let added = 0;
8057
+ let modified = 0;
8058
+ let deleted = 0;
8059
+ for (const [key, cellB] of b.cells) {
8060
+ const cellA = a.cells.get(key);
8061
+ if (!cellA) {
8062
+ entries.push({
8063
+ key,
8064
+ kind: "added",
8065
+ after: cellB.value,
8066
+ caused_by_stitch: cellB.last_stitch_id
8067
+ });
8068
+ added++;
8069
+ } else if (JSON.stringify(cellA.value) !== JSON.stringify(cellB.value)) {
8070
+ entries.push({
8071
+ key,
8072
+ kind: "modified",
8073
+ before: cellA.value,
8074
+ after: cellB.value,
8075
+ caused_by_stitch: cellB.last_stitch_id
8076
+ });
8077
+ modified++;
8078
+ }
8079
+ }
8080
+ for (const [key, cellA] of a.cells) {
8081
+ if (!b.cells.has(key)) {
8082
+ entries.push({
8083
+ key,
8084
+ kind: "deleted",
8085
+ before: cellA.value
8086
+ });
8087
+ deleted++;
8088
+ }
8089
+ }
8090
+ return {
8091
+ from_fabric_id: a.fabric_id,
8092
+ to_fabric_id: b.fabric_id,
8093
+ entries,
8094
+ added_count: added,
8095
+ modified_count: modified,
8096
+ deleted_count: deleted
8097
+ };
8098
+ }
8099
+ function hashState(cells) {
8100
+ const keys = [...cells.keys()].sort();
8101
+ const payload = keys.map((k) => `${k}=${JSON.stringify(cells.get(k).value)}`).join("\n");
8102
+ return createHash9("sha256").update(payload).digest("hex");
8103
+ }
8104
+ var init_fabric_engine = __esm({
8105
+ "src/needle/fabric.engine.ts"() {
8106
+ }
8107
+ });
8108
+
8109
+ // src/needle/pattern.engine.ts
8110
+ import { randomBytes as randomBytes11 } from "crypto";
8111
+ function detectSequencePatterns(stitches, windowSize, minOccurrences) {
8112
+ if (stitches.length < windowSize || windowSize < 2) return [];
8113
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
8114
+ const sequenceCounts = /* @__PURE__ */ new Map();
8115
+ for (let i = 0; i <= sorted.length - windowSize; i++) {
8116
+ const window = sorted.slice(i, i + windowSize);
8117
+ const key = window.map((s) => s.intent).join("\u2192");
8118
+ const ids = window.map((s) => s.stitch_id);
8119
+ const existing = sequenceCounts.get(key);
8120
+ if (existing) {
8121
+ existing.count++;
8122
+ existing.stitch_ids.push(ids);
8123
+ } else {
8124
+ sequenceCounts.set(key, { count: 1, stitch_ids: [ids] });
8125
+ }
8126
+ }
8127
+ const patterns = [];
8128
+ const now = Date.now();
8129
+ for (const [key, data] of sequenceCounts) {
8130
+ if (data.count < minOccurrences) continue;
8131
+ const intents = key.split("\u2192");
8132
+ const confidence = Math.min(data.count / (minOccurrences * 2), 1);
8133
+ patterns.push({
8134
+ pattern_id: `pat_seq_${randomBytes11(8).toString("hex")}`,
8135
+ kind: "sequence",
8136
+ name: `Sequence: ${intents.join(" \u2192 ")}`,
8137
+ signature: {
8138
+ intent_sequence: intents,
8139
+ min_length: windowSize,
8140
+ max_length: windowSize
8141
+ },
8142
+ confidence,
8143
+ occurrence_count: data.count,
8144
+ first_seen_at: now,
8145
+ last_seen_at: now,
8146
+ seen_in_threads: [...new Set(
8147
+ data.stitch_ids.flatMap(
8148
+ (ids) => ids.map((id) => sorted.find((s) => s.stitch_id === id)?.thread_id).filter(Boolean)
8149
+ )
8150
+ )],
8151
+ classification: "unclassified"
8152
+ });
8153
+ }
8154
+ return patterns;
8155
+ }
8156
+ function detectKnotPatterns(knots, minOccurrences) {
8157
+ const groups = /* @__PURE__ */ new Map();
8158
+ for (const knot of knots) {
8159
+ if (knot.status !== "tied") continue;
8160
+ const key = `${knot.type}:${knot.stitch_ids.length}`;
8161
+ const group = groups.get(key) ?? [];
8162
+ group.push(knot);
8163
+ groups.set(key, group);
8164
+ }
8165
+ const patterns = [];
8166
+ const now = Date.now();
8167
+ for (const [key, group] of groups) {
8168
+ if (group.length < minOccurrences) continue;
8169
+ const [type, sizeStr] = key.split(":");
8170
+ const size = parseInt(sizeStr, 10);
8171
+ const confidence = Math.min(group.length / (minOccurrences * 2), 1);
8172
+ patterns.push({
8173
+ pattern_id: `pat_knot_${randomBytes11(8).toString("hex")}`,
8174
+ kind: "knot",
8175
+ name: `Knot: ${type} (${size} stitches)`,
8176
+ signature: {
8177
+ knot_type: type,
8178
+ knot_size: size
8179
+ },
8180
+ confidence,
8181
+ occurrence_count: group.length,
8182
+ first_seen_at: now,
8183
+ last_seen_at: now,
8184
+ seen_in_threads: [...new Set(group.map((k) => k.thread_id))],
8185
+ classification: "unclassified"
8186
+ });
8187
+ }
8188
+ return patterns;
8189
+ }
8190
+ function matchPatterns(stitches, patterns) {
8191
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
8192
+ const matches = [];
8193
+ const now = Date.now();
8194
+ for (const pattern of patterns) {
8195
+ if (pattern.kind === "sequence" && pattern.signature.intent_sequence) {
8196
+ const seq = pattern.signature.intent_sequence;
8197
+ const seqLen = seq.length;
8198
+ for (let i = 0; i <= sorted.length - seqLen; i++) {
8199
+ const window = sorted.slice(i, i + seqLen);
8200
+ const windowIntents = window.map((s) => s.intent);
8201
+ if (windowIntents.every((intent, idx) => intent === seq[idx])) {
8202
+ matches.push({
8203
+ pattern_id: pattern.pattern_id,
8204
+ matched_stitch_ids: window.map((s) => s.stitch_id),
8205
+ match_score: 1,
8206
+ thread_id: window[0].thread_id,
8207
+ detected_at: now
8208
+ });
8209
+ }
8210
+ }
8211
+ }
8212
+ }
8213
+ return matches;
8214
+ }
8215
+ function recordOccurrence(pattern, threadId) {
8216
+ pattern.occurrence_count++;
8217
+ pattern.last_seen_at = Date.now();
8218
+ pattern.confidence = 1 - 1 / (1 + pattern.occurrence_count * 0.5);
8219
+ if (!pattern.seen_in_threads.includes(threadId)) {
8220
+ pattern.seen_in_threads.push(threadId);
8221
+ }
8222
+ }
8223
+ function detectAnomalies(recentStitches, knownPatterns, threshold = 0.7) {
8224
+ const anomalies = [];
8225
+ const sorted = [...recentStitches].sort((a, b) => a.sequence - b.sequence);
8226
+ const now = Date.now();
8227
+ for (const pattern of knownPatterns) {
8228
+ if (pattern.kind !== "sequence" || !pattern.signature.intent_sequence) continue;
8229
+ if (pattern.confidence < threshold) continue;
8230
+ const seq = pattern.signature.intent_sequence;
8231
+ if (sorted.length >= 1 && sorted.length < seq.length) {
8232
+ const partialMatch = sorted.every(
8233
+ (s, i) => i < seq.length && s.intent === seq[i]
8234
+ );
8235
+ if (partialMatch) {
8236
+ const expectedNext = seq[sorted.length];
8237
+ const lastStitch = sorted[sorted.length - 1];
8238
+ if (pattern.occurrence_count >= 3) {
8239
+ anomalies.push({
8240
+ pattern_id: `pat_anom_${randomBytes11(8).toString("hex")}`,
8241
+ kind: "anomaly",
8242
+ name: `Incomplete: ${pattern.name}`,
8243
+ description: `Expected '${expectedNext}' after '${lastStitch.intent}' based on pattern '${pattern.name}'`,
8244
+ signature: pattern.signature,
8245
+ confidence: pattern.confidence * 0.8,
8246
+ occurrence_count: 1,
8247
+ first_seen_at: now,
8248
+ last_seen_at: now,
8249
+ seen_in_threads: [lastStitch.thread_id],
8250
+ classification: "anomalous"
8251
+ });
8252
+ }
8253
+ }
8254
+ }
8255
+ }
8256
+ return anomalies;
8257
+ }
8258
+ var InMemoryPatternStore;
8259
+ var init_pattern_engine = __esm({
8260
+ "src/needle/pattern.engine.ts"() {
8261
+ InMemoryPatternStore = class {
8262
+ constructor() {
8263
+ this.patterns = /* @__PURE__ */ new Map();
8264
+ }
8265
+ save(pattern) {
8266
+ this.patterns.set(pattern.pattern_id, pattern);
8267
+ }
8268
+ get(patternId) {
8269
+ return this.patterns.get(patternId);
8270
+ }
8271
+ findByKind(kind) {
8272
+ return [...this.patterns.values()].filter((p) => p.kind === kind);
8273
+ }
8274
+ findByIntent(intent) {
8275
+ return [...this.patterns.values()].filter(
8276
+ (p) => p.signature.intent_sequence?.includes(intent)
8277
+ );
8278
+ }
8279
+ all() {
8280
+ return [...this.patterns.values()];
8281
+ }
8282
+ };
8283
+ }
8284
+ });
8285
+
8286
+ // src/sensors/tps.sensor.ts
8287
+ var require_tps_sensor = __commonJS({
8288
+ "src/sensors/tps.sensor.ts"(exports) {
8289
+ "use strict";
8290
+ var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
8291
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8292
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8293
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
8294
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8295
+ };
8296
+ var __metadata = exports && exports.__metadata || function(k, v) {
8297
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8298
+ };
8299
+ Object.defineProperty(exports, "__esModule", { value: true });
8300
+ exports.TpsSensor = void 0;
8301
+ var common_1 = __require("@nestjs/common");
8302
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8303
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8304
+ var TPS_EPOCH_MS = 9343548e5;
8305
+ function parseINotation(tps) {
8306
+ if (!tps.startsWith("i"))
8307
+ return null;
8308
+ const num = Number(tps.slice(1));
8309
+ if (!Number.isFinite(num))
8310
+ return null;
8311
+ return TPS_EPOCH_MS + num;
8312
+ }
8313
+ var TpsSensor2 = class TpsSensor {
8314
+ constructor(options = {}) {
8315
+ this.name = "TpsSensor";
8316
+ this.order = sensor_bands_1.BAND.POLICY + 2;
8317
+ this.maxDriftMs = options.maxDriftMs ?? 3e4;
8318
+ this.resolver = options.resolver ?? parseINotation;
8319
+ }
8320
+ supports(input) {
8321
+ const tps = input.metadata?.tps_coordinate ?? input.metadata?.tps ?? input.packet?.tps;
8322
+ return typeof tps === "string" && tps.length > 0;
8323
+ }
8324
+ async run(input) {
8325
+ const tps = input.metadata?.tps_coordinate ?? input.metadata?.tps ?? input.packet?.tps;
8326
+ const resolved = this.resolver(tps);
8327
+ if (resolved === null) {
8328
+ return {
8329
+ allow: false,
8330
+ riskScore: 80,
8331
+ reasons: [`TPS coordinate '${tps}' is structurally invalid`],
8332
+ code: "TPS_INVALID_FORMAT"
8333
+ };
8334
+ }
8335
+ const now = Date.now();
8336
+ const drift = Math.abs(now - resolved);
8337
+ if (drift > this.maxDriftMs) {
8338
+ const direction = resolved > now ? "future" : "past";
8339
+ return {
8340
+ allow: false,
8341
+ riskScore: 70,
8342
+ reasons: [
8343
+ `TPS drift ${drift}ms exceeds max ${this.maxDriftMs}ms (${direction})`
8344
+ ],
8345
+ code: "TPS_DRIFT_EXCEEDED",
8346
+ tags: { tpsDriftMs: drift, tpsDirection: direction }
8347
+ };
8348
+ }
8349
+ return {
8350
+ allow: true,
8351
+ riskScore: 0,
8352
+ reasons: [],
8353
+ tags: {
8354
+ tpsResolved: resolved,
8355
+ tpsDriftMs: drift
8356
+ }
8357
+ };
8358
+ }
8359
+ };
8360
+ exports.TpsSensor = TpsSensor2;
8361
+ exports.TpsSensor = TpsSensor2 = __decorate([
8362
+ (0, sensor_decorator_1.Sensor)(),
8363
+ (0, common_1.Injectable)(),
8364
+ __metadata("design:paramtypes", [Object])
8365
+ ], TpsSensor2);
8366
+ }
8367
+ });
8368
+
8369
+ // src/sensors/risk-gate.sensor.ts
8370
+ var require_risk_gate_sensor = __commonJS({
8371
+ "src/sensors/risk-gate.sensor.ts"(exports) {
8372
+ "use strict";
8373
+ var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
8374
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8375
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8376
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
8377
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8378
+ };
8379
+ var __metadata = exports && exports.__metadata || function(k, v) {
8380
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8381
+ };
8382
+ Object.defineProperty(exports, "__esModule", { value: true });
8383
+ exports.RiskGateSensor = void 0;
8384
+ var common_1 = __require("@nestjs/common");
8385
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8386
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8387
+ var risk_1 = (init_risk(), __toCommonJS(risk_exports));
8388
+ var SEVERITY_WEIGHT = {
8389
+ low: 10,
8390
+ medium: 25,
8391
+ high: 50,
8392
+ critical: 100
8393
+ };
8394
+ var RiskGateSensor2 = class RiskGateSensor {
8395
+ constructor(options) {
8396
+ this.name = "RiskGateSensor";
8397
+ this.order = sensor_bands_1.BAND.BUSINESS + 10;
8398
+ this.collectors = options.collectors;
8399
+ this.denyThreshold = options.denyThreshold ?? 75;
8400
+ this.flagThreshold = options.flagThreshold ?? 40;
8401
+ }
8402
+ async run(input) {
8403
+ const results = await Promise.all(this.collectors.map((c) => c(input)));
8404
+ const signals = results.flat();
8405
+ let totalWeight = 0;
8406
+ let weightedSum = 0;
8407
+ for (const signal of signals) {
8408
+ const w = SEVERITY_WEIGHT[signal.severity];
8409
+ totalWeight += 1;
8410
+ weightedSum += w;
8411
+ }
8412
+ const aggregateScore = totalWeight > 0 ? Math.min(100, Math.round(weightedSum / totalWeight)) : 0;
8413
+ const evaluation = this.evaluate(aggregateScore, signals);
8414
+ input.metadata = {
8415
+ ...input.metadata ?? {},
8416
+ riskEvaluation: evaluation
8417
+ };
8418
+ if (evaluation.decision === risk_1.RiskDecision.DENY) {
8419
+ return {
8420
+ allow: false,
8421
+ riskScore: aggregateScore,
8422
+ reasons: signals.map((s) => s.message),
8423
+ code: "RISK_GATE_DENY",
8424
+ tags: { riskDecision: evaluation.decision, signalCount: signals.length }
8425
+ };
8426
+ }
8427
+ if (evaluation.decision === risk_1.RiskDecision.THROTTLE) {
8428
+ return {
8429
+ allow: false,
8430
+ riskScore: aggregateScore,
8431
+ reasons: signals.map((s) => s.message),
8432
+ code: "RISK_GATE_THROTTLE",
8433
+ retryAfterMs: evaluation.retryAfterMs,
8434
+ tags: { riskDecision: evaluation.decision, signalCount: signals.length }
8435
+ };
8436
+ }
8437
+ return {
8438
+ allow: true,
8439
+ riskScore: aggregateScore,
8440
+ reasons: signals.filter((s) => s.severity === "medium" || s.severity === "high").map((s) => s.message),
8441
+ tags: {
8442
+ riskDecision: evaluation.decision,
8443
+ signalCount: signals.length
8444
+ }
8445
+ };
8446
+ }
8447
+ evaluate(score, signals) {
8448
+ const hasCritical = signals.some((s) => s.severity === "critical");
8449
+ if (hasCritical) {
8450
+ return {
8451
+ decision: risk_1.RiskDecision.DENY,
8452
+ reason: "Critical risk signal detected",
8453
+ confidence: 1,
8454
+ signals
8455
+ };
8456
+ }
8457
+ if (score >= this.denyThreshold) {
8458
+ return {
8459
+ decision: risk_1.RiskDecision.DENY,
8460
+ reason: `Aggregate risk score ${score} exceeds deny threshold ${this.denyThreshold}`,
8461
+ confidence: score / 100,
8462
+ signals
8463
+ };
8464
+ }
8465
+ if (score >= this.flagThreshold) {
8466
+ return {
8467
+ decision: risk_1.RiskDecision.STEP_UP,
8468
+ reason: `Aggregate risk score ${score} exceeds flag threshold ${this.flagThreshold}`,
8469
+ confidence: score / 100,
8470
+ signals
8471
+ };
8472
+ }
8473
+ return {
8474
+ decision: risk_1.RiskDecision.ALLOW,
8475
+ confidence: 1 - score / 100,
8476
+ signals
8477
+ };
8478
+ }
8479
+ };
8480
+ exports.RiskGateSensor = RiskGateSensor2;
8481
+ exports.RiskGateSensor = RiskGateSensor2 = __decorate([
8482
+ (0, sensor_decorator_1.Sensor)(),
8483
+ (0, common_1.Injectable)(),
8484
+ __metadata("design:paramtypes", [Object])
8485
+ ], RiskGateSensor2);
8486
+ }
8487
+ });
8488
+
8489
+ // src/sensors/tickauth.sensor.ts
8490
+ var require_tickauth_sensor = __commonJS({
8491
+ "src/sensors/tickauth.sensor.ts"(exports) {
8492
+ "use strict";
8493
+ var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
8494
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8495
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8496
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
8497
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8498
+ };
8499
+ var __metadata = exports && exports.__metadata || function(k, v) {
8500
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8501
+ };
8502
+ Object.defineProperty(exports, "__esModule", { value: true });
8503
+ exports.TickAuthSensor = void 0;
8504
+ var common_1 = __require("@nestjs/common");
8505
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8506
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8507
+ var TickAuthSensor2 = class TickAuthSensor {
8508
+ constructor(options = {}) {
8509
+ this.name = "TickAuthSensor";
8510
+ this.order = sensor_bands_1.BAND.IDENTITY + 40;
8511
+ this.verifier = options.verifier;
8512
+ this.matchIntent = options.matchIntent ?? true;
8513
+ this.acceptTypes = options.acceptTypes?.length ? new Set(options.acceptTypes) : null;
8514
+ }
8515
+ supports(input) {
8516
+ return !!(input.metadata?.capsule || input.metadata?.tickauthCapsule || input.metadata?.cceEnvelope?.capsule);
8517
+ }
8518
+ async run(input) {
8519
+ const capsule = input.metadata?.capsule ?? input.metadata?.tickauthCapsule ?? input.metadata?.cceEnvelope?.capsule;
8520
+ if (!capsule) {
8521
+ return {
8522
+ allow: false,
8523
+ riskScore: 90,
8524
+ reasons: ["TickAuth capsule not found"],
8525
+ code: "TICKAUTH_MISSING"
8526
+ };
8527
+ }
8528
+ if (!capsule.capsule_id || typeof capsule.capsule_id !== "string") {
8529
+ return {
8530
+ allow: false,
8531
+ riskScore: 100,
8532
+ reasons: ["TickAuth capsule has no valid capsule_id"],
8533
+ code: "TICKAUTH_INVALID_ID"
8534
+ };
8535
+ }
8536
+ const status = capsule.verification?.status;
8537
+ if (status && status !== "approved") {
8538
+ return {
8539
+ allow: false,
8540
+ riskScore: 100,
8541
+ reasons: [
8542
+ `TickAuth capsule status is '${status}'${capsule.verification?.reason ? `: ${capsule.verification.reason}` : ""}`
8543
+ ],
8544
+ code: `TICKAUTH_STATUS_${status.toUpperCase()}`
8545
+ };
8546
+ }
8547
+ if (this.acceptTypes && capsule.capsule_type) {
8548
+ if (!this.acceptTypes.has(capsule.capsule_type)) {
8549
+ return {
8550
+ allow: false,
8551
+ riskScore: 80,
8552
+ reasons: [
8553
+ `TickAuth capsule type '${capsule.capsule_type}' is not in accept list`
8554
+ ],
8555
+ code: "TICKAUTH_TYPE_REJECTED"
8556
+ };
8557
+ }
8558
+ }
8559
+ if (this.matchIntent && input.intent && capsule.intent) {
8560
+ if (capsule.intent !== input.intent) {
8561
+ return {
8562
+ allow: false,
8563
+ riskScore: 80,
8564
+ reasons: [
8565
+ `TickAuth capsule intent '${capsule.intent}' does not match AXIS intent '${input.intent}'`
8566
+ ],
8567
+ code: "TICKAUTH_INTENT_MISMATCH"
8568
+ };
8569
+ }
8570
+ }
8571
+ if (this.verifier) {
8572
+ const error = await this.verifier(capsule, input);
8573
+ if (error) {
8574
+ return {
8575
+ allow: false,
8576
+ riskScore: 90,
8577
+ reasons: [`TickAuth verification failed: ${error}`],
8578
+ code: "TICKAUTH_VERIFY_FAILED"
8579
+ };
8580
+ }
8581
+ }
8582
+ return {
8583
+ allow: true,
8584
+ riskScore: 0,
8585
+ reasons: [],
8586
+ tags: {
8587
+ tickauthCapsuleId: capsule.capsule_id,
8588
+ tickauthMode: capsule.mode,
8589
+ tickauthSingleUse: capsule.single_use
8590
+ }
8591
+ };
8592
+ }
8593
+ };
8594
+ exports.TickAuthSensor = TickAuthSensor2;
8595
+ exports.TickAuthSensor = TickAuthSensor2 = __decorate([
8596
+ (0, sensor_decorator_1.Sensor)(),
8597
+ (0, common_1.Injectable)(),
8598
+ __metadata("design:paramtypes", [Object])
8599
+ ], TickAuthSensor2);
6260
8600
  }
6261
8601
  });
6262
8602
 
@@ -7068,95 +9408,19 @@ var init_cce = __esm({
7068
9408
  // src/core/index.ts
7069
9409
  var core_exports = {};
7070
9410
  __export(core_exports, {
7071
- AXIS_MAGIC: () => AXIS_MAGIC,
7072
- AXIS_VERSION: () => AXIS_VERSION,
7073
9411
  AxisError: () => AxisError,
7074
9412
  AxisFrameZ: () => AxisFrameZ,
7075
- AxisMediaTypes: () => AxisMediaTypes,
7076
- BodyProfile: () => BodyProfile,
7077
- ERR_BAD_SIGNATURE: () => ERR_BAD_SIGNATURE,
7078
- ERR_CONTRACT_VIOLATION: () => ERR_CONTRACT_VIOLATION,
7079
- ERR_INVALID_PACKET: () => ERR_INVALID_PACKET,
7080
- ERR_REPLAY_DETECTED: () => ERR_REPLAY_DETECTED,
7081
- FLAG_BODY_TLV: () => FLAG_BODY_TLV,
7082
- FLAG_CHAIN_REQ: () => FLAG_CHAIN_REQ,
7083
- FLAG_HAS_WITNESS: () => FLAG_HAS_WITNESS,
7084
- MAX_BODY_LEN: () => MAX_BODY_LEN,
7085
- MAX_FRAME_LEN: () => MAX_FRAME_LEN,
7086
- MAX_HDR_LEN: () => MAX_HDR_LEN,
7087
- MAX_SIG_LEN: () => MAX_SIG_LEN,
7088
- NCERT_ALG: () => NCERT_ALG,
7089
- NCERT_EXP: () => NCERT_EXP,
7090
- NCERT_ISSUER_KID: () => NCERT_ISSUER_KID,
7091
- NCERT_KID: () => NCERT_KID,
7092
- NCERT_NBF: () => NCERT_NBF,
7093
- NCERT_NODE_ID: () => NCERT_NODE_ID,
7094
- NCERT_PAYLOAD: () => NCERT_PAYLOAD,
7095
- NCERT_PUB: () => NCERT_PUB,
7096
- NCERT_SCOPE: () => NCERT_SCOPE,
7097
- NCERT_SIG: () => NCERT_SIG,
7098
- PROOF_CAPSULE: () => PROOF_CAPSULE,
7099
- PROOF_JWT: () => PROOF_JWT,
7100
- PROOF_LOOM: () => PROOF_LOOM,
7101
- PROOF_MTLS: () => PROOF_MTLS,
7102
- PROOF_NONE: () => PROOF_NONE,
7103
- PROOF_WITNESS: () => PROOF_WITNESS,
7104
- ProofType: () => ProofType,
7105
- TLV: () => TLV,
7106
- TLV_ACTOR_ID: () => TLV_ACTOR_ID,
7107
- TLV_AUD: () => TLV_AUD,
7108
- TLV_BODY_ARR: () => TLV_BODY_ARR,
7109
- TLV_BODY_OBJ: () => TLV_BODY_OBJ,
7110
- TLV_CAPSULE: () => TLV_CAPSULE,
7111
- TLV_EFFECT: () => TLV_EFFECT,
7112
- TLV_ERROR_CODE: () => TLV_ERROR_CODE,
7113
- TLV_ERROR_MSG: () => TLV_ERROR_MSG,
7114
- TLV_INDEX: () => TLV_INDEX,
7115
- TLV_INTENT: () => TLV_INTENT,
7116
- TLV_KID: () => TLV_KID,
7117
- TLV_LOOM_PRESENCE_ID: () => TLV_LOOM_PRESENCE_ID,
7118
- TLV_LOOM_THREAD_HASH: () => TLV_LOOM_THREAD_HASH,
7119
- TLV_LOOM_WRIT: () => TLV_LOOM_WRIT,
7120
- TLV_NODE: () => TLV_NODE,
7121
- TLV_NODE_CERT_HASH: () => TLV_NODE_CERT_HASH,
7122
- TLV_NODE_KID: () => TLV_NODE_KID,
7123
- TLV_NONCE: () => TLV_NONCE,
7124
- TLV_OFFSET: () => TLV_OFFSET,
7125
- TLV_OK: () => TLV_OK,
7126
- TLV_PID: () => TLV_PID,
7127
- TLV_PREV_HASH: () => TLV_PREV_HASH,
7128
- TLV_PROOF_REF: () => TLV_PROOF_REF,
7129
- TLV_PROOF_TYPE: () => TLV_PROOF_TYPE,
7130
- TLV_REALM: () => TLV_REALM,
7131
- TLV_RECEIPT_HASH: () => TLV_RECEIPT_HASH,
7132
- TLV_RID: () => TLV_RID,
7133
- TLV_SHA256_CHUNK: () => TLV_SHA256_CHUNK,
7134
- TLV_TRACE_ID: () => TLV_TRACE_ID,
7135
- TLV_TS: () => TLV_TS,
7136
- TLV_UPLOAD_ID: () => TLV_UPLOAD_ID,
7137
9413
  computeReceiptHash: () => computeReceiptHash,
7138
9414
  computeSignaturePayload: () => computeSignaturePayload,
7139
- decodeArray: () => decodeArray,
7140
- decodeFrame: () => decodeFrame,
7141
- decodeObject: () => decodeObject,
7142
- decodeTLVs: () => decodeTLVs,
7143
- decodeTLVsList: () => decodeTLVsList,
7144
- decodeVarint: () => decodeVarint,
7145
- encodeFrame: () => encodeFrame,
7146
- encodeTLVs: () => encodeTLVs,
7147
- encodeVarint: () => encodeVarint,
7148
9415
  generateEd25519KeyPair: () => generateEd25519KeyPair,
7149
- getSignTarget: () => getSignTarget,
7150
9416
  sha256: () => sha2564,
7151
9417
  signFrame: () => signFrame,
7152
- varintLength: () => varintLength,
7153
9418
  verifyFrameSignature: () => verifyFrameSignature
7154
9419
  });
9420
+ import * as axis_protocol_star from "@nextera.one/axis-protocol";
7155
9421
  var init_core = __esm({
7156
9422
  "src/core/index.ts"() {
7157
- init_constants();
7158
- init_varint();
7159
- init_tlv();
9423
+ __reExport(core_exports, axis_protocol_star);
7160
9424
  init_axis_bin();
7161
9425
  init_signature();
7162
9426
  init_axis_error();
@@ -7357,8 +9621,10 @@ var init_crypto = __esm({
7357
9621
  var decorators_exports = {};
7358
9622
  __export(decorators_exports, {
7359
9623
  AXIS_ANONYMOUS_KEY: () => AXIS_ANONYMOUS_KEY,
9624
+ AXIS_META_KEY: () => AXIS_META_KEY,
7360
9625
  AXIS_PUBLIC_KEY: () => AXIS_PUBLIC_KEY,
7361
9626
  AXIS_RATE_LIMIT_KEY: () => AXIS_RATE_LIMIT_KEY,
9627
+ Axis: () => Axis,
7362
9628
  AxisAnonymous: () => AxisAnonymous,
7363
9629
  AxisPublic: () => AxisPublic,
7364
9630
  AxisRateLimit: () => AxisRateLimit,
@@ -7387,14 +9653,6 @@ __export(decorators_exports, {
7387
9653
  SENSOR_METADATA_KEY: () => SENSOR_METADATA_KEY,
7388
9654
  Sensitivity: () => Sensitivity,
7389
9655
  Sensor: () => Sensor,
7390
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
7391
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
7392
- TlvEnum: () => TlvEnum,
7393
- TlvField: () => TlvField,
7394
- TlvMinLen: () => TlvMinLen,
7395
- TlvRange: () => TlvRange,
7396
- TlvUtf8Pattern: () => TlvUtf8Pattern,
7397
- TlvValidate: () => TlvValidate,
7398
9656
  Witness: () => Witness,
7399
9657
  mergeCapsulePolicyOptions: () => mergeCapsulePolicyOptions,
7400
9658
  normalizeCapsulePolicyOptions: () => normalizeCapsulePolicyOptions
@@ -7412,7 +9670,7 @@ var init_decorators = __esm({
7412
9670
  init_intent_decorator();
7413
9671
  init_observer_decorator();
7414
9672
  init_sensor_decorator();
7415
- init_tlv_field_decorator();
9673
+ __reExport(decorators_exports, __toESM(require_tlv_field_decorator()));
7416
9674
  }
7417
9675
  });
7418
9676
 
@@ -7513,6 +9771,25 @@ var init_engine = __esm({
7513
9771
  }
7514
9772
  });
7515
9773
 
9774
+ // src/idel/idel.types.ts
9775
+ var init_idel_types = __esm({
9776
+ "src/idel/idel.types.ts"() {
9777
+ }
9778
+ });
9779
+
9780
+ // src/idel/index.ts
9781
+ var idel_exports = {};
9782
+ __export(idel_exports, {
9783
+ IdelCompiler: () => IdelCompiler,
9784
+ IdelSchemaRegistry: () => IdelSchemaRegistry
9785
+ });
9786
+ var init_idel = __esm({
9787
+ "src/idel/index.ts"() {
9788
+ init_idel_types();
9789
+ init_idel_compiler();
9790
+ }
9791
+ });
9792
+
7516
9793
  // src/loom/index.ts
7517
9794
  var loom_exports = {};
7518
9795
  __export(loom_exports, {
@@ -7522,11 +9799,98 @@ __export(loom_exports, {
7522
9799
  TLV_WRIT: () => TLV_LOOM_WRIT,
7523
9800
  canonicalizeGrant: () => canonicalizeGrant,
7524
9801
  canonicalizeWrit: () => canonicalizeWrit,
7525
- deriveAnchorReflection: () => deriveAnchorReflection
9802
+ createGrant: () => createGrant,
9803
+ createPresenceChallenge: () => createPresenceChallenge,
9804
+ createReceipt: () => createReceipt,
9805
+ createRevocation: () => createRevocation,
9806
+ createWrit: () => createWrit,
9807
+ deriveAnchorReflection: () => deriveAnchorReflection,
9808
+ executeLoomPipeline: () => executeLoomPipeline,
9809
+ getGrantStatus: () => getGrantStatus,
9810
+ getPresenceStatus: () => getPresenceStatus,
9811
+ grantCoversAction: () => grantCoversAction,
9812
+ isRevoked: () => isRevoked,
9813
+ renewPresence: () => renewPresence,
9814
+ signPresenceChallenge: () => signPresenceChallenge,
9815
+ updateThreadState: () => updateThreadState,
9816
+ validateGrant: () => validateGrant,
9817
+ validateWrit: () => validateWrit,
9818
+ verifyPresenceProof: () => verifyPresenceProof,
9819
+ verifyReceiptChain: () => verifyReceiptChain
7526
9820
  });
7527
9821
  var init_loom = __esm({
7528
9822
  "src/loom/index.ts"() {
7529
9823
  init_loom_types();
9824
+ init_loom_engine();
9825
+ }
9826
+ });
9827
+
9828
+ // src/needle/needle.types.ts
9829
+ var init_needle_types = __esm({
9830
+ "src/needle/needle.types.ts"() {
9831
+ }
9832
+ });
9833
+
9834
+ // src/needle/knot.types.ts
9835
+ var init_knot_types = __esm({
9836
+ "src/needle/knot.types.ts"() {
9837
+ }
9838
+ });
9839
+
9840
+ // src/needle/fabric.types.ts
9841
+ var init_fabric_types = __esm({
9842
+ "src/needle/fabric.types.ts"() {
9843
+ }
9844
+ });
9845
+
9846
+ // src/needle/pattern.types.ts
9847
+ var init_pattern_types = __esm({
9848
+ "src/needle/pattern.types.ts"() {
9849
+ }
9850
+ });
9851
+
9852
+ // src/needle/index.ts
9853
+ var needle_exports = {};
9854
+ __export(needle_exports, {
9855
+ InMemoryPatternStore: () => InMemoryPatternStore,
9856
+ addStitchToKnot: () => addStitchToKnot,
9857
+ applyStitch: () => applyStitch,
9858
+ assembleNeedle: () => assembleNeedle,
9859
+ breakKnot: () => breakKnot,
9860
+ createFabric: () => createFabric,
9861
+ detectAnomalies: () => detectAnomalies,
9862
+ detectKnotPatterns: () => detectKnotPatterns,
9863
+ detectSequencePatterns: () => detectSequencePatterns,
9864
+ diffFabrics: () => diffFabrics,
9865
+ findKnotsForStitch: () => findKnotsForStitch,
9866
+ forkFromKnot: () => forkFromKnot,
9867
+ formStitch: () => formStitch,
9868
+ getDecisionPoints: () => getDecisionPoints,
9869
+ getFabricValue: () => getFabricValue,
9870
+ getIrreversibleKnots: () => getIrreversibleKnots,
9871
+ isKnotOpen: () => isKnotOpen,
9872
+ isPointOfNoReturn: () => isPointOfNoReturn,
9873
+ lockCells: () => lockCells,
9874
+ matchPatterns: () => matchPatterns,
9875
+ openKnot: () => openKnot,
9876
+ projectAt: () => projectAt,
9877
+ queryFabric: () => queryFabric,
9878
+ recordOccurrence: () => recordOccurrence,
9879
+ runNeedlePipeline: () => runNeedlePipeline,
9880
+ tieKnot: () => tieKnot,
9881
+ validateKnot: () => validateKnot,
9882
+ weave: () => weave
9883
+ });
9884
+ var init_needle = __esm({
9885
+ "src/needle/index.ts"() {
9886
+ init_needle_types();
9887
+ init_needle_engine();
9888
+ init_knot_types();
9889
+ init_knot_engine();
9890
+ init_fabric_types();
9891
+ init_fabric_engine();
9892
+ init_pattern_types();
9893
+ init_pattern_engine();
7530
9894
  }
7531
9895
  });
7532
9896
 
@@ -8775,6 +11139,143 @@ var require_intent_registry_sensor = __commonJS({
8775
11139
  }
8776
11140
  });
8777
11141
 
11142
+ // src/sensors/law-evaluation.sensor.ts
11143
+ var require_law_evaluation_sensor = __commonJS({
11144
+ "src/sensors/law-evaluation.sensor.ts"(exports) {
11145
+ "use strict";
11146
+ var __decorate = exports && exports.__decorate || function(decorators, target, key, desc) {
11147
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11148
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
11149
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
11150
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
11151
+ };
11152
+ var __metadata = exports && exports.__metadata || function(k, v) {
11153
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11154
+ };
11155
+ var LawEvaluationSensor_1;
11156
+ Object.defineProperty(exports, "__esModule", { value: true });
11157
+ exports.LawEvaluationSensor = void 0;
11158
+ var common_1 = __require("@nestjs/common");
11159
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
11160
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
11161
+ var law_1 = (init_law(), __toCommonJS(law_exports));
11162
+ var LawEvaluationSensor = LawEvaluationSensor_1 = class LawEvaluationSensor {
11163
+ constructor(options = {}) {
11164
+ this.options = options;
11165
+ this.logger = new common_1.Logger(LawEvaluationSensor_1.name);
11166
+ this.name = "LawEvaluationSensor";
11167
+ this.order = sensor_bands_1.BAND.POLICY + 5;
11168
+ }
11169
+ supports(input) {
11170
+ return !!this.options.evaluator && !!input.intent;
11171
+ }
11172
+ async run(input) {
11173
+ const evaluator = this.options.evaluator;
11174
+ if (!evaluator) {
11175
+ return { action: "ALLOW" };
11176
+ }
11177
+ const context = (0, law_1.buildAxisLawEvaluationContext)(input);
11178
+ let result;
11179
+ try {
11180
+ result = await evaluator(context);
11181
+ } catch (error) {
11182
+ const message = error instanceof Error ? error.message : "Unknown law evaluation error";
11183
+ this.logger.error(`Law evaluation failed for ${input.intent}: ${message}`);
11184
+ input.metadata = {
11185
+ ...input.metadata ?? {},
11186
+ lawEvaluation: {
11187
+ decision: "deny",
11188
+ reason: "Law evaluation failed",
11189
+ explanation: message
11190
+ }
11191
+ };
11192
+ return {
11193
+ action: "DENY",
11194
+ code: "LAW_EVALUATION_ERROR",
11195
+ reason: message,
11196
+ meta: { lawDecision: "deny" }
11197
+ };
11198
+ }
11199
+ input.metadata = {
11200
+ ...input.metadata ?? {},
11201
+ lawEvaluation: {
11202
+ ...result,
11203
+ context: sanitizeLawContext(context)
11204
+ }
11205
+ };
11206
+ if (result.decision === "allow") {
11207
+ return {
11208
+ allow: true,
11209
+ riskScore: 0,
11210
+ reasons: result.reason ? [result.reason] : [],
11211
+ tags: {
11212
+ lawDecision: "allow",
11213
+ ...result.applicable ? { lawApplicableArticles: result.applicable.length } : {}
11214
+ },
11215
+ meta: result
11216
+ };
11217
+ }
11218
+ if (result.decision === "conditional") {
11219
+ const mode = this.options.conditionalDecision ?? "deny";
11220
+ const reasons = [result.reason, result.explanation].filter(Boolean);
11221
+ if (mode === "allow") {
11222
+ return {
11223
+ allow: true,
11224
+ riskScore: 0,
11225
+ reasons,
11226
+ tags: {
11227
+ lawDecision: "conditional"
11228
+ },
11229
+ meta: result
11230
+ };
11231
+ }
11232
+ if (mode === "flag") {
11233
+ return {
11234
+ action: "FLAG",
11235
+ scoreDelta: 25,
11236
+ reasons: reasons.length > 0 ? reasons : ["Execution is conditionally permitted pending additional requirements"],
11237
+ meta: result
11238
+ };
11239
+ }
11240
+ return {
11241
+ action: "DENY",
11242
+ code: "LAW_CONDITIONAL",
11243
+ reason: reasons.join(" | ") || "Execution is conditionally permitted pending additional requirements",
11244
+ meta: { lawDecision: "conditional", evaluation: result }
11245
+ };
11246
+ }
11247
+ return {
11248
+ action: "DENY",
11249
+ code: "LAW_DENIED",
11250
+ reason: [result.reason, result.explanation].filter(Boolean).join(" | ") || "Execution denied by law evaluation",
11251
+ meta: { lawDecision: "deny", evaluation: result }
11252
+ };
11253
+ }
11254
+ };
11255
+ exports.LawEvaluationSensor = LawEvaluationSensor;
11256
+ exports.LawEvaluationSensor = LawEvaluationSensor = LawEvaluationSensor_1 = __decorate([
11257
+ (0, sensor_decorator_1.Sensor)(),
11258
+ (0, common_1.Injectable)(),
11259
+ __metadata("design:paramtypes", [Object])
11260
+ ], LawEvaluationSensor);
11261
+ function sanitizeLawContext(context) {
11262
+ return {
11263
+ actorId: context.actorId,
11264
+ intent: context.intent,
11265
+ audience: context.audience,
11266
+ tps: context.tps,
11267
+ country: context.country,
11268
+ ip: context.ip,
11269
+ path: context.path,
11270
+ clientId: context.clientId,
11271
+ deviceId: context.deviceId,
11272
+ sessionId: context.sessionId,
11273
+ capsuleId: context.capsuleId
11274
+ };
11275
+ }
11276
+ }
11277
+ });
11278
+
8778
11279
  // src/sensors/proof-presence.sensor.ts
8779
11280
  var require_proof_presence_sensor = __commonJS({
8780
11281
  "src/sensors/proof-presence.sensor.ts"(exports) {
@@ -9477,16 +11978,40 @@ var init_sensors2 = __esm({
9477
11978
  __reExport(sensors_exports, __toESM(require_header_tlv_limit_sensor()));
9478
11979
  __reExport(sensors_exports, __toESM(require_intent_allowlist_sensor()));
9479
11980
  __reExport(sensors_exports, __toESM(require_intent_registry_sensor()));
11981
+ __reExport(sensors_exports, __toESM(require_law_evaluation_sensor()));
9480
11982
  __reExport(sensors_exports, __toESM(require_proof_presence_sensor()));
9481
11983
  __reExport(sensors_exports, __toESM(require_protocol_strict_sensor()));
9482
11984
  __reExport(sensors_exports, __toESM(require_receipt_policy_sensor()));
11985
+ __reExport(sensors_exports, __toESM(require_risk_gate_sensor()));
9483
11986
  __reExport(sensors_exports, __toESM(require_schema_validation_sensor()));
9484
11987
  __reExport(sensors_exports, __toESM(require_stream_scope_sensor()));
11988
+ __reExport(sensors_exports, __toESM(require_tickauth_sensor()));
9485
11989
  __reExport(sensors_exports, __toESM(require_tlv_parse_sensor()));
11990
+ __reExport(sensors_exports, __toESM(require_tps_sensor()));
9486
11991
  __reExport(sensors_exports, __toESM(require_varint_hardening_sensor()));
9487
11992
  }
9488
11993
  });
9489
11994
 
11995
+ // src/timeline/timeline.types.ts
11996
+ var init_timeline_types = __esm({
11997
+ "src/timeline/timeline.types.ts"() {
11998
+ }
11999
+ });
12000
+
12001
+ // src/timeline/index.ts
12002
+ var timeline_exports = {};
12003
+ __export(timeline_exports, {
12004
+ InMemoryTimelineStore: () => InMemoryTimelineStore,
12005
+ TimelineEngine: () => TimelineEngine
12006
+ });
12007
+ var init_timeline = __esm({
12008
+ "src/timeline/index.ts"() {
12009
+ init_timeline_types();
12010
+ init_timeline_store();
12011
+ init_timeline_engine();
12012
+ }
12013
+ });
12014
+
9490
12015
  // src/utils/index.ts
9491
12016
  var utils_exports = {};
9492
12017
  __export(utils_exports, {
@@ -9506,6 +12031,7 @@ __export(index_exports, {
9506
12031
  AXIS_ANONYMOUS_KEY: () => AXIS_ANONYMOUS_KEY,
9507
12032
  AXIS_EXECUTION_CONTEXT_KEY: () => AXIS_EXECUTION_CONTEXT_KEY,
9508
12033
  AXIS_MAGIC: () => AXIS_MAGIC,
12034
+ AXIS_META_KEY: () => AXIS_META_KEY,
9509
12035
  AXIS_OPCODES: () => AXIS_OPCODES,
9510
12036
  AXIS_PUBLIC_KEY: () => AXIS_PUBLIC_KEY,
9511
12037
  AXIS_RATE_LIMIT_KEY: () => AXIS_RATE_LIMIT_KEY,
@@ -9514,6 +12040,7 @@ __export(index_exports, {
9514
12040
  AXIS_UPLOAD_SESSION_STORE: () => AXIS_UPLOAD_SESSION_STORE,
9515
12041
  AXIS_VERSION: () => AXIS_VERSION,
9516
12042
  Ats1Codec: () => ats1_exports,
12043
+ Axis: () => Axis,
9517
12044
  AxisAnonymous: () => AxisAnonymous,
9518
12045
  AxisChainExecutor: () => import_axis_chain.AxisChainExecutor,
9519
12046
  AxisContext: () => import_axis_request.AxisContext,
@@ -9573,6 +12100,10 @@ __export(index_exports, {
9573
12100
  INTENT_SENSITIVITY_MAP: () => INTENT_SENSITIVITY_MAP,
9574
12101
  INTENT_SENSORS_KEY: () => INTENT_SENSORS_KEY,
9575
12102
  INTENT_TIMEOUTS: () => INTENT_TIMEOUTS,
12103
+ IdelCompiler: () => IdelCompiler,
12104
+ IdelSchemaRegistry: () => IdelSchemaRegistry,
12105
+ InMemoryPatternStore: () => InMemoryPatternStore,
12106
+ InMemoryTimelineStore: () => InMemoryTimelineStore,
9576
12107
  Intent: () => Intent,
9577
12108
  IntentBody: () => IntentBody,
9578
12109
  IntentRouter: () => import_intent2.IntentRouter,
@@ -9616,6 +12147,7 @@ __export(index_exports, {
9616
12147
  RequiredProof: () => RequiredProof,
9617
12148
  ResponseObserver: () => ResponseObserver,
9618
12149
  RiskDecision: () => RiskDecision,
12150
+ RiskGateSensor: () => import_risk_gate.RiskGateSensor,
9619
12151
  SENSITIVITY_METADATA_KEY: () => SENSITIVITY_METADATA_KEY,
9620
12152
  SENSOR_METADATA_KEY: () => SENSOR_METADATA_KEY,
9621
12153
  Schema2002_PasskeyLoginOptionsRes: () => Schema2002_PasskeyLoginOptionsRes,
@@ -9636,7 +12168,7 @@ __export(index_exports, {
9636
12168
  TLV_EFFECT: () => TLV_EFFECT,
9637
12169
  TLV_ERROR_CODE: () => TLV_ERROR_CODE,
9638
12170
  TLV_ERROR_MSG: () => TLV_ERROR_MSG,
9639
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
12171
+ TLV_FIELDS_KEY: () => import_tlv_field2.TLV_FIELDS_KEY,
9640
12172
  TLV_INDEX: () => TLV_INDEX,
9641
12173
  TLV_INTENT: () => TLV_INTENT,
9642
12174
  TLV_KID: () => TLV_KID,
@@ -9662,21 +12194,29 @@ __export(index_exports, {
9662
12194
  TLV_TRACE_ID: () => TLV_TRACE_ID,
9663
12195
  TLV_TS: () => TLV_TS,
9664
12196
  TLV_UPLOAD_ID: () => TLV_UPLOAD_ID,
9665
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
12197
+ TLV_VALIDATORS_KEY: () => import_tlv_field2.TLV_VALIDATORS_KEY,
9666
12198
  TLV_WRIT: () => TLV_LOOM_WRIT,
9667
- TlvEnum: () => TlvEnum,
9668
- TlvField: () => TlvField,
9669
- TlvMinLen: () => TlvMinLen,
9670
- TlvRange: () => TlvRange,
9671
- TlvUtf8Pattern: () => TlvUtf8Pattern,
9672
- TlvValidate: () => TlvValidate,
12199
+ TickAuthSensor: () => import_tickauth.TickAuthSensor,
12200
+ TimelineEngine: () => TimelineEngine,
12201
+ TlvEnum: () => import_tlv_field2.TlvEnum,
12202
+ TlvField: () => import_tlv_field2.TlvField,
12203
+ TlvMinLen: () => import_tlv_field2.TlvMinLen,
12204
+ TlvRange: () => import_tlv_field2.TlvRange,
12205
+ TlvUtf8Pattern: () => import_tlv_field2.TlvUtf8Pattern,
12206
+ TlvValidate: () => import_tlv_field2.TlvValidate,
12207
+ TpsSensor: () => import_tps.TpsSensor,
9673
12208
  Witness: () => Witness,
12209
+ addStitchToKnot: () => addStitchToKnot,
12210
+ applyStitch: () => applyStitch,
12211
+ assembleNeedle: () => assembleNeedle,
9674
12212
  axis1SigningBytes: () => axis1SigningBytes,
9675
12213
  b64urlDecode: () => b64urlDecode,
9676
12214
  b64urlDecodeString: () => b64urlDecodeString,
9677
12215
  b64urlEncode: () => b64urlEncode,
9678
12216
  b64urlEncodeString: () => b64urlEncodeString,
12217
+ breakKnot: () => breakKnot,
9679
12218
  buildAts1Hdr: () => buildAts1Hdr,
12219
+ buildAxisLawEvaluationContext: () => buildAxisLawEvaluationContext,
9680
12220
  buildDtoDecoder: () => import_dto_schema.buildDtoDecoder,
9681
12221
  buildPacket: () => buildPacket,
9682
12222
  buildQueueMessage: () => buildQueueMessage,
@@ -9695,7 +12235,13 @@ __export(index_exports, {
9695
12235
  computeReceiptHash: () => computeReceiptHash,
9696
12236
  computeSignaturePayload: () => computeSignaturePayload,
9697
12237
  core: () => core_exports,
12238
+ createFabric: () => createFabric,
12239
+ createGrant: () => createGrant,
9698
12240
  createObservation: () => createObservation,
12241
+ createPresenceChallenge: () => createPresenceChallenge,
12242
+ createReceipt: () => createReceipt,
12243
+ createRevocation: () => createRevocation,
12244
+ createWrit: () => createWrit,
9699
12245
  crypto: () => crypto_exports,
9700
12246
  decodeArray: () => decodeArray,
9701
12247
  decodeAxis1Frame: () => decodeAxis1Frame,
@@ -9707,6 +12253,10 @@ __export(index_exports, {
9707
12253
  decodeVarint: () => decodeVarint,
9708
12254
  decorators: () => decorators_exports,
9709
12255
  deriveAnchorReflection: () => deriveAnchorReflection,
12256
+ detectAnomalies: () => detectAnomalies,
12257
+ detectKnotPatterns: () => detectKnotPatterns,
12258
+ detectSequencePatterns: () => detectSequencePatterns,
12259
+ diffFabrics: () => diffFabrics,
9710
12260
  encVarint: () => encVarint,
9711
12261
  encodeAxis1Frame: () => encodeAxis1Frame,
9712
12262
  encodeAxisTlvDto: () => encodeAxisTlvDto,
@@ -9717,20 +12267,38 @@ __export(index_exports, {
9717
12267
  endStage: () => endStage,
9718
12268
  engine: () => engine_exports,
9719
12269
  executeCcePipeline: () => executeCcePipeline,
12270
+ executeLoomPipeline: () => executeLoomPipeline,
9720
12271
  extractDtoSchema: () => import_dto_schema.extractDtoSchema,
9721
12272
  finalizeObservation: () => finalizeObservation,
12273
+ findKnotsForStitch: () => findKnotsForStitch,
12274
+ forkFromKnot: () => forkFromKnot,
12275
+ formStitch: () => formStitch,
9722
12276
  generateEd25519KeyPair: () => generateEd25519KeyPair,
9723
12277
  getAxisExecutionContext: () => getAxisExecutionContext,
12278
+ getDecisionPoints: () => getDecisionPoints,
12279
+ getFabricValue: () => getFabricValue,
12280
+ getGrantStatus: () => getGrantStatus,
12281
+ getIrreversibleKnots: () => getIrreversibleKnots,
12282
+ getPresenceStatus: () => getPresenceStatus,
9724
12283
  getSignTarget: () => getSignTarget,
12284
+ grantCoversAction: () => grantCoversAction,
9725
12285
  hasScope: () => hasScope,
9726
12286
  hashObservation: () => hashObservation,
12287
+ idel: () => idel_exports,
9727
12288
  isAdminOpcode: () => isAdminOpcode,
12289
+ isKnotOpen: () => isKnotOpen,
9728
12290
  isKnownOpcode: () => isKnownOpcode,
12291
+ isPointOfNoReturn: () => isPointOfNoReturn,
12292
+ isRevoked: () => isRevoked,
9729
12293
  isTimestampValid: () => isTimestampValid,
12294
+ lockCells: () => lockCells,
9730
12295
  loom: () => loom_exports,
12296
+ matchPatterns: () => matchPatterns,
9731
12297
  mergeAxisExecutionContext: () => mergeAxisExecutionContext,
12298
+ needle: () => needle_exports,
9732
12299
  nonce16: () => nonce16,
9733
12300
  normalizeSensorDecision: () => normalizeSensorDecision,
12301
+ openKnot: () => openKnot,
9734
12302
  packPasskeyLoginOptionsReq: () => packPasskeyLoginOptionsReq,
9735
12303
  packPasskeyLoginOptionsRes: () => packPasskeyLoginOptionsRes,
9736
12304
  packPasskeyLoginVerifyReq: () => packPasskeyLoginVerifyReq,
@@ -9739,31 +12307,48 @@ __export(index_exports, {
9739
12307
  parseAutoClaimEntries: () => parseAutoClaimEntries,
9740
12308
  parseScope: () => parseScope,
9741
12309
  parseStreamEntries: () => parseStreamEntries,
12310
+ projectAt: () => projectAt,
12311
+ queryFabric: () => queryFabric,
12312
+ recordOccurrence: () => recordOccurrence,
9742
12313
  recordSensor: () => recordSensor,
12314
+ renewPresence: () => renewPresence,
9743
12315
  resolveTimeout: () => resolveTimeout,
12316
+ runNeedlePipeline: () => runNeedlePipeline,
9744
12317
  schemas: () => schemas_exports,
12318
+ scoreTruth: () => scoreTruth,
9745
12319
  security: () => security_exports,
9746
12320
  sensitivityName: () => sensitivityName,
9747
12321
  sensors: () => sensors_exports,
9748
12322
  sha256: () => sha2564,
9749
12323
  signFrame: () => signFrame,
12324
+ signPresenceChallenge: () => signPresenceChallenge,
9750
12325
  stableJsonStringify: () => stableJsonStringify,
9751
12326
  startStage: () => startStage,
12327
+ tieKnot: () => tieKnot,
12328
+ timeline: () => timeline_exports,
9752
12329
  tlv: () => tlv,
9753
12330
  u64be: () => u64be,
9754
12331
  unpackPasskeyLoginOptionsReq: () => unpackPasskeyLoginOptionsReq,
9755
12332
  unpackPasskeyLoginVerifyReq: () => unpackPasskeyLoginVerifyReq,
9756
12333
  unpackPasskeyRegisterOptionsReq: () => unpackPasskeyRegisterOptionsReq,
12334
+ updateThreadState: () => updateThreadState,
9757
12335
  utf8: () => utf8,
9758
12336
  utils: () => utils_exports,
9759
12337
  validateFrameShape: () => validateFrameShape,
12338
+ validateGrant: () => validateGrant,
12339
+ validateKnot: () => validateKnot,
12340
+ validateWrit: () => validateWrit,
9760
12341
  varintLength: () => varintLength,
9761
12342
  varintU: () => varintU,
9762
12343
  verifyFrameSignature: () => verifyFrameSignature,
12344
+ verifyObservation: () => verifyObservation,
12345
+ verifyPresenceProof: () => verifyPresenceProof,
12346
+ verifyReceiptChain: () => verifyReceiptChain,
9763
12347
  verifyResponse: () => verifyResponse,
12348
+ weave: () => weave,
9764
12349
  withAxisExecutionContext: () => withAxisExecutionContext
9765
12350
  });
9766
- var import_dto_schema, import_axis_id, import_axis_response, import_axis_chain, import_intent2, import_axis_files, import_axis_request, import_observer_discovery, import_observer_dispatcher, import_handler_discovery, import_sensor_discovery, import_observer2, import_sensor2, import_axis_sensor_chain;
12351
+ var import_tlv_field2, import_dto_schema, import_axis_id, import_axis_response, import_axis_chain, import_intent2, import_axis_files, import_axis_request, import_observer_discovery, import_observer_dispatcher, import_handler_discovery, import_sensor_discovery, import_observer2, import_sensor2, import_axis_sensor_chain, import_tps, import_risk_gate, import_tickauth;
9767
12352
  var init_index = __esm({
9768
12353
  "src/index.ts"() {
9769
12354
  init_chain_decorator();
@@ -9776,7 +12361,7 @@ var init_index = __esm({
9776
12361
  init_observer_decorator();
9777
12362
  init_handler_sensors_decorator();
9778
12363
  init_sensor_decorator();
9779
- init_tlv_field_decorator();
12364
+ import_tlv_field2 = __toESM(require_tlv_field_decorator());
9780
12365
  import_dto_schema = __toESM(require_dto_schema_util());
9781
12366
  init_axis_tlv_dto();
9782
12367
  import_axis_id = __toESM(require_axis_id_dto());
@@ -9789,6 +12374,7 @@ var init_index = __esm({
9789
12374
  init_stable_json();
9790
12375
  init_observation_queue_codec();
9791
12376
  init_observation_hash();
12377
+ init_truth_scoring();
9792
12378
  init_response_observer();
9793
12379
  init_constants();
9794
12380
  init_varint();
@@ -9810,6 +12396,7 @@ var init_index = __esm({
9810
12396
  init_axis_sensor();
9811
12397
  init_scopes();
9812
12398
  init_capabilities();
12399
+ init_law();
9813
12400
  init_risk();
9814
12401
  init_opcodes();
9815
12402
  init_receipt();
@@ -9829,19 +12416,33 @@ var init_index = __esm({
9829
12416
  import_sensor2 = __toESM(require_sensor_registry());
9830
12417
  init_axis_observation();
9831
12418
  import_axis_sensor_chain = __toESM(require_axis_sensor_chain_service());
12419
+ init_timeline_engine();
12420
+ init_timeline_store();
9832
12421
  init_cce_pipeline();
9833
12422
  init_cce_types();
9834
12423
  init_axis_tlv_codec();
9835
12424
  init_loom_types();
12425
+ init_loom_engine();
12426
+ init_idel_compiler();
12427
+ init_needle_engine();
12428
+ init_knot_engine();
12429
+ init_fabric_engine();
12430
+ init_pattern_engine();
12431
+ import_tps = __toESM(require_tps_sensor());
12432
+ import_risk_gate = __toESM(require_risk_gate_sensor());
12433
+ import_tickauth = __toESM(require_tickauth_sensor());
9836
12434
  init_cce();
9837
12435
  init_core();
9838
12436
  init_crypto();
9839
12437
  init_decorators();
9840
12438
  init_engine();
12439
+ init_idel();
9841
12440
  init_loom();
12441
+ init_needle();
9842
12442
  init_schemas();
9843
12443
  init_security();
9844
12444
  init_sensors2();
12445
+ init_timeline();
9845
12446
  init_utils();
9846
12447
  }
9847
12448
  });
@@ -9867,8 +12468,19 @@ var export_RESPONSE_TAG_CREATED_BY = import_axis_response.RESPONSE_TAG_CREATED_B
9867
12468
  var export_RESPONSE_TAG_ID = import_axis_response.RESPONSE_TAG_ID;
9868
12469
  var export_RESPONSE_TAG_UPDATED_AT = import_axis_response.RESPONSE_TAG_UPDATED_AT;
9869
12470
  var export_RESPONSE_TAG_UPDATED_BY = import_axis_response.RESPONSE_TAG_UPDATED_BY;
12471
+ var export_RiskGateSensor = import_risk_gate.RiskGateSensor;
9870
12472
  var export_SensorDiscoveryService = import_sensor_discovery.SensorDiscoveryService;
9871
12473
  var export_SensorRegistry = import_sensor2.SensorRegistry;
12474
+ var export_TLV_FIELDS_KEY = import_tlv_field2.TLV_FIELDS_KEY;
12475
+ var export_TLV_VALIDATORS_KEY = import_tlv_field2.TLV_VALIDATORS_KEY;
12476
+ var export_TickAuthSensor = import_tickauth.TickAuthSensor;
12477
+ var export_TlvEnum = import_tlv_field2.TlvEnum;
12478
+ var export_TlvField = import_tlv_field2.TlvField;
12479
+ var export_TlvMinLen = import_tlv_field2.TlvMinLen;
12480
+ var export_TlvRange = import_tlv_field2.TlvRange;
12481
+ var export_TlvUtf8Pattern = import_tlv_field2.TlvUtf8Pattern;
12482
+ var export_TlvValidate = import_tlv_field2.TlvValidate;
12483
+ var export_TpsSensor = import_tps.TpsSensor;
9872
12484
  var export_buildDtoDecoder = import_dto_schema.buildDtoDecoder;
9873
12485
  var export_extractDtoSchema = import_dto_schema.extractDtoSchema;
9874
12486
  export {
@@ -9877,6 +12489,7 @@ export {
9877
12489
  AXIS_ANONYMOUS_KEY,
9878
12490
  AXIS_EXECUTION_CONTEXT_KEY,
9879
12491
  AXIS_MAGIC,
12492
+ AXIS_META_KEY,
9880
12493
  AXIS_OPCODES,
9881
12494
  AXIS_PUBLIC_KEY,
9882
12495
  AXIS_RATE_LIMIT_KEY,
@@ -9885,6 +12498,7 @@ export {
9885
12498
  AXIS_UPLOAD_SESSION_STORE,
9886
12499
  AXIS_VERSION,
9887
12500
  ats1_exports as Ats1Codec,
12501
+ Axis,
9888
12502
  AxisAnonymous,
9889
12503
  export_AxisChainExecutor as AxisChainExecutor,
9890
12504
  export_AxisContext as AxisContext,
@@ -9944,6 +12558,10 @@ export {
9944
12558
  INTENT_SENSITIVITY_MAP,
9945
12559
  INTENT_SENSORS_KEY,
9946
12560
  INTENT_TIMEOUTS,
12561
+ IdelCompiler,
12562
+ IdelSchemaRegistry,
12563
+ InMemoryPatternStore,
12564
+ InMemoryTimelineStore,
9947
12565
  Intent,
9948
12566
  IntentBody,
9949
12567
  export_IntentRouter as IntentRouter,
@@ -9987,6 +12605,7 @@ export {
9987
12605
  RequiredProof,
9988
12606
  ResponseObserver,
9989
12607
  RiskDecision,
12608
+ export_RiskGateSensor as RiskGateSensor,
9990
12609
  SENSITIVITY_METADATA_KEY,
9991
12610
  SENSOR_METADATA_KEY,
9992
12611
  Schema2002_PasskeyLoginOptionsRes,
@@ -10007,7 +12626,7 @@ export {
10007
12626
  TLV_EFFECT,
10008
12627
  TLV_ERROR_CODE,
10009
12628
  TLV_ERROR_MSG,
10010
- TLV_FIELDS_KEY,
12629
+ export_TLV_FIELDS_KEY as TLV_FIELDS_KEY,
10011
12630
  TLV_INDEX,
10012
12631
  TLV_INTENT,
10013
12632
  TLV_KID,
@@ -10033,21 +12652,29 @@ export {
10033
12652
  TLV_TRACE_ID,
10034
12653
  TLV_TS,
10035
12654
  TLV_UPLOAD_ID,
10036
- TLV_VALIDATORS_KEY,
12655
+ export_TLV_VALIDATORS_KEY as TLV_VALIDATORS_KEY,
10037
12656
  TLV_LOOM_WRIT as TLV_WRIT,
10038
- TlvEnum,
10039
- TlvField,
10040
- TlvMinLen,
10041
- TlvRange,
10042
- TlvUtf8Pattern,
10043
- TlvValidate,
12657
+ export_TickAuthSensor as TickAuthSensor,
12658
+ TimelineEngine,
12659
+ export_TlvEnum as TlvEnum,
12660
+ export_TlvField as TlvField,
12661
+ export_TlvMinLen as TlvMinLen,
12662
+ export_TlvRange as TlvRange,
12663
+ export_TlvUtf8Pattern as TlvUtf8Pattern,
12664
+ export_TlvValidate as TlvValidate,
12665
+ export_TpsSensor as TpsSensor,
10044
12666
  Witness,
12667
+ addStitchToKnot,
12668
+ applyStitch,
12669
+ assembleNeedle,
10045
12670
  axis1SigningBytes,
10046
12671
  b64urlDecode,
10047
12672
  b64urlDecodeString,
10048
12673
  b64urlEncode,
10049
12674
  b64urlEncodeString,
12675
+ breakKnot,
10050
12676
  buildAts1Hdr,
12677
+ buildAxisLawEvaluationContext,
10051
12678
  export_buildDtoDecoder as buildDtoDecoder,
10052
12679
  buildPacket,
10053
12680
  buildQueueMessage,
@@ -10066,7 +12693,13 @@ export {
10066
12693
  computeReceiptHash,
10067
12694
  computeSignaturePayload,
10068
12695
  core_exports as core,
12696
+ createFabric,
12697
+ createGrant,
10069
12698
  createObservation,
12699
+ createPresenceChallenge,
12700
+ createReceipt,
12701
+ createRevocation,
12702
+ createWrit,
10070
12703
  crypto_exports as crypto,
10071
12704
  decodeArray,
10072
12705
  decodeAxis1Frame,
@@ -10078,6 +12711,10 @@ export {
10078
12711
  decodeVarint,
10079
12712
  decorators_exports as decorators,
10080
12713
  deriveAnchorReflection,
12714
+ detectAnomalies,
12715
+ detectKnotPatterns,
12716
+ detectSequencePatterns,
12717
+ diffFabrics,
10081
12718
  encVarint,
10082
12719
  encodeAxis1Frame,
10083
12720
  encodeAxisTlvDto,
@@ -10088,20 +12725,38 @@ export {
10088
12725
  endStage,
10089
12726
  engine_exports as engine,
10090
12727
  executeCcePipeline,
12728
+ executeLoomPipeline,
10091
12729
  export_extractDtoSchema as extractDtoSchema,
10092
12730
  finalizeObservation,
12731
+ findKnotsForStitch,
12732
+ forkFromKnot,
12733
+ formStitch,
10093
12734
  generateEd25519KeyPair,
10094
12735
  getAxisExecutionContext,
12736
+ getDecisionPoints,
12737
+ getFabricValue,
12738
+ getGrantStatus,
12739
+ getIrreversibleKnots,
12740
+ getPresenceStatus,
10095
12741
  getSignTarget,
12742
+ grantCoversAction,
10096
12743
  hasScope,
10097
12744
  hashObservation,
12745
+ idel_exports as idel,
10098
12746
  isAdminOpcode,
12747
+ isKnotOpen,
10099
12748
  isKnownOpcode,
12749
+ isPointOfNoReturn,
12750
+ isRevoked,
10100
12751
  isTimestampValid,
12752
+ lockCells,
10101
12753
  loom_exports as loom,
12754
+ matchPatterns,
10102
12755
  mergeAxisExecutionContext,
12756
+ needle_exports as needle,
10103
12757
  nonce16,
10104
12758
  normalizeSensorDecision,
12759
+ openKnot,
10105
12760
  packPasskeyLoginOptionsReq,
10106
12761
  packPasskeyLoginOptionsRes,
10107
12762
  packPasskeyLoginVerifyReq,
@@ -10110,28 +12765,45 @@ export {
10110
12765
  parseAutoClaimEntries,
10111
12766
  parseScope,
10112
12767
  parseStreamEntries,
12768
+ projectAt,
12769
+ queryFabric,
12770
+ recordOccurrence,
10113
12771
  recordSensor,
12772
+ renewPresence,
10114
12773
  resolveTimeout,
12774
+ runNeedlePipeline,
10115
12775
  schemas_exports as schemas,
12776
+ scoreTruth,
10116
12777
  security_exports as security,
10117
12778
  sensitivityName,
10118
12779
  sensors_exports as sensors,
10119
12780
  sha2564 as sha256,
10120
12781
  signFrame,
12782
+ signPresenceChallenge,
10121
12783
  stableJsonStringify,
10122
12784
  startStage,
12785
+ tieKnot,
12786
+ timeline_exports as timeline,
10123
12787
  tlv,
10124
12788
  u64be,
10125
12789
  unpackPasskeyLoginOptionsReq,
10126
12790
  unpackPasskeyLoginVerifyReq,
10127
12791
  unpackPasskeyRegisterOptionsReq,
12792
+ updateThreadState,
10128
12793
  utf8,
10129
12794
  utils_exports as utils,
10130
12795
  validateFrameShape,
12796
+ validateGrant,
12797
+ validateKnot,
12798
+ validateWrit,
10131
12799
  varintLength,
10132
12800
  varintU,
10133
12801
  verifyFrameSignature,
12802
+ verifyObservation,
12803
+ verifyPresenceProof,
12804
+ verifyReceiptChain,
10134
12805
  verifyResponse,
12806
+ weave,
10135
12807
  withAxisExecutionContext
10136
12808
  };
10137
12809
  //# sourceMappingURL=index.mjs.map