@nextera.one/axis-server-sdk 2.1.6 → 2.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -327,12 +327,16 @@ __export(intent_decorator_exports, {
327
327
  });
328
328
  function Intent(action, options) {
329
329
  return (target, propertyKey) => {
330
- Reflect.defineMetadata(
331
- INTENT_METADATA_KEY,
332
- { intent: action, ...options },
333
- target,
334
- propertyKey
335
- );
330
+ const metadata = { intent: action, ...options };
331
+ Reflect.defineMetadata(INTENT_METADATA_KEY, metadata, target, propertyKey);
332
+ if (options?.sensitivity) {
333
+ Reflect.defineMetadata(
334
+ SENSITIVITY_METADATA_KEY,
335
+ options.sensitivity,
336
+ target,
337
+ propertyKey
338
+ );
339
+ }
336
340
  const routes = Reflect.getMetadata(INTENT_ROUTES_KEY, target.constructor) || [];
337
341
  routes.push({
338
342
  action,
@@ -340,10 +344,12 @@ function Intent(action, options) {
340
344
  absolute: options?.absolute,
341
345
  frame: options?.frame,
342
346
  kind: options?.kind,
347
+ sensitivity: options?.sensitivity,
343
348
  chain: options?.chain,
344
349
  bodyProfile: options?.bodyProfile,
345
350
  tlv: options?.tlv,
346
- dto: options?.dto
351
+ dto: options?.dto,
352
+ is: options?.is
347
353
  });
348
354
  Reflect.defineMetadata(INTENT_ROUTES_KEY, routes, target.constructor);
349
355
  };
@@ -352,6 +358,7 @@ var import_reflect_metadata4, INTENT_METADATA_KEY, INTENT_ROUTES_KEY;
352
358
  var init_intent_decorator = __esm({
353
359
  "src/decorators/intent.decorator.ts"() {
354
360
  import_reflect_metadata4 = require("reflect-metadata");
361
+ init_intent_policy_decorator();
355
362
  INTENT_METADATA_KEY = "axis:intent";
356
363
  INTENT_ROUTES_KEY = "axis:intent_routes";
357
364
  }
@@ -499,76 +506,90 @@ var init_sensor_decorator = __esm({
499
506
  });
500
507
 
501
508
  // src/decorators/tlv-field.decorator.ts
502
- var tlv_field_decorator_exports = {};
503
- __export(tlv_field_decorator_exports, {
504
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
505
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
506
- TlvEnum: () => TlvEnum,
507
- TlvField: () => TlvField,
508
- TlvMinLen: () => TlvMinLen,
509
- TlvRange: () => TlvRange,
510
- TlvUtf8Pattern: () => TlvUtf8Pattern,
511
- TlvValidate: () => TlvValidate
512
- });
513
- function TlvField(tag, options) {
514
- return (target, propertyKey) => {
515
- const existing = Reflect.getOwnMetadata(TLV_FIELDS_KEY, target.constructor) || [];
516
- existing.push({
517
- property: String(propertyKey),
518
- tag,
519
- options
520
- });
521
- Reflect.defineMetadata(TLV_FIELDS_KEY, existing, target.constructor);
522
- };
523
- }
524
- function TlvValidate(validator) {
525
- return (target, propertyKey) => {
526
- const existing = Reflect.getOwnMetadata(TLV_VALIDATORS_KEY, target.constructor) || [];
527
- const prop = String(propertyKey);
528
- let entry = existing.find((e) => e.property === prop);
529
- if (!entry) {
530
- entry = { property: prop, tag: 0, validators: [] };
531
- existing.push(entry);
509
+ var require_tlv_field_decorator = __commonJS({
510
+ "src/decorators/tlv-field.decorator.ts"(exports2) {
511
+ "use strict";
512
+ Object.defineProperty(exports2, "__esModule", { value: true });
513
+ exports2.TLV_VALIDATORS_KEY = exports2.TLV_FIELDS_KEY = void 0;
514
+ exports2.TlvField = TlvField2;
515
+ exports2.TlvValidate = TlvValidate2;
516
+ exports2.TlvUtf8Pattern = TlvUtf8Pattern2;
517
+ exports2.TlvMinLen = TlvMinLen2;
518
+ exports2.TlvEnum = TlvEnum2;
519
+ exports2.TlvRange = TlvRange2;
520
+ require("reflect-metadata");
521
+ exports2.TLV_FIELDS_KEY = "axis:tlv:fields";
522
+ exports2.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
+ }
532
533
  }
533
- entry.validators.push(validator);
534
- Reflect.defineMetadata(TLV_VALIDATORS_KEY, existing, target.constructor);
535
- };
536
- }
537
- function TlvUtf8Pattern(pattern, message) {
538
- return TlvValidate((val, prop) => {
539
- const str = new TextDecoder().decode(val);
540
- return pattern.test(str) ? null : message || `${prop}: failed pattern check`;
541
- });
542
- }
543
- function TlvMinLen(min, message) {
544
- return TlvValidate((val, prop) => {
545
- return val.length >= min ? null : message || `${prop}: too short (${val.length} < ${min})`;
546
- });
547
- }
548
- function TlvEnum(allowed, message) {
549
- const set = new Set(allowed);
550
- return TlvValidate((val, prop) => {
551
- const str = new TextDecoder().decode(val);
552
- return set.has(str) ? null : message || `${prop}: must be one of [${allowed.join(", ")}]`;
553
- });
554
- }
555
- function TlvRange(min, max, message) {
556
- return TlvValidate((val, prop) => {
557
- if (val.length !== 8) return `${prop}: u64 must be 8 bytes`;
558
- let n = 0n;
559
- for (const b of val) n = n << 8n | BigInt(b);
560
- if (n < min || n > max) {
561
- return message || `${prop}: value ${n} out of range [${min}, ${max}]`;
534
+ function TlvField2(tag, options) {
535
+ return (target, propertyKey) => {
536
+ const existing = Reflect.getOwnMetadata(exports2.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(exports2.TLV_FIELDS_KEY, existing, target.constructor);
545
+ };
546
+ }
547
+ function TlvValidate2(validator) {
548
+ return (target, propertyKey) => {
549
+ const existing = Reflect.getOwnMetadata(exports2.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(exports2.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
+ });
562
592
  }
563
- return null;
564
- });
565
- }
566
- var import_reflect_metadata9, TLV_FIELDS_KEY, TLV_VALIDATORS_KEY;
567
- var init_tlv_field_decorator = __esm({
568
- "src/decorators/tlv-field.decorator.ts"() {
569
- import_reflect_metadata9 = require("reflect-metadata");
570
- TLV_FIELDS_KEY = "axis:tlv:fields";
571
- TLV_VALIDATORS_KEY = "axis:tlv:validators";
572
593
  }
573
594
  });
574
595
 
@@ -597,7 +618,7 @@ var require_dto_schema_util = __commonJS({
597
618
  exports2.extractDtoSchema = extractDtoSchema2;
598
619
  exports2.buildDtoDecoder = buildDtoDecoder2;
599
620
  require("reflect-metadata");
600
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
621
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
601
622
  var tlv_1 = (init_tlv(), __toCommonJS(tlv_exports));
602
623
  function extractDtoSchema2(dto) {
603
624
  const fieldMetas = Reflect.getMetadata(tlv_field_decorator_1.TLV_FIELDS_KEY, dto) || [];
@@ -706,7 +727,7 @@ var require_axis_id_dto = __commonJS({
706
727
  };
707
728
  Object.defineProperty(exports2, "__esModule", { value: true });
708
729
  exports2.AxisIdDto = void 0;
709
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
730
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
710
731
  var axis_tlv_dto_1 = (init_axis_tlv_dto(), __toCommonJS(axis_tlv_dto_exports));
711
732
  var AxisIdDto2 = class extends axis_tlv_dto_1.AxisTlvDto {
712
733
  };
@@ -723,27 +744,27 @@ var require_axis_id_dto = __commonJS({
723
744
  function AxisPartialType(BaseDto) {
724
745
  class PartialDto extends BaseDto {
725
746
  }
726
- const fields = Reflect.getOwnMetadata(TLV_FIELDS_KEY, BaseDto) || [];
747
+ const fields = Reflect.getOwnMetadata(import_tlv_field.TLV_FIELDS_KEY, BaseDto) || [];
727
748
  const partialFields = fields.map((f) => ({
728
749
  property: f.property,
729
750
  tag: f.tag,
730
751
  options: { ...f.options, required: false }
731
752
  }));
732
- Reflect.defineMetadata(TLV_FIELDS_KEY, partialFields, PartialDto);
733
- const validators = Reflect.getOwnMetadata(TLV_VALIDATORS_KEY, BaseDto) || [];
753
+ Reflect.defineMetadata(import_tlv_field.TLV_FIELDS_KEY, partialFields, PartialDto);
754
+ const validators = Reflect.getOwnMetadata(import_tlv_field.TLV_VALIDATORS_KEY, BaseDto) || [];
734
755
  if (validators.length > 0) {
735
- Reflect.defineMetadata(TLV_VALIDATORS_KEY, [...validators], PartialDto);
756
+ Reflect.defineMetadata(import_tlv_field.TLV_VALIDATORS_KEY, [...validators], PartialDto);
736
757
  }
737
758
  Object.defineProperty(PartialDto, "name", {
738
759
  value: `Partial${BaseDto.name}`
739
760
  });
740
761
  return PartialDto;
741
762
  }
742
- var import_reflect_metadata10;
763
+ var import_reflect_metadata9, import_tlv_field;
743
764
  var init_axis_partial_type = __esm({
744
765
  "src/base/axis-partial-type.ts"() {
745
- import_reflect_metadata10 = require("reflect-metadata");
746
- init_tlv_field_decorator();
766
+ import_reflect_metadata9 = require("reflect-metadata");
767
+ import_tlv_field = __toESM(require_tlv_field_decorator());
747
768
  }
748
769
  });
749
770
 
@@ -762,7 +783,7 @@ var require_axis_response_dto = __commonJS({
762
783
  };
763
784
  Object.defineProperty(exports2, "__esModule", { value: true });
764
785
  exports2.AxisResponseDto = exports2.RESPONSE_TAG_UPDATED_BY = exports2.RESPONSE_TAG_CREATED_BY = exports2.RESPONSE_TAG_UPDATED_AT = exports2.RESPONSE_TAG_CREATED_AT = exports2.RESPONSE_TAG_ID = void 0;
765
- var tlv_field_decorator_1 = (init_tlv_field_decorator(), __toCommonJS(tlv_field_decorator_exports));
786
+ var tlv_field_decorator_1 = require_tlv_field_decorator();
766
787
  var axis_tlv_dto_1 = (init_axis_tlv_dto(), __toCommonJS(axis_tlv_dto_exports));
767
788
  exports2.RESPONSE_TAG_ID = 1;
768
789
  exports2.RESPONSE_TAG_CREATED_AT = 2;
@@ -2067,6 +2088,121 @@ var init_inline_capsule = __esm({
2067
2088
  }
2068
2089
  });
2069
2090
 
2091
+ // src/engine/registry/sensor.registry.ts
2092
+ var require_sensor_registry = __commonJS({
2093
+ "src/engine/registry/sensor.registry.ts"(exports2) {
2094
+ "use strict";
2095
+ var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
2096
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2097
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2098
+ 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;
2099
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2100
+ };
2101
+ var __metadata = exports2 && exports2.__metadata || function(k, v) {
2102
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2103
+ };
2104
+ var SensorRegistry_1;
2105
+ var _a;
2106
+ Object.defineProperty(exports2, "__esModule", { value: true });
2107
+ exports2.SensorRegistry = void 0;
2108
+ var common_1 = require("@nestjs/common");
2109
+ var config_1 = require("@nestjs/config");
2110
+ var SensorRegistry2 = SensorRegistry_1 = class SensorRegistry {
2111
+ constructor(configService) {
2112
+ this.configService = configService;
2113
+ this.sensors = [];
2114
+ this.sensorsByName = /* @__PURE__ */ new Map();
2115
+ this.sensorsByType = /* @__PURE__ */ new Map();
2116
+ this.logger = new common_1.Logger(SensorRegistry_1.name);
2117
+ }
2118
+ register(sensor) {
2119
+ if (!sensor.name) {
2120
+ throw new Error("AxisSensor must have a name");
2121
+ }
2122
+ const enabledSensorsStr = this.configService.get("ENABLED_SENSORS");
2123
+ const disabledSensorsStr = this.configService.get("DISABLED_SENSORS");
2124
+ const enabledSensors = enabledSensorsStr ? enabledSensorsStr.split(",").map((s) => s.trim()) : null;
2125
+ const disabledSensors = disabledSensorsStr ? disabledSensorsStr.split(",").map((s) => s.trim()) : [];
2126
+ if (enabledSensors && !enabledSensors.includes(sensor.name)) {
2127
+ this.logger.log(`Skipping disabled sensor (not in ENABLED_SENSORS): ${sensor.name}`);
2128
+ return;
2129
+ }
2130
+ if (disabledSensors.includes(sensor.name)) {
2131
+ this.logger.log(`Skipping disabled sensor (in DISABLED_SENSORS): ${sensor.name}`);
2132
+ return;
2133
+ }
2134
+ if (sensor.order === void 0) {
2135
+ throw new Error(`AxisSensor "${sensor.name}" must have an order field`);
2136
+ }
2137
+ const isPreDecodeSensor = this.isPreDecodeSensor(sensor);
2138
+ const isPostDecodeSensor = this.isPostDecodeSensor(sensor);
2139
+ if (isPreDecodeSensor && sensor.order >= 40) {
2140
+ this.logger.warn(`AxisSensor "${sensor.name}" is marked as PRE_DECODE but has order ${sensor.order} (should be < 40)`);
2141
+ }
2142
+ if (isPostDecodeSensor && sensor.order < 40) {
2143
+ this.logger.warn(`AxisSensor "${sensor.name}" is marked as POST_DECODE but has order ${sensor.order} (should be >= 40)`);
2144
+ }
2145
+ this.sensors.push(sensor);
2146
+ this.indexSensor(sensor);
2147
+ const phaseLabel = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase || "UNKNOWN";
2148
+ this.logger.debug(`Registered sensor: ${sensor.name} (order: ${sensor.order}, phase: ${phaseLabel})`);
2149
+ }
2150
+ list() {
2151
+ return [...this.sensors].sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
2152
+ }
2153
+ resolve(ref) {
2154
+ if (typeof ref === "string") {
2155
+ return this.sensorsByName.get(ref);
2156
+ }
2157
+ return this.sensorsByType.get(ref) ?? this.sensorsByName.get(ref.name);
2158
+ }
2159
+ getByName(name) {
2160
+ return this.sensorsByName.get(name);
2161
+ }
2162
+ getPreDecodeSensors() {
2163
+ return this.list().filter((s) => (s.order ?? 999) < 40);
2164
+ }
2165
+ getPostDecodeSensors() {
2166
+ return this.list().filter((s) => (s.order ?? 999) >= 40);
2167
+ }
2168
+ isPreDecodeSensor(sensor) {
2169
+ const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
2170
+ return phase === "PRE_DECODE" || (sensor.order ?? 999) < 40;
2171
+ }
2172
+ isPostDecodeSensor(sensor) {
2173
+ const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
2174
+ return phase === "POST_DECODE" || (sensor.order ?? 999) >= 40;
2175
+ }
2176
+ getSensorCountByPhase() {
2177
+ return {
2178
+ preDecodeCount: this.getPreDecodeSensors().length,
2179
+ postDecodeCount: this.getPostDecodeSensors().length
2180
+ };
2181
+ }
2182
+ clear() {
2183
+ this.sensors = [];
2184
+ this.sensorsByName.clear();
2185
+ this.sensorsByType.clear();
2186
+ }
2187
+ indexSensor(sensor) {
2188
+ this.sensorsByName.set(sensor.name, sensor);
2189
+ const sensorType = sensor.constructor;
2190
+ if (!sensorType)
2191
+ return;
2192
+ this.sensorsByType.set(sensorType, sensor);
2193
+ if (!this.sensorsByName.has(sensorType.name)) {
2194
+ this.sensorsByName.set(sensorType.name, sensor);
2195
+ }
2196
+ }
2197
+ };
2198
+ exports2.SensorRegistry = SensorRegistry2;
2199
+ exports2.SensorRegistry = SensorRegistry2 = SensorRegistry_1 = __decorate([
2200
+ (0, common_1.Injectable)(),
2201
+ __metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
2202
+ ], SensorRegistry2);
2203
+ }
2204
+ });
2205
+
2070
2206
  // src/engine/intent.router.ts
2071
2207
  var require_intent_router = __commonJS({
2072
2208
  "src/engine/intent.router.ts"(exports2) {
@@ -2088,6 +2224,7 @@ var require_intent_router = __commonJS({
2088
2224
  var IntentRouter_1;
2089
2225
  var _a;
2090
2226
  var _b;
2227
+ var _c;
2091
2228
  Object.defineProperty(exports2, "__esModule", { value: true });
2092
2229
  exports2.IntentRouter = void 0;
2093
2230
  var common_1 = require("@nestjs/common");
@@ -2108,11 +2245,33 @@ var require_intent_router = __commonJS({
2108
2245
  var observer_decorator_1 = (init_observer_decorator(), __toCommonJS(observer_decorator_exports));
2109
2246
  var inline_capsule_1 = (init_inline_capsule(), __toCommonJS(inline_capsule_exports));
2110
2247
  var axis_sensor_1 = (init_axis_sensor(), __toCommonJS(axis_sensor_exports));
2248
+ var sensor_registry_1 = require_sensor_registry();
2111
2249
  var axis_execution_context_1 = (init_axis_execution_context(), __toCommonJS(axis_execution_context_exports));
2112
2250
  var observer_dispatcher_service_1 = require_observer_dispatcher_service();
2113
2251
  function observerRefKey(ref) {
2114
2252
  return typeof ref === "string" ? ref : ref.name;
2115
2253
  }
2254
+ function sensorRefKey(ref) {
2255
+ return typeof ref === "string" ? ref : ref.name;
2256
+ }
2257
+ function mergeIntentSensorRefs(...sensorGroups) {
2258
+ const merged = /* @__PURE__ */ new Map();
2259
+ for (const group of sensorGroups) {
2260
+ if (!Array.isArray(group))
2261
+ continue;
2262
+ for (const ref of group) {
2263
+ const key = sensorRefKey(ref);
2264
+ const existing = merged.get(key);
2265
+ if (!existing || typeof existing === "string" && typeof ref !== "string") {
2266
+ merged.set(key, ref);
2267
+ }
2268
+ }
2269
+ }
2270
+ return Array.from(merged.values());
2271
+ }
2272
+ function isAxisSensorInstance(value) {
2273
+ return !!value && typeof value.name === "string" && typeof value.run === "function";
2274
+ }
2116
2275
  function mergeObserverBindings(bindings) {
2117
2276
  const merged = /* @__PURE__ */ new Map();
2118
2277
  for (const binding of bindings) {
@@ -2149,9 +2308,10 @@ var require_intent_router = __commonJS({
2149
2308
  };
2150
2309
  }
2151
2310
  var IntentRouter2 = IntentRouter_1 = class IntentRouter {
2152
- constructor(moduleRef, observerDispatcher) {
2311
+ constructor(moduleRef, observerDispatcher, sensorRegistry) {
2153
2312
  this.moduleRef = moduleRef;
2154
2313
  this.observerDispatcher = observerDispatcher;
2314
+ this.sensorRegistry = sensorRegistry;
2155
2315
  this.logger = new common_1.Logger(IntentRouter_1.name);
2156
2316
  this.decoder = new TextDecoder();
2157
2317
  this.encoder = new TextEncoder();
@@ -2319,9 +2479,9 @@ var require_intent_router = __commonJS({
2319
2479
  if (!handler) {
2320
2480
  throw new Error(`Intent not found: ${intent}`);
2321
2481
  }
2322
- const sensorClasses = this.intentSensors.get(intent);
2323
- if (sensorClasses && sensorClasses.length > 0) {
2324
- await this.runIntentSensors(sensorClasses, intent, frame);
2482
+ const sensorRefs = this.intentSensors.get(intent);
2483
+ if (sensorRefs && sensorRefs.length > 0) {
2484
+ await this.runIntentSensors(sensorRefs, intent, frame);
2325
2485
  }
2326
2486
  const decoder = this.intentDecoders.get(intent);
2327
2487
  let decodedBody = frame.body;
@@ -2392,10 +2552,8 @@ var require_intent_router = __commonJS({
2392
2552
  this.intentDecoders.set(intent, decoder);
2393
2553
  }
2394
2554
  const intentSensors = Reflect.getMetadata(intent_sensors_decorator_1.INTENT_SENSORS_KEY, proto, methodName);
2395
- const combined = [
2396
- ...handlerSensors || [],
2397
- ...Array.isArray(intentSensors) ? intentSensors : []
2398
- ];
2555
+ const meta = Reflect.getMetadata(intent_decorator_1.INTENT_METADATA_KEY, proto, methodName);
2556
+ const combined = mergeIntentSensorRefs(handlerSensors, Array.isArray(intentSensors) ? intentSensors : void 0, Array.isArray(meta?.is) ? meta.is : void 0);
2399
2557
  if (combined.length > 0) {
2400
2558
  this.intentSensors.set(intent, combined);
2401
2559
  }
@@ -2413,7 +2571,6 @@ var require_intent_router = __commonJS({
2413
2571
  if (capsulePolicy) {
2414
2572
  this.intentCapsulePolicies.set(intent, capsulePolicy);
2415
2573
  }
2416
- const meta = Reflect.getMetadata(intent_decorator_1.INTENT_METADATA_KEY, proto, methodName);
2417
2574
  if (meta) {
2418
2575
  this.storeSchema({ ...meta, intent });
2419
2576
  if (meta.kind) {
@@ -2427,7 +2584,7 @@ var require_intent_router = __commonJS({
2427
2584
  }
2428
2585
  const methodSensitivity = Reflect.getMetadata(intent_policy_decorator_1.SENSITIVITY_METADATA_KEY, proto, methodName);
2429
2586
  const classSensitivity = Reflect.getMetadata(intent_policy_decorator_1.SENSITIVITY_METADATA_KEY, proto.constructor);
2430
- const sensitivity = methodSensitivity ?? classSensitivity;
2587
+ const sensitivity = meta?.sensitivity ?? methodSensitivity ?? classSensitivity;
2431
2588
  if (sensitivity) {
2432
2589
  this.intentSensitivity.set(intent, sensitivity);
2433
2590
  }
@@ -2481,23 +2638,26 @@ var require_intent_router = __commonJS({
2481
2638
  return;
2482
2639
  await this.observerDispatcher.dispatch(bindings, context);
2483
2640
  }
2484
- async runIntentSensors(sensorClasses, intent, frame) {
2485
- if (!this.moduleRef)
2486
- return;
2487
- for (const SensorClass of sensorClasses) {
2488
- let sensor;
2489
- try {
2490
- sensor = this.moduleRef.get(SensorClass, { strict: false });
2491
- } catch {
2492
- this.logger.warn(`@IntentSensors: could not resolve ${SensorClass.name} for ${intent}`);
2493
- continue;
2641
+ async runIntentSensors(sensorRefs, intent, frame) {
2642
+ for (const sensorRef of sensorRefs) {
2643
+ const sensor = this.resolveIntentSensor(sensorRef);
2644
+ const sensorName = sensorRefKey(sensorRef);
2645
+ if (!sensor) {
2646
+ this.logger.error(`Intent sensor ${sensorName} is not registered for ${intent}`);
2647
+ throw new Error(`SENSOR_MISSING:${sensorName}`);
2494
2648
  }
2495
2649
  const sensorInput = {
2496
2650
  rawBytes: frame.body,
2497
2651
  intent,
2498
2652
  body: frame.body,
2499
2653
  headerTLVs: frame.headers,
2500
- metadata: { phase: "intent", intent }
2654
+ frameBody: frame.body,
2655
+ metadata: {
2656
+ phase: "intent",
2657
+ intent,
2658
+ schema: this.getSchema(intent),
2659
+ validators: this.getValidators(intent)
2660
+ }
2501
2661
  };
2502
2662
  if (sensor.supports && !sensor.supports(sensorInput))
2503
2663
  continue;
@@ -2509,6 +2669,21 @@ var require_intent_router = __commonJS({
2509
2669
  }
2510
2670
  }
2511
2671
  }
2672
+ resolveIntentSensor(ref) {
2673
+ const registered = this.sensorRegistry?.resolve(ref);
2674
+ if (registered) {
2675
+ return registered;
2676
+ }
2677
+ if (!this.moduleRef || typeof ref === "string") {
2678
+ return void 0;
2679
+ }
2680
+ try {
2681
+ const resolved = this.moduleRef.get(ref, { strict: false });
2682
+ return isAxisSensorInstance(resolved) ? resolved : void 0;
2683
+ } catch {
2684
+ return void 0;
2685
+ }
2686
+ }
2512
2687
  getEffectiveCapsulePolicy(intent, frame) {
2513
2688
  const registeredPolicy = this.intentCapsulePolicies.get(intent);
2514
2689
  const chainConfig = this.intentChains.get(intent);
@@ -2824,7 +2999,8 @@ var require_intent_router = __commonJS({
2824
2999
  (0, common_1.Injectable)(),
2825
3000
  __param(0, (0, common_1.Optional)()),
2826
3001
  __param(1, (0, common_1.Optional)()),
2827
- __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])
3002
+ __param(2, (0, common_1.Optional)()),
3003
+ __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])
2828
3004
  ], IntentRouter2);
2829
3005
  }
2830
3006
  });
@@ -3463,6 +3639,213 @@ var init_observation_hash = __esm({
3463
3639
  }
3464
3640
  });
3465
3641
 
3642
+ // src/engine/observation/truth-scoring.ts
3643
+ function scoreTruth(obs, expected) {
3644
+ const anomalies = [];
3645
+ let passedChecks = 0;
3646
+ let totalChecks = 0;
3647
+ totalChecks++;
3648
+ if (obs.endMs && obs.decision) {
3649
+ passedChecks++;
3650
+ } else {
3651
+ anomalies.push({
3652
+ code: "OBS_NOT_FINALIZED",
3653
+ level: "critical",
3654
+ message: "Observation was not finalized"
3655
+ });
3656
+ }
3657
+ totalChecks++;
3658
+ if (obs.stages.length > 0) {
3659
+ passedChecks++;
3660
+ } else {
3661
+ anomalies.push({
3662
+ code: "OBS_NO_STAGES",
3663
+ level: "warning",
3664
+ message: "Observation has no execution stages"
3665
+ });
3666
+ }
3667
+ totalChecks++;
3668
+ const failedStages = obs.stages.filter((s) => s.status === "fail");
3669
+ if (failedStages.length === 0 || obs.decision === "DENY") {
3670
+ passedChecks++;
3671
+ } else {
3672
+ for (const stage of failedStages) {
3673
+ anomalies.push({
3674
+ code: "STAGE_FAILED",
3675
+ level: "warning",
3676
+ message: `Stage '${stage.name}' failed: ${stage.reason ?? "unknown"}`,
3677
+ field: `stages.${stage.name}`
3678
+ });
3679
+ }
3680
+ }
3681
+ totalChecks++;
3682
+ const invalidSensors = obs.sensors.filter((s) => s.durationMs < 0);
3683
+ if (invalidSensors.length === 0) {
3684
+ passedChecks++;
3685
+ } else {
3686
+ anomalies.push({
3687
+ code: "SENSOR_INVALID_TIMING",
3688
+ level: "warning",
3689
+ message: `${invalidSensors.length} sensor(s) have negative duration`
3690
+ });
3691
+ }
3692
+ totalChecks++;
3693
+ if (obs.durationMs !== void 0 && obs.durationMs >= 0 && obs.durationMs < 3e5) {
3694
+ passedChecks++;
3695
+ } else {
3696
+ anomalies.push({
3697
+ code: "OBS_DURATION_ANOMALY",
3698
+ level: "warning",
3699
+ message: `Observation duration ${obs.durationMs}ms is suspicious`,
3700
+ actual: obs.durationMs
3701
+ });
3702
+ }
3703
+ if (expected) {
3704
+ if (expected.decision !== void 0) {
3705
+ totalChecks++;
3706
+ if (obs.decision === expected.decision) {
3707
+ passedChecks++;
3708
+ } else {
3709
+ anomalies.push({
3710
+ code: "DECISION_MISMATCH",
3711
+ level: "critical",
3712
+ message: `Expected decision '${expected.decision}', got '${obs.decision}'`,
3713
+ field: "decision",
3714
+ expected: expected.decision,
3715
+ actual: obs.decision
3716
+ });
3717
+ }
3718
+ }
3719
+ if (expected.statusCode !== void 0) {
3720
+ totalChecks++;
3721
+ if (obs.statusCode === expected.statusCode) {
3722
+ passedChecks++;
3723
+ } else {
3724
+ anomalies.push({
3725
+ code: "STATUS_MISMATCH",
3726
+ level: "warning",
3727
+ message: `Expected status ${expected.statusCode}, got ${obs.statusCode}`,
3728
+ field: "statusCode",
3729
+ expected: expected.statusCode,
3730
+ actual: obs.statusCode
3731
+ });
3732
+ }
3733
+ }
3734
+ if (expected.effect !== void 0) {
3735
+ totalChecks++;
3736
+ if (obs.resultCode === expected.effect || obs.facts?.effect === expected.effect) {
3737
+ passedChecks++;
3738
+ } else {
3739
+ anomalies.push({
3740
+ code: "EFFECT_MISMATCH",
3741
+ level: "warning",
3742
+ message: `Expected effect '${expected.effect}', got '${obs.resultCode}'`,
3743
+ field: "resultCode",
3744
+ expected: expected.effect,
3745
+ actual: obs.resultCode
3746
+ });
3747
+ }
3748
+ }
3749
+ if (expected.maxDurationMs !== void 0) {
3750
+ totalChecks++;
3751
+ if (obs.durationMs !== void 0 && obs.durationMs <= expected.maxDurationMs) {
3752
+ passedChecks++;
3753
+ } else {
3754
+ anomalies.push({
3755
+ code: "DURATION_EXCEEDED",
3756
+ level: "warning",
3757
+ message: `Execution took ${obs.durationMs}ms, max allowed ${expected.maxDurationMs}ms`,
3758
+ field: "durationMs",
3759
+ expected: expected.maxDurationMs,
3760
+ actual: obs.durationMs
3761
+ });
3762
+ }
3763
+ }
3764
+ if (expected.minSensorsPassed !== void 0) {
3765
+ totalChecks++;
3766
+ const passed = obs.sensors.filter((s) => s.allowed).length;
3767
+ if (passed >= expected.minSensorsPassed) {
3768
+ passedChecks++;
3769
+ } else {
3770
+ anomalies.push({
3771
+ code: "INSUFFICIENT_SENSORS",
3772
+ level: "warning",
3773
+ message: `Only ${passed} sensors passed, minimum required ${expected.minSensorsPassed}`,
3774
+ field: "sensors",
3775
+ expected: expected.minSensorsPassed,
3776
+ actual: passed
3777
+ });
3778
+ }
3779
+ }
3780
+ if (expected.assertions) {
3781
+ for (const [key, expectedValue] of Object.entries(expected.assertions)) {
3782
+ totalChecks++;
3783
+ const actualValue = obs.facts[key];
3784
+ if (deepEqual(actualValue, expectedValue)) {
3785
+ passedChecks++;
3786
+ } else {
3787
+ anomalies.push({
3788
+ code: "ASSERTION_FAILED",
3789
+ level: "warning",
3790
+ message: `Assertion failed for facts.${key}`,
3791
+ field: `facts.${key}`,
3792
+ expected: expectedValue,
3793
+ actual: actualValue
3794
+ });
3795
+ }
3796
+ }
3797
+ }
3798
+ }
3799
+ const confidence = totalChecks > 0 ? passedChecks / totalChecks : 0;
3800
+ const hasCritical = anomalies.some((a) => a.level === "critical");
3801
+ const status = computeTruthStatus(confidence, hasCritical, anomalies.length);
3802
+ const isDeed = status === "confirmed" || status === "partial" && !hasCritical;
3803
+ return {
3804
+ status,
3805
+ confidence,
3806
+ anomalies,
3807
+ passedChecks,
3808
+ totalChecks,
3809
+ verifiedAt: Date.now(),
3810
+ isDeed
3811
+ };
3812
+ }
3813
+ function computeTruthStatus(confidence, hasCritical, anomalyCount) {
3814
+ if (hasCritical) return "failed";
3815
+ if (confidence === 1) return "confirmed";
3816
+ if (confidence >= 0.8) return "partial";
3817
+ if (confidence >= 0.5) return "uncertain";
3818
+ return "disputed";
3819
+ }
3820
+ function verifyObservation(obs, expected) {
3821
+ const verdict = scoreTruth(obs, expected);
3822
+ return { observation: obs, verdict };
3823
+ }
3824
+ function deepEqual(a, b) {
3825
+ if (a === b) return true;
3826
+ if (a === null || b === null) return false;
3827
+ if (typeof a !== typeof b) return false;
3828
+ if (typeof a !== "object") return String(a) === String(b);
3829
+ if (Array.isArray(a) && Array.isArray(b)) {
3830
+ if (a.length !== b.length) return false;
3831
+ return a.every((v, i) => deepEqual(v, b[i]));
3832
+ }
3833
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
3834
+ const aKeys = Object.keys(a);
3835
+ const bKeys = Object.keys(b);
3836
+ if (aKeys.length !== bKeys.length) return false;
3837
+ return aKeys.every(
3838
+ (key) => deepEqual(
3839
+ a[key],
3840
+ b[key]
3841
+ )
3842
+ );
3843
+ }
3844
+ var init_truth_scoring = __esm({
3845
+ "src/engine/observation/truth-scoring.ts"() {
3846
+ }
3847
+ });
3848
+
3466
3849
  // src/engine/observation/response-observer.ts
3467
3850
  function verifyResponse(ctx, response) {
3468
3851
  if (!response.effect || typeof response.effect !== "string") {
@@ -3533,97 +3916,15 @@ var init_varint = __esm({
3533
3916
  var axis_bin_exports = {};
3534
3917
  __export(axis_bin_exports, {
3535
3918
  AxisFrameZ: () => AxisFrameZ,
3536
- decodeFrame: () => decodeFrame,
3537
- encodeFrame: () => encodeFrame,
3538
- getSignTarget: () => getSignTarget
3539
- });
3540
- function encodeFrame(frame) {
3541
- const hdrBytes = (0, import_axis_protocol.encodeTLVs)(
3542
- Array.from(frame.headers.entries()).map(([t, v]) => ({
3543
- type: t,
3544
- value: v
3545
- }))
3546
- );
3547
- if (hdrBytes.length > import_axis_protocol2.MAX_HDR_LEN) throw new Error("Header too large");
3548
- if (frame.body.length > import_axis_protocol2.MAX_BODY_LEN) throw new Error("Body too large");
3549
- if (frame.sig.length > import_axis_protocol2.MAX_SIG_LEN) throw new Error("Signature too large");
3550
- const hdrLenBytes = (0, import_axis_protocol3.encodeVarint)(hdrBytes.length);
3551
- const bodyLenBytes = (0, import_axis_protocol3.encodeVarint)(frame.body.length);
3552
- const sigLenBytes = (0, import_axis_protocol3.encodeVarint)(frame.sig.length);
3553
- const totalLen = 5 + // Magic (AXIS1)
3554
- 1 + // Version
3555
- 1 + // Flags
3556
- hdrLenBytes.length + bodyLenBytes.length + sigLenBytes.length + hdrBytes.length + frame.body.length + frame.sig.length;
3557
- if (totalLen > import_axis_protocol2.MAX_FRAME_LEN) throw new Error("Total frame too large");
3558
- const buf = new Uint8Array(totalLen);
3559
- let offset = 0;
3560
- buf.set(import_axis_protocol2.AXIS_MAGIC, offset);
3561
- offset += 5;
3562
- buf[offset++] = import_axis_protocol2.AXIS_VERSION;
3563
- buf[offset++] = frame.flags;
3564
- buf.set(hdrLenBytes, offset);
3565
- offset += hdrLenBytes.length;
3566
- buf.set(bodyLenBytes, offset);
3567
- offset += bodyLenBytes.length;
3568
- buf.set(sigLenBytes, offset);
3569
- offset += sigLenBytes.length;
3570
- buf.set(hdrBytes, offset);
3571
- offset += hdrBytes.length;
3572
- buf.set(frame.body, offset);
3573
- offset += frame.body.length;
3574
- buf.set(frame.sig, offset);
3575
- offset += frame.sig.length;
3576
- return buf;
3577
- }
3578
- function decodeFrame(buf) {
3579
- let offset = 0;
3580
- if (offset + 5 > buf.length) throw new Error("Packet too short");
3581
- for (let i = 0; i < 5; i++) {
3582
- if (buf[offset + i] !== import_axis_protocol2.AXIS_MAGIC[i]) throw new Error("Invalid Magic");
3583
- }
3584
- offset += 5;
3585
- const ver = buf[offset++];
3586
- if (ver !== import_axis_protocol2.AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);
3587
- const flags = buf[offset++];
3588
- const { value: hdrLen, length: hlLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
3589
- offset += hlLen;
3590
- if (hdrLen > import_axis_protocol2.MAX_HDR_LEN) throw new Error("Header limit exceeded");
3591
- const { value: bodyLen, length: blLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
3592
- offset += blLen;
3593
- if (bodyLen > import_axis_protocol2.MAX_BODY_LEN) throw new Error("Body limit exceeded");
3594
- const { value: sigLen, length: slLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
3595
- offset += slLen;
3596
- if (sigLen > import_axis_protocol2.MAX_SIG_LEN) throw new Error("Signature limit exceeded");
3597
- if (offset + hdrLen + bodyLen + sigLen > buf.length) {
3598
- throw new Error("Frame truncated");
3599
- }
3600
- const hdrBytes = buf.slice(offset, offset + hdrLen);
3601
- offset += hdrLen;
3602
- const bodyBytes = buf.slice(offset, offset + bodyLen);
3603
- offset += bodyLen;
3604
- const sigBytes = buf.slice(offset, offset + sigLen);
3605
- offset += sigLen;
3606
- const headers = (0, import_axis_protocol.decodeTLVs)(hdrBytes);
3607
- return {
3608
- flags,
3609
- headers,
3610
- body: bodyBytes,
3611
- sig: sigBytes
3612
- };
3613
- }
3614
- function getSignTarget(frame) {
3615
- return encodeFrame({
3616
- ...frame,
3617
- sig: new Uint8Array(0)
3618
- });
3619
- }
3620
- var z, AxisFrameZ;
3919
+ decodeFrame: () => import_axis_protocol4.decodeFrame,
3920
+ encodeFrame: () => import_axis_protocol4.encodeFrame,
3921
+ getSignTarget: () => import_axis_protocol4.getSignTarget
3922
+ });
3923
+ var z, import_axis_protocol4, AxisFrameZ;
3621
3924
  var init_axis_bin = __esm({
3622
3925
  "src/core/axis-bin.ts"() {
3623
3926
  z = __toESM(require("zod"));
3624
- init_constants();
3625
- init_tlv();
3626
- init_varint();
3927
+ import_axis_protocol4 = require("@nextera.one/axis-protocol");
3627
3928
  AxisFrameZ = z.object({
3628
3929
  /** Flag bits for protocol control (e.g., encryption, compression) */
3629
3930
  flags: z.number().int().nonnegative(),
@@ -3642,12 +3943,7 @@ var init_axis_bin = __esm({
3642
3943
 
3643
3944
  // src/core/signature.ts
3644
3945
  function computeSignaturePayload(frame) {
3645
- const frameWithoutSig = {
3646
- ...frame,
3647
- sig: new Uint8Array(0)
3648
- };
3649
- const encoded = encodeFrame(frameWithoutSig);
3650
- return Buffer.from(encoded);
3946
+ return Buffer.from((0, import_axis_protocol4.getSignTarget)(frame));
3651
3947
  }
3652
3948
  function signFrame(frame, privateKey) {
3653
3949
  const payload = computeSignaturePayload(frame);
@@ -4535,7 +4831,7 @@ function encodeAxis1Frame(f) {
4535
4831
  if (!Buffer.isBuffer(f.hdr) || !Buffer.isBuffer(f.body) || !Buffer.isBuffer(f.sig)) {
4536
4832
  throw new Error("AXIS1_BAD_BUFFERS");
4537
4833
  }
4538
- if (f.ver !== 1) throw new Error("AXIS1_BAD_VER");
4834
+ if (f.ver !== import_axis_protocol5.AXIS_VERSION) throw new Error("AXIS1_BAD_VER");
4539
4835
  const hdrLen = encVarint(BigInt(f.hdr.length));
4540
4836
  const bodyLen = encVarint(BigInt(f.body.length));
4541
4837
  const sigLen = encVarint(BigInt(f.sig.length));
@@ -4551,17 +4847,18 @@ function encodeAxis1Frame(f) {
4551
4847
  f.sig
4552
4848
  ]);
4553
4849
  }
4554
- var MAGIC;
4850
+ var import_axis_protocol5, MAGIC;
4555
4851
  var init_axis1_encode = __esm({
4556
4852
  "src/codec/axis1.encode.ts"() {
4853
+ import_axis_protocol5 = require("@nextera.one/axis-protocol");
4557
4854
  init_tlv_encode();
4558
- MAGIC = Buffer.from("AXIS1", "ascii");
4855
+ MAGIC = Buffer.from(import_axis_protocol5.AXIS_MAGIC);
4559
4856
  }
4560
4857
  });
4561
4858
 
4562
4859
  // src/codec/axis1.signing.ts
4563
4860
  function axis1SigningBytes(params) {
4564
- if (params.ver !== 1) throw new Error("AXIS1_BAD_VER");
4861
+ if (params.ver !== import_axis_protocol6.AXIS_VERSION) throw new Error("AXIS1_BAD_VER");
4565
4862
  const hdrLen = encVarint(BigInt(params.hdr.length));
4566
4863
  const bodyLen = encVarint(BigInt(params.body.length));
4567
4864
  const sigLenZero = encVarint(0n);
@@ -4576,11 +4873,12 @@ function axis1SigningBytes(params) {
4576
4873
  params.body
4577
4874
  ]);
4578
4875
  }
4579
- var MAGIC2;
4876
+ var import_axis_protocol6, MAGIC2;
4580
4877
  var init_axis1_signing = __esm({
4581
4878
  "src/codec/axis1.signing.ts"() {
4879
+ import_axis_protocol6 = require("@nextera.one/axis-protocol");
4582
4880
  init_tlv_encode();
4583
- MAGIC2 = Buffer.from("AXIS1", "ascii");
4881
+ MAGIC2 = Buffer.from(import_axis_protocol6.AXIS_MAGIC);
4584
4882
  }
4585
4883
  });
4586
4884
 
@@ -4910,11 +5208,12 @@ function decodeAxis1Frame(buf) {
4910
5208
  if (off !== buf.length) throw new Error("AXIS1_TRAILING_BYTES");
4911
5209
  return { ver, flags, hdr, body, sig, frameSize: buf.length };
4912
5210
  }
4913
- var MAGIC3;
5211
+ var import_axis_protocol7, MAGIC3;
4914
5212
  var init_frame = __esm({
4915
5213
  "src/types/frame.ts"() {
5214
+ import_axis_protocol7 = require("@nextera.one/axis-protocol");
4916
5215
  init_tlv2();
4917
- MAGIC3 = Buffer.from("AXIS1", "ascii");
5216
+ MAGIC3 = Buffer.from(import_axis_protocol7.AXIS_MAGIC);
4918
5217
  }
4919
5218
  });
4920
5219
 
@@ -5037,7 +5336,52 @@ var init_capabilities = __esm({
5037
5336
  }
5038
5337
  });
5039
5338
 
5339
+ // src/law/law.types.ts
5340
+ function buildAxisLawEvaluationContext(input) {
5341
+ const metadata = input.metadata ?? {};
5342
+ const packet = input.packet;
5343
+ const packetBody = input.frameBody ?? packet?.body ?? packet?.args ?? void 0;
5344
+ const capsuleId = metadata.capsule_id ?? metadata.capsuleId ?? packet?.capsuleId ?? input.clientId;
5345
+ const audience = input.aud ?? metadata.audience ?? packet?.aud;
5346
+ const tps = metadata.tps ?? packet?.tps ?? packet?.tickTps;
5347
+ return {
5348
+ actorId: input.actorId,
5349
+ intent: input.intent,
5350
+ audience,
5351
+ tps,
5352
+ country: input.country,
5353
+ ip: input.ip,
5354
+ path: input.path,
5355
+ clientId: input.clientId,
5356
+ deviceId: input.deviceId,
5357
+ sessionId: input.sessionId,
5358
+ capsuleId,
5359
+ metadata,
5360
+ packet,
5361
+ frameBody: packetBody
5362
+ };
5363
+ }
5364
+ var init_law_types = __esm({
5365
+ "src/law/law.types.ts"() {
5366
+ }
5367
+ });
5368
+
5369
+ // src/law/index.ts
5370
+ var law_exports = {};
5371
+ __export(law_exports, {
5372
+ buildAxisLawEvaluationContext: () => buildAxisLawEvaluationContext
5373
+ });
5374
+ var init_law = __esm({
5375
+ "src/law/index.ts"() {
5376
+ init_law_types();
5377
+ }
5378
+ });
5379
+
5040
5380
  // src/risk/index.ts
5381
+ var risk_exports = {};
5382
+ __export(risk_exports, {
5383
+ RiskDecision: () => RiskDecision
5384
+ });
5041
5385
  var RiskDecision;
5042
5386
  var init_risk = __esm({
5043
5387
  "src/risk/index.ts"() {
@@ -5781,9 +6125,9 @@ var require_handler_discovery_service = __commonJS({
5781
6125
  }
5782
6126
  });
5783
6127
 
5784
- // src/engine/registry/sensor.registry.ts
5785
- var require_sensor_registry = __commonJS({
5786
- "src/engine/registry/sensor.registry.ts"(exports2) {
6128
+ // src/engine/sensor-discovery.service.ts
6129
+ var require_sensor_discovery_service = __commonJS({
6130
+ "src/engine/sensor-discovery.service.ts"(exports2) {
5787
6131
  "use strict";
5788
6132
  var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
5789
6133
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -5794,101 +6138,10 @@ var require_sensor_registry = __commonJS({
5794
6138
  var __metadata = exports2 && exports2.__metadata || function(k, v) {
5795
6139
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5796
6140
  };
5797
- var SensorRegistry_1;
6141
+ var SensorDiscoveryService_1;
5798
6142
  var _a;
5799
- Object.defineProperty(exports2, "__esModule", { value: true });
5800
- exports2.SensorRegistry = void 0;
5801
- var common_1 = require("@nestjs/common");
5802
- var config_1 = require("@nestjs/config");
5803
- var SensorRegistry2 = SensorRegistry_1 = class SensorRegistry {
5804
- constructor(configService) {
5805
- this.configService = configService;
5806
- this.sensors = [];
5807
- this.logger = new common_1.Logger(SensorRegistry_1.name);
5808
- }
5809
- register(sensor) {
5810
- if (!sensor.name) {
5811
- throw new Error("AxisSensor must have a name");
5812
- }
5813
- const enabledSensorsStr = this.configService.get("ENABLED_SENSORS");
5814
- const disabledSensorsStr = this.configService.get("DISABLED_SENSORS");
5815
- const enabledSensors = enabledSensorsStr ? enabledSensorsStr.split(",").map((s) => s.trim()) : null;
5816
- const disabledSensors = disabledSensorsStr ? disabledSensorsStr.split(",").map((s) => s.trim()) : [];
5817
- if (enabledSensors && !enabledSensors.includes(sensor.name)) {
5818
- this.logger.log(`Skipping disabled sensor (not in ENABLED_SENSORS): ${sensor.name}`);
5819
- return;
5820
- }
5821
- if (disabledSensors.includes(sensor.name)) {
5822
- this.logger.log(`Skipping disabled sensor (in DISABLED_SENSORS): ${sensor.name}`);
5823
- return;
5824
- }
5825
- if (sensor.order === void 0) {
5826
- throw new Error(`AxisSensor "${sensor.name}" must have an order field`);
5827
- }
5828
- const isPreDecodeSensor = this.isPreDecodeSensor(sensor);
5829
- const isPostDecodeSensor = this.isPostDecodeSensor(sensor);
5830
- if (isPreDecodeSensor && sensor.order >= 40) {
5831
- this.logger.warn(`AxisSensor "${sensor.name}" is marked as PRE_DECODE but has order ${sensor.order} (should be < 40)`);
5832
- }
5833
- if (isPostDecodeSensor && sensor.order < 40) {
5834
- this.logger.warn(`AxisSensor "${sensor.name}" is marked as POST_DECODE but has order ${sensor.order} (should be >= 40)`);
5835
- }
5836
- this.sensors.push(sensor);
5837
- const phaseLabel = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase || "UNKNOWN";
5838
- this.logger.debug(`Registered sensor: ${sensor.name} (order: ${sensor.order}, phase: ${phaseLabel})`);
5839
- }
5840
- list() {
5841
- return [...this.sensors].sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
5842
- }
5843
- getPreDecodeSensors() {
5844
- return this.list().filter((s) => (s.order ?? 999) < 40);
5845
- }
5846
- getPostDecodeSensors() {
5847
- return this.list().filter((s) => (s.order ?? 999) >= 40);
5848
- }
5849
- isPreDecodeSensor(sensor) {
5850
- const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
5851
- return phase === "PRE_DECODE" || (sensor.order ?? 999) < 40;
5852
- }
5853
- isPostDecodeSensor(sensor) {
5854
- const phase = typeof sensor.phase === "string" ? sensor.phase : sensor.phase?.phase;
5855
- return phase === "POST_DECODE" || (sensor.order ?? 999) >= 40;
5856
- }
5857
- getSensorCountByPhase() {
5858
- return {
5859
- preDecodeCount: this.getPreDecodeSensors().length,
5860
- postDecodeCount: this.getPostDecodeSensors().length
5861
- };
5862
- }
5863
- clear() {
5864
- this.sensors = [];
5865
- }
5866
- };
5867
- exports2.SensorRegistry = SensorRegistry2;
5868
- exports2.SensorRegistry = SensorRegistry2 = SensorRegistry_1 = __decorate([
5869
- (0, common_1.Injectable)(),
5870
- __metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
5871
- ], SensorRegistry2);
5872
- }
5873
- });
5874
-
5875
- // src/engine/sensor-discovery.service.ts
5876
- var require_sensor_discovery_service = __commonJS({
5877
- "src/engine/sensor-discovery.service.ts"(exports2) {
5878
- "use strict";
5879
- var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
5880
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5881
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5882
- 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;
5883
- return c > 3 && r && Object.defineProperty(target, key, r), r;
5884
- };
5885
- var __metadata = exports2 && exports2.__metadata || function(k, v) {
5886
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5887
- };
5888
- var SensorDiscoveryService_1;
5889
- var _a;
5890
- var _b;
5891
- var _c;
6143
+ var _b;
6144
+ var _c;
5892
6145
  Object.defineProperty(exports2, "__esModule", { value: true });
5893
6146
  exports2.SensorDiscoveryService = void 0;
5894
6147
  var common_1 = require("@nestjs/common");
@@ -6110,6 +6363,374 @@ var require_axis_sensor_chain_service = __commonJS({
6110
6363
  }
6111
6364
  });
6112
6365
 
6366
+ // src/timeline/timeline.engine.ts
6367
+ function generateId(prefix) {
6368
+ return `${prefix}_${(0, import_crypto8.randomBytes)(16).toString("hex")}`;
6369
+ }
6370
+ function sha2566(data) {
6371
+ return (0, import_crypto8.createHash)("sha256").update(data).digest("hex");
6372
+ }
6373
+ function hashPayload2(payload) {
6374
+ return sha2566(JSON.stringify(payload));
6375
+ }
6376
+ function diffObjects(a, b) {
6377
+ const diffs = [];
6378
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
6379
+ for (const key of allKeys) {
6380
+ const va = a[key];
6381
+ const vb = b[key];
6382
+ if (JSON.stringify(va) !== JSON.stringify(vb)) {
6383
+ diffs.push({ field: key, original: va, replayed: vb });
6384
+ }
6385
+ }
6386
+ return diffs;
6387
+ }
6388
+ var import_crypto8, TimelineEngine;
6389
+ var init_timeline_engine = __esm({
6390
+ "src/timeline/timeline.engine.ts"() {
6391
+ import_crypto8 = require("crypto");
6392
+ TimelineEngine = class {
6393
+ constructor(store) {
6394
+ this.store = store;
6395
+ this.handlers = /* @__PURE__ */ new Map();
6396
+ }
6397
+ /** Register an intent handler for timeline execution */
6398
+ registerHandler(handler) {
6399
+ this.handlers.set(handler.intent, handler);
6400
+ }
6401
+ // ──────────────────────────────────────────────────────────────────────
6402
+ // Record (store a real execution as a timeline event)
6403
+ // ──────────────────────────────────────────────────────────────────────
6404
+ async recordEvent(intent, actorId, payload, result, options = {}) {
6405
+ const event = {
6406
+ event_id: generateId("evt"),
6407
+ timeline_id: options.timelineId ?? "prime",
6408
+ branch_id: options.branchId ?? "main",
6409
+ parent_event_id: options.parentEventId ?? null,
6410
+ intent,
6411
+ actor_id: actorId,
6412
+ capsule_id: options.capsuleId,
6413
+ tps_coordinate: options.tpsCoordinate,
6414
+ payload_hash: hashPayload2(payload),
6415
+ result_hash: hashPayload2(result),
6416
+ status: "executed",
6417
+ domain: "prime",
6418
+ determinism: options.determinism ?? "deterministic",
6419
+ witness_id: options.witnessId,
6420
+ created_at: Date.now(),
6421
+ metadata: { payload, result }
6422
+ };
6423
+ await this.store.saveEvent(event);
6424
+ return event;
6425
+ }
6426
+ // ──────────────────────────────────────────────────────────────────────
6427
+ // Replay
6428
+ // ──────────────────────────────────────────────────────────────────────
6429
+ async replay(request) {
6430
+ const originalEvent = await this.store.getEvent(request.source_event_id);
6431
+ if (!originalEvent) {
6432
+ throw new Error(`Event ${request.source_event_id} not found`);
6433
+ }
6434
+ const handler = this.handlers.get(originalEvent.intent);
6435
+ if (!handler) {
6436
+ throw new Error(`No handler registered for intent '${originalEvent.intent}'`);
6437
+ }
6438
+ const originalPayload = originalEvent.metadata?.payload ?? {};
6439
+ const replayPayload = request.mode === "analytical" && request.override_payload ? request.override_payload : originalPayload;
6440
+ const snapshot = await this.store.getSnapshotByEvent(originalEvent.event_id);
6441
+ const context = {
6442
+ event_id: generateId("evt"),
6443
+ timeline_id: originalEvent.timeline_id,
6444
+ branch_id: `replay_${originalEvent.branch_id}`,
6445
+ domain: "audit",
6446
+ actor_id: originalEvent.actor_id,
6447
+ tps_coordinate: originalEvent.tps_coordinate,
6448
+ snapshot: snapshot ?? void 0,
6449
+ is_replay: true,
6450
+ is_simulation: false
6451
+ };
6452
+ const startMs = Date.now();
6453
+ const handlerResult = await handler.execute(replayPayload, context);
6454
+ const durationMs = Date.now() - startMs;
6455
+ const replayedEvent = {
6456
+ event_id: context.event_id,
6457
+ timeline_id: originalEvent.timeline_id,
6458
+ branch_id: context.branch_id,
6459
+ parent_event_id: originalEvent.event_id,
6460
+ intent: originalEvent.intent,
6461
+ actor_id: originalEvent.actor_id,
6462
+ capsule_id: originalEvent.capsule_id,
6463
+ tps_coordinate: originalEvent.tps_coordinate,
6464
+ payload_hash: hashPayload2(replayPayload),
6465
+ result_hash: hashPayload2(handlerResult.result_data),
6466
+ status: "replayed",
6467
+ domain: "audit",
6468
+ determinism: originalEvent.determinism,
6469
+ created_at: Date.now(),
6470
+ metadata: { payload: replayPayload, result: handlerResult.result_data }
6471
+ };
6472
+ await this.store.saveEvent(replayedEvent);
6473
+ const originalResult = originalEvent.metadata?.result ?? {};
6474
+ const differences = diffObjects(originalResult, handlerResult.result_data);
6475
+ const deterministicMatch = originalEvent.result_hash === replayedEvent.result_hash;
6476
+ return {
6477
+ original_event: originalEvent,
6478
+ replayed_event: replayedEvent,
6479
+ mode: request.mode,
6480
+ deterministic_match: deterministicMatch,
6481
+ differences,
6482
+ duration_ms: durationMs
6483
+ };
6484
+ }
6485
+ // ──────────────────────────────────────────────────────────────────────
6486
+ // Fork
6487
+ // ──────────────────────────────────────────────────────────────────────
6488
+ async fork(request) {
6489
+ const sourceEvent = await this.store.getEvent(request.source_event_id);
6490
+ if (!sourceEvent) {
6491
+ throw new Error(`Event ${request.source_event_id} not found`);
6492
+ }
6493
+ const handler = this.handlers.get(sourceEvent.intent);
6494
+ if (!handler) {
6495
+ throw new Error(`No handler registered for intent '${sourceEvent.intent}'`);
6496
+ }
6497
+ const branch = {
6498
+ branch_id: generateId("branch"),
6499
+ timeline_id: generateId("timeline"),
6500
+ origin_timeline_id: sourceEvent.timeline_id,
6501
+ origin_event_id: sourceEvent.event_id,
6502
+ branch_type: "fork",
6503
+ creator_subject_id: request.actor_id,
6504
+ purpose: request.purpose,
6505
+ status: "active"
6506
+ };
6507
+ await this.store.saveBranch(branch);
6508
+ const snapshot = {
6509
+ snapshot_id: generateId("snap"),
6510
+ timeline_id: sourceEvent.timeline_id,
6511
+ event_id: sourceEvent.event_id,
6512
+ tps_coordinate: sourceEvent.tps_coordinate,
6513
+ state_hash: hashPayload2(
6514
+ sourceEvent.metadata?.result ?? {}
6515
+ ),
6516
+ state_data: sourceEvent.metadata?.result ?? {},
6517
+ created_at: Date.now()
6518
+ };
6519
+ await this.store.saveSnapshot(snapshot);
6520
+ const context = {
6521
+ event_id: generateId("evt"),
6522
+ timeline_id: branch.timeline_id,
6523
+ branch_id: branch.branch_id,
6524
+ domain: "fork",
6525
+ actor_id: request.actor_id,
6526
+ tps_coordinate: sourceEvent.tps_coordinate,
6527
+ snapshot,
6528
+ is_replay: false,
6529
+ is_simulation: false
6530
+ };
6531
+ const handlerResult = await handler.execute(request.new_payload, context);
6532
+ const forkedEvent = {
6533
+ event_id: context.event_id,
6534
+ timeline_id: branch.timeline_id,
6535
+ branch_id: branch.branch_id,
6536
+ parent_event_id: sourceEvent.event_id,
6537
+ intent: sourceEvent.intent,
6538
+ actor_id: request.actor_id,
6539
+ tps_coordinate: sourceEvent.tps_coordinate,
6540
+ payload_hash: hashPayload2(request.new_payload),
6541
+ result_hash: hashPayload2(handlerResult.result_data),
6542
+ status: "forked",
6543
+ domain: "fork",
6544
+ determinism: sourceEvent.determinism,
6545
+ created_at: Date.now(),
6546
+ metadata: {
6547
+ payload: request.new_payload,
6548
+ result: handlerResult.result_data
6549
+ }
6550
+ };
6551
+ await this.store.saveEvent(forkedEvent);
6552
+ return { branch, forked_event: forkedEvent, snapshot };
6553
+ }
6554
+ // ──────────────────────────────────────────────────────────────────────
6555
+ // Simulate
6556
+ // ──────────────────────────────────────────────────────────────────────
6557
+ async simulate(request) {
6558
+ const handler = this.handlers.get(request.intent);
6559
+ if (!handler) {
6560
+ throw new Error(`No handler registered for intent '${request.intent}'`);
6561
+ }
6562
+ let snapshot;
6563
+ if (request.from_snapshot_id) {
6564
+ const loaded = await this.store.getSnapshot(request.from_snapshot_id);
6565
+ if (!loaded) {
6566
+ throw new Error(`Snapshot ${request.from_snapshot_id} not found`);
6567
+ }
6568
+ snapshot = loaded;
6569
+ }
6570
+ const branch = {
6571
+ branch_id: generateId("branch"),
6572
+ timeline_id: generateId("timeline"),
6573
+ origin_timeline_id: "prime",
6574
+ origin_event_id: "simulation_origin",
6575
+ branch_type: "simulation",
6576
+ created_at_tps: request.at_tps,
6577
+ creator_subject_id: request.actor_id,
6578
+ purpose: request.purpose,
6579
+ status: "active"
6580
+ };
6581
+ await this.store.saveBranch(branch);
6582
+ const context = {
6583
+ event_id: generateId("evt"),
6584
+ timeline_id: branch.timeline_id,
6585
+ branch_id: branch.branch_id,
6586
+ domain: "shadow",
6587
+ actor_id: request.actor_id,
6588
+ tps_coordinate: request.at_tps,
6589
+ snapshot,
6590
+ is_replay: false,
6591
+ is_simulation: true
6592
+ };
6593
+ const startMs = Date.now();
6594
+ const handlerResult = await handler.execute(request.payload, context);
6595
+ const durationMs = Date.now() - startMs;
6596
+ const simulatedEvent = {
6597
+ event_id: context.event_id,
6598
+ timeline_id: branch.timeline_id,
6599
+ branch_id: branch.branch_id,
6600
+ parent_event_id: null,
6601
+ intent: request.intent,
6602
+ actor_id: request.actor_id,
6603
+ tps_coordinate: request.at_tps,
6604
+ payload_hash: hashPayload2(request.payload),
6605
+ result_hash: hashPayload2(handlerResult.result_data),
6606
+ status: "simulated",
6607
+ domain: "shadow",
6608
+ determinism: "bounded_nondeterministic",
6609
+ created_at: Date.now(),
6610
+ metadata: { payload: request.payload, result: handlerResult.result_data }
6611
+ };
6612
+ await this.store.saveEvent(simulatedEvent);
6613
+ branch.status = "completed";
6614
+ await this.store.saveBranch(branch);
6615
+ return {
6616
+ branch,
6617
+ simulated_event: simulatedEvent,
6618
+ predicted_outcome: handlerResult.result_data,
6619
+ side_effects: handlerResult.side_effects ?? [],
6620
+ duration_ms: durationMs
6621
+ };
6622
+ }
6623
+ // ──────────────────────────────────────────────────────────────────────
6624
+ // Compare timelines
6625
+ // ──────────────────────────────────────────────────────────────────────
6626
+ async compare(timelineIdA, timelineIdB) {
6627
+ const eventsA = await this.store.getEventsByTimeline(timelineIdA);
6628
+ const eventsB = await this.store.getEventsByTimeline(timelineIdB);
6629
+ eventsA.sort((a, b) => a.created_at - b.created_at);
6630
+ eventsB.sort((a, b) => a.created_at - b.created_at);
6631
+ const maxLen = Math.max(eventsA.length, eventsB.length);
6632
+ const eventPairs = [];
6633
+ let divergencePoint;
6634
+ for (let i = 0; i < maxLen; i++) {
6635
+ const a = eventsA[i];
6636
+ const b = eventsB[i];
6637
+ if (!a || !b) {
6638
+ if (!divergencePoint) {
6639
+ divergencePoint = a?.event_id ?? b?.event_id;
6640
+ }
6641
+ continue;
6642
+ }
6643
+ const match = a.result_hash === b.result_hash;
6644
+ const resultA = a.metadata?.result ?? {};
6645
+ const resultB = b.metadata?.result ?? {};
6646
+ const differences = match ? [] : diffObjects(resultA, resultB);
6647
+ if (!match && !divergencePoint) {
6648
+ divergencePoint = a.event_id;
6649
+ }
6650
+ eventPairs.push({ event_a: a, event_b: b, match, differences });
6651
+ }
6652
+ return {
6653
+ timeline_a: timelineIdA,
6654
+ timeline_b: timelineIdB,
6655
+ event_pairs: eventPairs,
6656
+ divergence_point: divergencePoint
6657
+ };
6658
+ }
6659
+ // ──────────────────────────────────────────────────────────────────────
6660
+ // State snapshot management
6661
+ // ──────────────────────────────────────────────────────────────────────
6662
+ async createSnapshot(eventId, stateData) {
6663
+ const event = await this.store.getEvent(eventId);
6664
+ if (!event) {
6665
+ throw new Error(`Event ${eventId} not found`);
6666
+ }
6667
+ const snapshot = {
6668
+ snapshot_id: generateId("snap"),
6669
+ timeline_id: event.timeline_id,
6670
+ event_id: eventId,
6671
+ tps_coordinate: event.tps_coordinate,
6672
+ state_hash: hashPayload2(stateData),
6673
+ state_data: stateData,
6674
+ created_at: Date.now()
6675
+ };
6676
+ await this.store.saveSnapshot(snapshot);
6677
+ return snapshot;
6678
+ }
6679
+ async restoreSnapshot(snapshotId) {
6680
+ const snapshot = await this.store.getSnapshot(snapshotId);
6681
+ if (!snapshot) {
6682
+ throw new Error(`Snapshot ${snapshotId} not found`);
6683
+ }
6684
+ return snapshot;
6685
+ }
6686
+ };
6687
+ }
6688
+ });
6689
+
6690
+ // src/timeline/timeline.store.ts
6691
+ var InMemoryTimelineStore;
6692
+ var init_timeline_store = __esm({
6693
+ "src/timeline/timeline.store.ts"() {
6694
+ InMemoryTimelineStore = class {
6695
+ constructor() {
6696
+ this.events = /* @__PURE__ */ new Map();
6697
+ this.branches = /* @__PURE__ */ new Map();
6698
+ this.snapshots = /* @__PURE__ */ new Map();
6699
+ }
6700
+ async saveEvent(event) {
6701
+ this.events.set(event.event_id, event);
6702
+ }
6703
+ async getEvent(eventId) {
6704
+ return this.events.get(eventId) ?? null;
6705
+ }
6706
+ async getEventsByTimeline(timelineId) {
6707
+ return [...this.events.values()].filter((e) => e.timeline_id === timelineId);
6708
+ }
6709
+ async getEventsByBranch(branchId) {
6710
+ return [...this.events.values()].filter((e) => e.branch_id === branchId);
6711
+ }
6712
+ async saveBranch(branch) {
6713
+ this.branches.set(branch.branch_id, branch);
6714
+ }
6715
+ async getBranch(branchId) {
6716
+ return this.branches.get(branchId) ?? null;
6717
+ }
6718
+ async getBranchesByTimeline(timelineId) {
6719
+ return [...this.branches.values()].filter((b) => b.timeline_id === timelineId);
6720
+ }
6721
+ async saveSnapshot(snapshot) {
6722
+ this.snapshots.set(snapshot.snapshot_id, snapshot);
6723
+ }
6724
+ async getSnapshot(snapshotId) {
6725
+ return this.snapshots.get(snapshotId) ?? null;
6726
+ }
6727
+ async getSnapshotByEvent(eventId) {
6728
+ return [...this.snapshots.values()].find((s) => s.event_id === eventId) ?? null;
6729
+ }
6730
+ };
6731
+ }
6732
+ });
6733
+
6113
6734
  // src/utils/axis-tlv-codec.ts
6114
6735
  function encodeAxisTlvDto(dtoClass, data) {
6115
6736
  const schema = (0, import_dto_schema.extractDtoSchema)(dtoClass);
@@ -6168,37 +6789,1752 @@ var init_axis_tlv_codec = __esm({
6168
6789
  }
6169
6790
  });
6170
6791
 
6171
- // src/loom/loom.types.ts
6172
- function deriveAnchorReflection(softid, context = "openlogs", scope = "loom") {
6173
- return `ar:${context}:${scope}:${softid}`;
6174
- }
6175
- function canonicalizeWrit(writ) {
6176
- const ordered = {
6177
- head: { tid: writ.head.tid, seq: writ.head.seq },
6178
- body: {
6179
- who: writ.body.who,
6180
- act: writ.body.act,
6181
- res: writ.body.res,
6182
- law: writ.body.law
6183
- },
6184
- meta: { iat: writ.meta.iat, exp: writ.meta.exp, prev: writ.meta.prev }
6185
- };
6186
- return JSON.stringify(ordered);
6187
- }
6188
- function canonicalizeGrant(grant) {
6189
- const ordered = {
6190
- grant_id: grant.grant_id,
6191
- issuer: grant.issuer,
6192
- subject: grant.subject,
6193
- grant_type: grant.grant_type,
6194
- caps: grant.caps,
6195
- meta: grant.meta
6196
- };
6197
- return JSON.stringify(ordered);
6198
- }
6199
- var init_loom_types = __esm({
6200
- "src/loom/loom.types.ts"() {
6201
- init_constants();
6792
+ // src/loom/loom.types.ts
6793
+ function deriveAnchorReflection(softid, context = "openlogs", scope = "loom") {
6794
+ return `ar:${context}:${scope}:${softid}`;
6795
+ }
6796
+ function canonicalizeWrit(writ) {
6797
+ const ordered = {
6798
+ head: { tid: writ.head.tid, seq: writ.head.seq },
6799
+ body: {
6800
+ who: writ.body.who,
6801
+ act: writ.body.act,
6802
+ res: writ.body.res,
6803
+ law: writ.body.law
6804
+ },
6805
+ meta: { iat: writ.meta.iat, exp: writ.meta.exp, prev: writ.meta.prev }
6806
+ };
6807
+ return JSON.stringify(ordered);
6808
+ }
6809
+ function canonicalizeGrant(grant) {
6810
+ const ordered = {
6811
+ grant_id: grant.grant_id,
6812
+ issuer: grant.issuer,
6813
+ subject: grant.subject,
6814
+ grant_type: grant.grant_type,
6815
+ caps: grant.caps,
6816
+ meta: grant.meta
6817
+ };
6818
+ return JSON.stringify(ordered);
6819
+ }
6820
+ var init_loom_types = __esm({
6821
+ "src/loom/loom.types.ts"() {
6822
+ init_constants();
6823
+ }
6824
+ });
6825
+
6826
+ // src/loom/loom.engine.ts
6827
+ function sha2567(data) {
6828
+ return (0, import_crypto9.createHash)("sha256").update(data).digest("hex");
6829
+ }
6830
+ function hexToUint8(hex) {
6831
+ const bytes2 = new Uint8Array(hex.length / 2);
6832
+ for (let i = 0; i < hex.length; i += 2) {
6833
+ bytes2[i / 2] = parseInt(hex.substring(i, i + 2), 16);
6834
+ }
6835
+ return bytes2;
6836
+ }
6837
+ function uint8ToHex(bytes2) {
6838
+ return Array.from(bytes2).map((b) => b.toString(16).padStart(2, "0")).join("");
6839
+ }
6840
+ function b64ToUint8(b64) {
6841
+ const bin = Buffer.from(b64, "base64");
6842
+ return new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength);
6843
+ }
6844
+ function uint8ToB64(bytes2) {
6845
+ return Buffer.from(bytes2).toString("base64");
6846
+ }
6847
+ function createPresenceChallenge(declaration, ttlMs = DEFAULT_PRESENCE_TTL_MS) {
6848
+ const now = Date.now();
6849
+ const nonce = (0, import_crypto9.randomBytes)(32).toString("hex");
6850
+ const challengeId = sha2567(`${declaration.softid}:${nonce}:${now}`);
6851
+ return {
6852
+ challenge_id: challengeId,
6853
+ nonce,
6854
+ temporal_anchor: now,
6855
+ ttl_ms: ttlMs,
6856
+ expires_at: now + ttlMs
6857
+ };
6858
+ }
6859
+ function presenceSigningData(challenge, deviceMeta) {
6860
+ return JSON.stringify({
6861
+ nonce: challenge.nonce,
6862
+ temporal_anchor: challenge.temporal_anchor,
6863
+ device_meta: deviceMeta ?? null
6864
+ });
6865
+ }
6866
+ function signPresenceChallenge(challenge, privateKeyHex, publicKeyHex, declaration, kid) {
6867
+ const data = presenceSigningData(challenge, declaration.device_meta);
6868
+ const msgBytes = new TextEncoder().encode(data);
6869
+ const secretKey = hexToUint8(privateKeyHex);
6870
+ const signature = import_tweetnacl.sign.detached(msgBytes, secretKey);
6871
+ return {
6872
+ challenge_id: challenge.challenge_id,
6873
+ signature: uint8ToHex(signature),
6874
+ public_key: publicKeyHex,
6875
+ kid
6876
+ };
6877
+ }
6878
+ function verifyPresenceProof(challenge, proof, declaration, durationMs = DEFAULT_PRESENCE_DURATION_MS) {
6879
+ if (Date.now() > challenge.expires_at) {
6880
+ return { valid: false, error: "Challenge expired", code: "CHALLENGE_EXPIRED" };
6881
+ }
6882
+ if (proof.challenge_id !== challenge.challenge_id) {
6883
+ return { valid: false, error: "Challenge ID mismatch", code: "CHALLENGE_MISMATCH" };
6884
+ }
6885
+ const data = presenceSigningData(challenge, declaration.device_meta);
6886
+ const msgBytes = new TextEncoder().encode(data);
6887
+ const sigBytes = hexToUint8(proof.signature);
6888
+ const pubBytes = hexToUint8(proof.public_key);
6889
+ let isValid;
6890
+ try {
6891
+ isValid = import_tweetnacl.sign.detached.verify(msgBytes, sigBytes, pubBytes);
6892
+ } catch {
6893
+ return { valid: false, error: "Signature verification failed", code: "SIG_INVALID" };
6894
+ }
6895
+ if (!isValid) {
6896
+ return { valid: false, error: "Invalid signature", code: "SIG_INVALID" };
6897
+ }
6898
+ const now = Date.now();
6899
+ const presenceId = sha2567(
6900
+ `${proof.public_key}:${challenge.nonce}:${challenge.temporal_anchor}`
6901
+ );
6902
+ const anchorReflection = sha2567(
6903
+ `ar:openlogs:loom:${proof.public_key}`
6904
+ );
6905
+ const receipt = {
6906
+ presence_id: presenceId,
6907
+ softid: declaration.softid,
6908
+ anchor_reflection: anchorReflection,
6909
+ scope: {
6910
+ device_fingerprint: declaration.device_meta?.fingerprint
6911
+ },
6912
+ issued_at: now,
6913
+ expires_at: now + durationMs
6914
+ };
6915
+ return { valid: true, presence: receipt };
6916
+ }
6917
+ function getPresenceStatus(receipt) {
6918
+ const now = Date.now();
6919
+ if (now > receipt.expires_at) return "expired";
6920
+ return "active";
6921
+ }
6922
+ function renewPresence(receipt, extensionMs = DEFAULT_PRESENCE_DURATION_MS) {
6923
+ const now = Date.now();
6924
+ return {
6925
+ ...receipt,
6926
+ renewed_at: now,
6927
+ expires_at: now + extensionMs
6928
+ };
6929
+ }
6930
+ function createWrit(body, meta, thread, privateKeyHex, kid) {
6931
+ const head = { tid: thread.tid, seq: thread.seq };
6932
+ const writMeta = { ...meta, prev: thread.prevHash };
6933
+ const unsigned = { head, body, meta: writMeta };
6934
+ const canonical = canonicalizeWrit(unsigned);
6935
+ const msgBytes = new TextEncoder().encode(canonical);
6936
+ const secretKey = hexToUint8(privateKeyHex);
6937
+ const signature = import_tweetnacl.sign.detached(msgBytes, secretKey);
6938
+ const sig = {
6939
+ alg: "ed25519",
6940
+ value: uint8ToB64(signature),
6941
+ kid
6942
+ };
6943
+ return { head, body, meta: writMeta, sig };
6944
+ }
6945
+ function validateWrit(writ, publicKeyHex, threadState, grants) {
6946
+ const now = Math.floor(Date.now() / 1e3);
6947
+ if (now < writ.meta.iat) {
6948
+ return {
6949
+ valid: false,
6950
+ error: "Writ not yet valid (iat in future)",
6951
+ code: "TEMPORAL_NOT_YET",
6952
+ gate_failed: "temporal"
6953
+ };
6954
+ }
6955
+ if (now > writ.meta.exp) {
6956
+ return {
6957
+ valid: false,
6958
+ error: "Writ expired",
6959
+ code: "TEMPORAL_EXPIRED",
6960
+ gate_failed: "temporal"
6961
+ };
6962
+ }
6963
+ if (threadState) {
6964
+ if (writ.head.tid !== threadState.thread_id) {
6965
+ return {
6966
+ valid: false,
6967
+ error: "Thread ID mismatch",
6968
+ code: "CAUSAL_TID",
6969
+ gate_failed: "causal"
6970
+ };
6971
+ }
6972
+ if (writ.head.seq !== threadState.sequence + 1) {
6973
+ return {
6974
+ valid: false,
6975
+ error: `Expected seq ${threadState.sequence + 1}, got ${writ.head.seq}`,
6976
+ code: "CAUSAL_SEQ",
6977
+ gate_failed: "causal"
6978
+ };
6979
+ }
6980
+ if (writ.meta.prev !== threadState.last_receipt_hash) {
6981
+ return {
6982
+ valid: false,
6983
+ error: "Previous receipt hash mismatch",
6984
+ code: "CAUSAL_PREV",
6985
+ gate_failed: "causal"
6986
+ };
6987
+ }
6988
+ } else {
6989
+ if (writ.head.seq !== 1) {
6990
+ return {
6991
+ valid: false,
6992
+ error: "First writ in thread must have seq=1",
6993
+ code: "CAUSAL_FIRST_SEQ",
6994
+ gate_failed: "causal"
6995
+ };
6996
+ }
6997
+ if (writ.meta.prev !== "") {
6998
+ return {
6999
+ valid: false,
7000
+ error: "First writ must have empty prev hash",
7001
+ code: "CAUSAL_FIRST_PREV",
7002
+ gate_failed: "causal"
7003
+ };
7004
+ }
7005
+ }
7006
+ if (writ.body.law !== "self") {
7007
+ const matchingGrant = grants.find(
7008
+ (g) => g.grant_id === writ.body.law && g.subject === writ.body.who && grantCoversAction(g, writ.body.act, writ.body.res, now)
7009
+ );
7010
+ if (!matchingGrant) {
7011
+ return {
7012
+ valid: false,
7013
+ error: `No valid grant found for law=${writ.body.law}`,
7014
+ code: "LEGAL_NO_GRANT",
7015
+ gate_failed: "legal"
7016
+ };
7017
+ }
7018
+ }
7019
+ const unsigned = {
7020
+ head: writ.head,
7021
+ body: writ.body,
7022
+ meta: writ.meta
7023
+ };
7024
+ const canonical = canonicalizeWrit(unsigned);
7025
+ const msgBytes = new TextEncoder().encode(canonical);
7026
+ const sigBytes = b64ToUint8(writ.sig.value);
7027
+ const pubBytes = hexToUint8(publicKeyHex);
7028
+ let sigValid;
7029
+ try {
7030
+ sigValid = import_tweetnacl.sign.detached.verify(msgBytes, sigBytes, pubBytes);
7031
+ } catch {
7032
+ return {
7033
+ valid: false,
7034
+ error: "Signature verification failed",
7035
+ code: "AUTH_SIG_FAIL",
7036
+ gate_failed: "authentic"
7037
+ };
7038
+ }
7039
+ if (!sigValid) {
7040
+ return {
7041
+ valid: false,
7042
+ error: "Invalid signature",
7043
+ code: "AUTH_SIG_INVALID",
7044
+ gate_failed: "authentic"
7045
+ };
7046
+ }
7047
+ return { valid: true, writ };
7048
+ }
7049
+ function grantCoversAction(grant, action, resource, nowUnix) {
7050
+ if (nowUnix < grant.meta.iat || nowUnix > grant.meta.exp) {
7051
+ return false;
7052
+ }
7053
+ return grant.caps.some(
7054
+ (cap) => matchOec(cap.oec, action) && matchScope(cap.scope, resource)
7055
+ );
7056
+ }
7057
+ function matchOec(pattern, action) {
7058
+ if (pattern === "*") return true;
7059
+ if (pattern === action) return true;
7060
+ if (pattern.endsWith(".*")) {
7061
+ const prefix = pattern.slice(0, -2);
7062
+ return action.startsWith(prefix + ".");
7063
+ }
7064
+ return false;
7065
+ }
7066
+ function matchScope(pattern, resource) {
7067
+ if (pattern === "*") return true;
7068
+ if (pattern === resource) return true;
7069
+ if (pattern.includes("*")) {
7070
+ const regex = new RegExp(
7071
+ "^" + pattern.replace(/\./g, "\\.").replace(/\*/g, "[^:]*") + "$"
7072
+ );
7073
+ return regex.test(resource);
7074
+ }
7075
+ return false;
7076
+ }
7077
+ function getGrantStatus(grant, revocations) {
7078
+ const now = Math.floor(Date.now() / 1e3);
7079
+ const revoked = revocations.find(
7080
+ (r) => r.target_type === "grant" && r.target_id === grant.grant_id
7081
+ );
7082
+ if (revoked && revoked.effective_at <= now * 1e3) {
7083
+ return "revoked";
7084
+ }
7085
+ if (now > grant.meta.exp) return "expired";
7086
+ return "active";
7087
+ }
7088
+ function validateGrant(grant, issuerPublicKeyHex) {
7089
+ const unsigned = {
7090
+ grant_id: grant.grant_id,
7091
+ issuer: grant.issuer,
7092
+ subject: grant.subject,
7093
+ grant_type: grant.grant_type,
7094
+ caps: grant.caps,
7095
+ meta: grant.meta
7096
+ };
7097
+ const canonical = canonicalizeGrant(unsigned);
7098
+ const msgBytes = new TextEncoder().encode(canonical);
7099
+ const sigBytes = b64ToUint8(grant.sig.value);
7100
+ const pubBytes = hexToUint8(issuerPublicKeyHex);
7101
+ let valid;
7102
+ try {
7103
+ valid = import_tweetnacl.sign.detached.verify(msgBytes, sigBytes, pubBytes);
7104
+ } catch {
7105
+ return { valid: false, error: "Grant signature verification failed", code: "GRANT_SIG_FAIL" };
7106
+ }
7107
+ if (!valid) {
7108
+ return { valid: false, error: "Invalid grant signature", code: "GRANT_SIG_INVALID" };
7109
+ }
7110
+ return { valid: true, grant };
7111
+ }
7112
+ function createGrant(grantId, issuer, subject, grantType, caps, meta, privateKeyHex, kid) {
7113
+ const unsigned = {
7114
+ grant_id: grantId,
7115
+ issuer,
7116
+ subject,
7117
+ grant_type: grantType,
7118
+ caps,
7119
+ meta
7120
+ };
7121
+ const canonical = canonicalizeGrant(unsigned);
7122
+ const msgBytes = new TextEncoder().encode(canonical);
7123
+ const secretKey = hexToUint8(privateKeyHex);
7124
+ const signature = import_tweetnacl.sign.detached(msgBytes, secretKey);
7125
+ return {
7126
+ ...unsigned,
7127
+ sig: {
7128
+ alg: "ed25519",
7129
+ value: uint8ToB64(signature),
7130
+ kid
7131
+ }
7132
+ };
7133
+ }
7134
+ function createReceipt(writ, effect, prevReceipt, metadata) {
7135
+ const now = Date.now();
7136
+ const sequence = prevReceipt ? prevReceipt.sequence + 1 : 1;
7137
+ const prevHash = prevReceipt?.hash ?? null;
7138
+ const writHash = sha2567(canonicalizeWrit({
7139
+ head: writ.head,
7140
+ body: writ.body,
7141
+ meta: writ.meta
7142
+ }));
7143
+ const hashInput = [
7144
+ prevHash ?? "",
7145
+ writHash,
7146
+ writ.head.tid,
7147
+ String(sequence),
7148
+ effect,
7149
+ String(now)
7150
+ ].join(":");
7151
+ const receiptHash = sha2567(hashInput);
7152
+ const receiptId = sha2567(`receipt:${receiptHash}:${now}`);
7153
+ return {
7154
+ receipt_id: receiptId,
7155
+ writ_hash: writHash,
7156
+ thread_id: writ.head.tid,
7157
+ sequence,
7158
+ effect,
7159
+ hash: receiptHash,
7160
+ prev_hash: prevHash,
7161
+ executed_at: now,
7162
+ metadata
7163
+ };
7164
+ }
7165
+ function verifyReceiptChain(receipts) {
7166
+ if (receipts.length === 0) return { valid: true };
7167
+ const sorted = [...receipts].sort((a, b) => a.sequence - b.sequence);
7168
+ if (sorted[0].prev_hash !== null) {
7169
+ return {
7170
+ valid: false,
7171
+ brokenAt: 0,
7172
+ error: "First receipt must have null prev_hash"
7173
+ };
7174
+ }
7175
+ for (let i = 1; i < sorted.length; i++) {
7176
+ if (sorted[i].prev_hash !== sorted[i - 1].hash) {
7177
+ return {
7178
+ valid: false,
7179
+ brokenAt: i,
7180
+ error: `Receipt ${i} prev_hash does not match receipt ${i - 1} hash`
7181
+ };
7182
+ }
7183
+ }
7184
+ return { valid: true };
7185
+ }
7186
+ function updateThreadState(receipt, softid) {
7187
+ return {
7188
+ thread_id: receipt.thread_id,
7189
+ softid,
7190
+ last_receipt_hash: receipt.hash,
7191
+ sequence: receipt.sequence,
7192
+ updated_at: receipt.executed_at
7193
+ };
7194
+ }
7195
+ function createRevocation(targetType, targetId, issuerSoftid, privateKeyHex, reason) {
7196
+ const now = Date.now();
7197
+ const revocationId = sha2567(`revoke:${targetType}:${targetId}:${now}`);
7198
+ const payload = JSON.stringify({
7199
+ revocation_id: revocationId,
7200
+ target_type: targetType,
7201
+ target_id: targetId,
7202
+ issuer_softid: issuerSoftid,
7203
+ effective_at: now,
7204
+ reason: reason ?? null
7205
+ });
7206
+ const msgBytes = new TextEncoder().encode(payload);
7207
+ const secretKey = hexToUint8(privateKeyHex);
7208
+ const signature = import_tweetnacl.sign.detached(msgBytes, secretKey);
7209
+ return {
7210
+ revocation_id: revocationId,
7211
+ target_type: targetType,
7212
+ target_id: targetId,
7213
+ issuer_softid: issuerSoftid,
7214
+ reason,
7215
+ effective_at: now,
7216
+ sig_value: uint8ToHex(signature)
7217
+ };
7218
+ }
7219
+ function isRevoked(targetType, targetId, revocations) {
7220
+ const now = Date.now();
7221
+ return revocations.some(
7222
+ (r) => r.target_type === targetType && r.target_id === targetId && r.effective_at <= now
7223
+ );
7224
+ }
7225
+ function executeLoomPipeline(writ, publicKeyHex, presence, threadState, grants, revocations, prevReceipt) {
7226
+ const presenceStatus = getPresenceStatus(presence);
7227
+ if (presenceStatus !== "active") {
7228
+ return { valid: false, error: "Presence not active", code: "PRESENCE_INACTIVE" };
7229
+ }
7230
+ if (isRevoked("presence", presence.presence_id, revocations)) {
7231
+ return { valid: false, error: "Presence revoked", code: "PRESENCE_REVOKED" };
7232
+ }
7233
+ const activeGrants = grants.filter(
7234
+ (g) => getGrantStatus(g, revocations) === "active"
7235
+ );
7236
+ const writResult = validateWrit(writ, publicKeyHex, threadState, activeGrants);
7237
+ if (!writResult.valid) {
7238
+ return { valid: false, error: writResult.error, code: writResult.code };
7239
+ }
7240
+ const receipt = createReceipt(writ, "ALLOW", prevReceipt);
7241
+ const newThreadState = updateThreadState(receipt, writ.body.who);
7242
+ return {
7243
+ receipt,
7244
+ threadState: newThreadState,
7245
+ writValidation: writResult
7246
+ };
7247
+ }
7248
+ var import_crypto9, import_tweetnacl, DEFAULT_PRESENCE_TTL_MS, DEFAULT_PRESENCE_DURATION_MS;
7249
+ var init_loom_engine = __esm({
7250
+ "src/loom/loom.engine.ts"() {
7251
+ import_crypto9 = require("crypto");
7252
+ import_tweetnacl = require("tweetnacl");
7253
+ init_loom_types();
7254
+ DEFAULT_PRESENCE_TTL_MS = 5e3;
7255
+ DEFAULT_PRESENCE_DURATION_MS = 30 * 60 * 1e3;
7256
+ }
7257
+ });
7258
+
7259
+ // src/idel/idel.compiler.ts
7260
+ function validateType(value, expectedType) {
7261
+ switch (expectedType) {
7262
+ case "string":
7263
+ return typeof value === "string";
7264
+ case "number":
7265
+ return typeof value === "number" && Number.isFinite(value);
7266
+ case "boolean":
7267
+ return typeof value === "boolean";
7268
+ case "object":
7269
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7270
+ case "array":
7271
+ return Array.isArray(value);
7272
+ default:
7273
+ return true;
7274
+ }
7275
+ }
7276
+ function assessRisk(schema, proposal, constraints) {
7277
+ const factors = [];
7278
+ let score = 0;
7279
+ const baseRiskMap = {
7280
+ none: 0,
7281
+ low: 0.1,
7282
+ medium: 0.3,
7283
+ high: 0.6,
7284
+ critical: 0.9
7285
+ };
7286
+ score = baseRiskMap[schema.risk_level] ?? 0;
7287
+ if (schema.risk_level !== "none") {
7288
+ factors.push(`Base risk: ${schema.risk_level}`);
7289
+ }
7290
+ if (schema.has_side_effects) {
7291
+ score += 0.1;
7292
+ factors.push("Has side effects");
7293
+ }
7294
+ if (!schema.reversible) {
7295
+ score += 0.1;
7296
+ factors.push("Not reversible");
7297
+ }
7298
+ const failed = constraints.filter((c) => !c.satisfied);
7299
+ if (failed.length > 0) {
7300
+ score += 0.05 * failed.length;
7301
+ factors.push(`${failed.length} unsatisfied constraint(s)`);
7302
+ }
7303
+ score = Math.min(score, 1);
7304
+ let level;
7305
+ if (score <= 0) level = "none";
7306
+ else if (score <= 0.2) level = "low";
7307
+ else if (score <= 0.5) level = "medium";
7308
+ else if (score <= 0.8) level = "high";
7309
+ else level = "critical";
7310
+ return { level, score, factors };
7311
+ }
7312
+ var IdelSchemaRegistry, IdelCompiler;
7313
+ var init_idel_compiler = __esm({
7314
+ "src/idel/idel.compiler.ts"() {
7315
+ IdelSchemaRegistry = class {
7316
+ constructor() {
7317
+ this.schemas = /* @__PURE__ */ new Map();
7318
+ this.aliases = /* @__PURE__ */ new Map();
7319
+ }
7320
+ register(schema) {
7321
+ this.schemas.set(schema.intent, schema);
7322
+ }
7323
+ registerAlias(alias, intent) {
7324
+ this.aliases.set(alias.toLowerCase(), intent);
7325
+ }
7326
+ get(intent) {
7327
+ return this.schemas.get(intent);
7328
+ }
7329
+ resolve(raw) {
7330
+ const exact = this.schemas.get(raw);
7331
+ if (exact) return exact;
7332
+ const aliased = this.aliases.get(raw.toLowerCase());
7333
+ if (aliased) return this.schemas.get(aliased);
7334
+ const candidates = [...this.schemas.keys()].filter(
7335
+ (k) => k.startsWith(raw + ".") || k.toLowerCase().includes(raw.toLowerCase())
7336
+ );
7337
+ if (candidates.length === 1) {
7338
+ return this.schemas.get(candidates[0]);
7339
+ }
7340
+ return void 0;
7341
+ }
7342
+ /**
7343
+ * Find all schemas that partially match the raw input.
7344
+ * Returns scored candidates for ambiguity resolution.
7345
+ */
7346
+ findCandidates(raw) {
7347
+ const normalized = raw.toLowerCase().trim();
7348
+ const results = [];
7349
+ for (const [key, schema] of this.schemas) {
7350
+ let score = 0;
7351
+ if (key === raw) {
7352
+ score = 1;
7353
+ } else if (key.toLowerCase() === normalized) {
7354
+ score = 0.95;
7355
+ } else if (this.aliases.get(normalized) === key) {
7356
+ score = 0.9;
7357
+ } else if (key.toLowerCase().startsWith(normalized)) {
7358
+ score = 0.7;
7359
+ } else if (key.toLowerCase().includes(normalized)) {
7360
+ score = 0.5;
7361
+ } else if (schema.tags?.some((t) => t.toLowerCase().includes(normalized))) {
7362
+ score = 0.4;
7363
+ } else if (schema.description.toLowerCase().includes(normalized)) {
7364
+ score = 0.3;
7365
+ }
7366
+ if (score > 0) {
7367
+ results.push({ schema, score });
7368
+ }
7369
+ }
7370
+ return results.sort((a, b) => b.score - a.score);
7371
+ }
7372
+ list() {
7373
+ return [...this.schemas.values()];
7374
+ }
7375
+ };
7376
+ IdelCompiler = class {
7377
+ constructor(registry) {
7378
+ this.registry = registry;
7379
+ }
7380
+ /**
7381
+ * Compile a raw intent proposal into a validated, executable structure.
7382
+ */
7383
+ compile(proposal) {
7384
+ const errors = [];
7385
+ const candidates = this.registry.findCandidates(proposal.raw);
7386
+ if (candidates.length === 0) {
7387
+ return {
7388
+ ok: false,
7389
+ errors: [{
7390
+ code: "IDEL_UNKNOWN_INTENT",
7391
+ message: `No intent found matching '${proposal.raw}'`
7392
+ }]
7393
+ };
7394
+ }
7395
+ const best = candidates[0];
7396
+ const schema = best.schema;
7397
+ const alternatives = candidates.slice(1, 4).filter((c) => c.score >= 0.3).map((c) => ({
7398
+ intent: c.schema.intent,
7399
+ confidence: c.score,
7400
+ reason: c.schema.description
7401
+ }));
7402
+ const constraints = [];
7403
+ const clarifications = [];
7404
+ const params = { ...proposal.params };
7405
+ for (const paramSchema of schema.params) {
7406
+ const value = params[paramSchema.name];
7407
+ if (paramSchema.required && value === void 0) {
7408
+ if (paramSchema.default !== void 0) {
7409
+ params[paramSchema.name] = paramSchema.default;
7410
+ constraints.push({
7411
+ kind: "required_param",
7412
+ field: paramSchema.name,
7413
+ description: `Defaulted to ${JSON.stringify(paramSchema.default)}`,
7414
+ satisfied: true,
7415
+ value: paramSchema.default
7416
+ });
7417
+ } else {
7418
+ constraints.push({
7419
+ kind: "required_param",
7420
+ field: paramSchema.name,
7421
+ description: `Required parameter '${paramSchema.name}' is missing`,
7422
+ satisfied: false
7423
+ });
7424
+ clarifications.push({
7425
+ id: `clarify_${paramSchema.name}`,
7426
+ question: paramSchema.description ?? `What is the ${paramSchema.name}?`,
7427
+ field: paramSchema.name,
7428
+ options: paramSchema.enum?.map(String),
7429
+ required: true
7430
+ });
7431
+ }
7432
+ continue;
7433
+ }
7434
+ if (value === void 0) continue;
7435
+ const typeValid = validateType(value, paramSchema.type);
7436
+ constraints.push({
7437
+ kind: "type_check",
7438
+ field: paramSchema.name,
7439
+ description: `Must be ${paramSchema.type}`,
7440
+ satisfied: typeValid,
7441
+ value,
7442
+ expected: paramSchema.type
7443
+ });
7444
+ if (!typeValid) {
7445
+ errors.push({
7446
+ code: "IDEL_TYPE_ERROR",
7447
+ message: `Parameter '${paramSchema.name}' must be ${paramSchema.type}, got ${typeof value}`,
7448
+ field: paramSchema.name
7449
+ });
7450
+ }
7451
+ if (paramSchema.min !== void 0 || paramSchema.max !== void 0) {
7452
+ const numVal = typeof value === "number" ? value : Number(value);
7453
+ const inRange = (paramSchema.min === void 0 || numVal >= paramSchema.min) && (paramSchema.max === void 0 || numVal <= paramSchema.max);
7454
+ constraints.push({
7455
+ kind: "range",
7456
+ field: paramSchema.name,
7457
+ description: `Must be between ${paramSchema.min ?? "-\u221E"} and ${paramSchema.max ?? "\u221E"}`,
7458
+ satisfied: inRange,
7459
+ value: numVal
7460
+ });
7461
+ }
7462
+ if (paramSchema.pattern) {
7463
+ const matches = new RegExp(paramSchema.pattern).test(String(value));
7464
+ constraints.push({
7465
+ kind: "pattern",
7466
+ field: paramSchema.name,
7467
+ description: `Must match ${paramSchema.pattern}`,
7468
+ satisfied: matches,
7469
+ value,
7470
+ expected: paramSchema.pattern
7471
+ });
7472
+ }
7473
+ if (paramSchema.enum) {
7474
+ const inEnum = paramSchema.enum.some(
7475
+ (e) => JSON.stringify(e) === JSON.stringify(value)
7476
+ );
7477
+ constraints.push({
7478
+ kind: "custom",
7479
+ field: paramSchema.name,
7480
+ description: `Must be one of: ${paramSchema.enum.join(", ")}`,
7481
+ satisfied: inEnum,
7482
+ value,
7483
+ expected: paramSchema.enum
7484
+ });
7485
+ }
7486
+ }
7487
+ const risk = assessRisk(schema, proposal, constraints);
7488
+ const unsatisfied = constraints.filter((c) => !c.satisfied);
7489
+ const needsClarification = clarifications.length > 0;
7490
+ let confidence = best.score;
7491
+ if (unsatisfied.length > 0) {
7492
+ confidence *= 1 - unsatisfied.length / Math.max(constraints.length, 1) * 0.5;
7493
+ }
7494
+ if (errors.length > 0) {
7495
+ confidence *= 0.5;
7496
+ }
7497
+ const compiled = {
7498
+ intent: schema.intent,
7499
+ actor_id: proposal.actor_id,
7500
+ target: proposal.target,
7501
+ params,
7502
+ constraints,
7503
+ confidence,
7504
+ alternatives,
7505
+ needs_clarification: needsClarification,
7506
+ clarifications,
7507
+ expected_outcome: schema.description,
7508
+ fallback: schema.related?.[0],
7509
+ risk,
7510
+ metadata: {
7511
+ schema_intent: schema.intent,
7512
+ resolved_from: proposal.raw,
7513
+ has_side_effects: schema.has_side_effects,
7514
+ reversible: schema.reversible
7515
+ }
7516
+ };
7517
+ return {
7518
+ ok: errors.length === 0 && !needsClarification,
7519
+ compiled,
7520
+ errors
7521
+ };
7522
+ }
7523
+ /**
7524
+ * Apply clarification answers and re-compile.
7525
+ */
7526
+ applyClarifications(compiled, answers) {
7527
+ const proposal = {
7528
+ raw: compiled.intent,
7529
+ actor_id: compiled.actor_id,
7530
+ target: compiled.target,
7531
+ params: { ...compiled.params, ...answers }
7532
+ };
7533
+ return this.compile(proposal);
7534
+ }
7535
+ };
7536
+ }
7537
+ });
7538
+
7539
+ // src/needle/needle.engine.ts
7540
+ function assembleNeedle(params) {
7541
+ return {
7542
+ needle_id: (0, import_crypto10.randomBytes)(16).toString("hex"),
7543
+ phase: "created",
7544
+ tps_coordinate: params.tps_coordinate,
7545
+ intent: params.intent,
7546
+ presence: params.presence,
7547
+ writ: params.writ,
7548
+ grants: params.grants,
7549
+ created_at: Date.now()
7550
+ };
7551
+ }
7552
+ function classifyStitch(observation, verdict) {
7553
+ if (verdict.status === "failed" || verdict.status === "disputed") {
7554
+ return "torn";
7555
+ }
7556
+ if (observation.decision === "DENY") {
7557
+ return "silent";
7558
+ }
7559
+ if (verdict.isDeed) {
7560
+ return "deed";
7561
+ }
7562
+ return "silent";
7563
+ }
7564
+ function formStitch(needle, observation, verdict, receipt) {
7565
+ return {
7566
+ stitch_id: needle.needle_id,
7567
+ kind: classifyStitch(observation, verdict),
7568
+ intent: needle.intent.intent,
7569
+ actor_id: needle.intent.actor_id,
7570
+ tps_coordinate: needle.tps_coordinate,
7571
+ observation,
7572
+ verdict,
7573
+ receipt,
7574
+ thread_id: receipt.thread_id,
7575
+ sequence: receipt.sequence,
7576
+ stitched_at: Date.now()
7577
+ };
7578
+ }
7579
+ async function runNeedlePipeline(needle, config, threadState, prevReceipt, expectedOutcome) {
7580
+ const obs = createObservation("http");
7581
+ obs.intent = needle.intent.intent;
7582
+ obs.actorId = needle.intent.actor_id;
7583
+ needle.phase = "validated";
7584
+ let stage = startStage(obs, "loom.validate");
7585
+ const validation = validateWrit(
7586
+ needle.writ,
7587
+ config.public_key,
7588
+ threadState,
7589
+ needle.grants
7590
+ );
7591
+ if (!validation.valid) {
7592
+ endStage(stage, "fail", validation.error);
7593
+ return failNeedle(needle, obs, "validated", "LOOM_VALIDATION_FAILED", validation.error ?? "Writ validation failed");
7594
+ }
7595
+ endStage(stage, "ok");
7596
+ if (config.sensors && config.sensors.length > 0) {
7597
+ stage = startStage(obs, "sensors.evaluate");
7598
+ const sensorInput = {
7599
+ intent: needle.intent.intent,
7600
+ actorId: needle.intent.actor_id,
7601
+ metadata: {
7602
+ observation: obs,
7603
+ needle_id: needle.needle_id,
7604
+ tps_coordinate: needle.tps_coordinate,
7605
+ writ: needle.writ,
7606
+ grants: needle.grants,
7607
+ params: needle.intent.params
7608
+ }
7609
+ };
7610
+ for (const sensor of config.sensors) {
7611
+ if (sensor.supports && !sensor.supports(sensorInput)) continue;
7612
+ const t0 = Date.now();
7613
+ let decision;
7614
+ try {
7615
+ const rawDecision = await sensor.run(sensorInput);
7616
+ decision = normalizeSensorDecision(rawDecision);
7617
+ } catch (err) {
7618
+ const msg = err instanceof Error ? err.message : String(err);
7619
+ recordSensor(obs, sensor.name, false, 100, Date.now() - t0, [`sensor_error:${msg}`]);
7620
+ endStage(stage, "fail", `Sensor ${sensor.name} threw: ${msg}`);
7621
+ return failNeedle(needle, obs, "validated", "SENSOR_ERROR", `Sensor ${sensor.name} failed: ${msg}`);
7622
+ }
7623
+ recordSensor(obs, sensor.name, decision.allow, decision.riskScore, Date.now() - t0, decision.reasons);
7624
+ if (!decision.allow) {
7625
+ endStage(stage, "fail", `Sensor ${sensor.name} denied`);
7626
+ return failNeedle(needle, obs, "validated", "SENSOR_DENY", decision.reasons[0] ?? `Denied by ${sensor.name}`);
7627
+ }
7628
+ }
7629
+ endStage(stage, "ok");
7630
+ }
7631
+ needle.phase = "executing";
7632
+ stage = startStage(obs, "handler.execute");
7633
+ const handler = config.handlers.get(needle.intent.intent);
7634
+ if (!handler) {
7635
+ endStage(stage, "fail", `No handler for intent '${needle.intent.intent}'`);
7636
+ return failNeedle(needle, obs, "executing", "NO_HANDLER", `No handler registered for intent '${needle.intent.intent}'`);
7637
+ }
7638
+ const handlerCtx = {
7639
+ needle_id: needle.needle_id,
7640
+ actor_id: needle.intent.actor_id,
7641
+ presence_id: needle.presence.presence_id,
7642
+ writ: needle.writ,
7643
+ grants: needle.grants,
7644
+ tps_coordinate: needle.tps_coordinate
7645
+ };
7646
+ let handlerResult;
7647
+ try {
7648
+ handlerResult = await handler(needle.intent, handlerCtx);
7649
+ } catch (err) {
7650
+ const msg = err instanceof Error ? err.message : String(err);
7651
+ endStage(stage, "fail", msg);
7652
+ return failNeedle(needle, obs, "executing", "HANDLER_ERROR", msg);
7653
+ }
7654
+ if (!handlerResult.ok) {
7655
+ endStage(stage, "fail", handlerResult.effect);
7656
+ obs.decision = "DENY";
7657
+ obs.resultCode = handlerResult.effect;
7658
+ obs.statusCode = handlerResult.status_code ?? 400;
7659
+ } else {
7660
+ endStage(stage, "ok");
7661
+ obs.decision = "ALLOW";
7662
+ obs.resultCode = handlerResult.effect;
7663
+ obs.statusCode = handlerResult.status_code ?? 200;
7664
+ }
7665
+ if (handlerResult.data) {
7666
+ obs.facts = { ...obs.facts, ...handlerResult.data };
7667
+ }
7668
+ needle.phase = "observed";
7669
+ finalizeObservation(obs, obs.decision ?? "DENY", obs.statusCode ?? 500, obs.resultCode);
7670
+ needle.observation = obs;
7671
+ const verdict = scoreTruth(obs, expectedOutcome);
7672
+ needle.verdict = verdict;
7673
+ needle.phase = "stitched";
7674
+ stage = startStage(obs, "stitch.form");
7675
+ const receipt = createReceipt(
7676
+ needle.writ,
7677
+ obs.decision ?? "DENY",
7678
+ prevReceipt
7679
+ );
7680
+ needle.receipt = receipt;
7681
+ const newThreadState = updateThreadState(
7682
+ receipt,
7683
+ needle.intent.actor_id
7684
+ );
7685
+ const stitch = formStitch(needle, obs, verdict, receipt);
7686
+ needle.completed_at = Date.now();
7687
+ endStage(stage, "ok");
7688
+ return {
7689
+ ok: handlerResult.ok,
7690
+ needle,
7691
+ stitch,
7692
+ thread_state: newThreadState
7693
+ };
7694
+ }
7695
+ function failNeedle(needle, obs, phase, code, message) {
7696
+ needle.phase = "failed";
7697
+ needle.error = { phase, code, message };
7698
+ needle.completed_at = Date.now();
7699
+ obs.decision = obs.decision ?? "DENY";
7700
+ obs.statusCode = obs.statusCode ?? 500;
7701
+ finalizeObservation(obs, obs.decision, obs.statusCode, obs.resultCode);
7702
+ needle.observation = obs;
7703
+ const verdict = scoreTruth(obs);
7704
+ needle.verdict = verdict;
7705
+ return {
7706
+ ok: false,
7707
+ needle
7708
+ };
7709
+ }
7710
+ var import_crypto10;
7711
+ var init_needle_engine = __esm({
7712
+ "src/needle/needle.engine.ts"() {
7713
+ import_crypto10 = require("crypto");
7714
+ init_axis_observation();
7715
+ init_truth_scoring();
7716
+ init_loom_engine();
7717
+ init_axis_sensor();
7718
+ }
7719
+ });
7720
+
7721
+ // src/needle/knot.engine.ts
7722
+ function openKnot(params) {
7723
+ const isIrreversible = params.type === "irreversible";
7724
+ return {
7725
+ knot_id: `knot_${(0, import_crypto11.randomBytes)(16).toString("hex")}`,
7726
+ type: params.type,
7727
+ status: "open",
7728
+ stitch_ids: [],
7729
+ thread_id: params.thread_id,
7730
+ tps_anchor: params.tps_anchor,
7731
+ irreversible: isIrreversible,
7732
+ capsule_id: params.capsule_id,
7733
+ law_ref: params.law_ref,
7734
+ branch_ids: [],
7735
+ required_count: params.required_count,
7736
+ all_or_nothing: params.all_or_nothing ?? (params.type === "authority" || isIrreversible),
7737
+ actor_id: params.actor_id,
7738
+ created_at: Date.now()
7739
+ };
7740
+ }
7741
+ function addStitchToKnot(knot, stitch) {
7742
+ if (knot.status !== "open") {
7743
+ return `Knot ${knot.knot_id} is ${knot.status}, cannot add stitches`;
7744
+ }
7745
+ if (stitch.thread_id !== knot.thread_id) {
7746
+ return `Stitch thread ${stitch.thread_id} does not match knot thread ${knot.thread_id}`;
7747
+ }
7748
+ if (knot.stitch_ids.includes(stitch.stitch_id)) {
7749
+ return `Stitch ${stitch.stitch_id} already in knot`;
7750
+ }
7751
+ if (knot.type === "authority" && knot.capsule_id) {
7752
+ if (stitch.observation.capsuleId && stitch.observation.capsuleId !== knot.capsule_id) {
7753
+ return `Stitch capsule ${stitch.observation.capsuleId} does not match knot capsule ${knot.capsule_id}`;
7754
+ }
7755
+ }
7756
+ knot.stitch_ids.push(stitch.stitch_id);
7757
+ return null;
7758
+ }
7759
+ function validateKnot(knot, stitches) {
7760
+ const errors = [];
7761
+ const passedIds = [];
7762
+ const failedIds = [];
7763
+ const stitchMap = new Map(stitches.map((s) => [s.stitch_id, s]));
7764
+ for (const sid of knot.stitch_ids) {
7765
+ const stitch = stitchMap.get(sid);
7766
+ if (!stitch) {
7767
+ failedIds.push(sid);
7768
+ errors.push({
7769
+ code: "KNOT_MISSING_STITCH",
7770
+ message: `Stitch ${sid} not found`,
7771
+ stitch_id: sid
7772
+ });
7773
+ continue;
7774
+ }
7775
+ if (stitch.kind === "torn") {
7776
+ failedIds.push(sid);
7777
+ errors.push({
7778
+ code: "KNOT_TORN_STITCH",
7779
+ message: `Stitch ${sid} is torn (failed/disputed)`,
7780
+ stitch_id: sid
7781
+ });
7782
+ continue;
7783
+ }
7784
+ if (knot.type === "irreversible" && stitch.kind !== "deed") {
7785
+ failedIds.push(sid);
7786
+ errors.push({
7787
+ code: "KNOT_REQUIRES_DEED",
7788
+ message: `Irreversible knot requires deed stitch, got '${stitch.kind}'`,
7789
+ stitch_id: sid
7790
+ });
7791
+ continue;
7792
+ }
7793
+ passedIds.push(sid);
7794
+ }
7795
+ if (knot.required_count !== void 0 && knot.stitch_ids.length < knot.required_count) {
7796
+ errors.push({
7797
+ code: "KNOT_INSUFFICIENT_STITCHES",
7798
+ message: `Knot requires ${knot.required_count} stitches, has ${knot.stitch_ids.length}`
7799
+ });
7800
+ }
7801
+ const allPassed = failedIds.length === 0;
7802
+ 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);
7803
+ return {
7804
+ valid: allPassed && errors.length === 0,
7805
+ passed_stitch_ids: passedIds,
7806
+ failed_stitch_ids: failedIds,
7807
+ can_tie: canTie,
7808
+ errors
7809
+ };
7810
+ }
7811
+ function tieKnot(knot, stitches) {
7812
+ const validation = validateKnot(knot, stitches);
7813
+ if (!validation.can_tie) {
7814
+ return { ...validation, knot };
7815
+ }
7816
+ 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);
7817
+ const witnessPayload = receiptHashes.join(":");
7818
+ knot.witness_hash = (0, import_crypto11.createHash)("sha256").update(witnessPayload).digest("hex");
7819
+ knot.status = "tied";
7820
+ knot.tied_at = Date.now();
7821
+ return { ...validation, knot };
7822
+ }
7823
+ function breakKnot(knot, request) {
7824
+ if (knot.status === "broken") {
7825
+ return { ok: false, error: "Knot is already broken" };
7826
+ }
7827
+ if (knot.status === "open") {
7828
+ knot.status = "broken";
7829
+ knot.broken_at = Date.now();
7830
+ knot.break_reason = request.reason;
7831
+ return { ok: true };
7832
+ }
7833
+ if (knot.status === "tied") {
7834
+ if (!request.reason) {
7835
+ return { ok: false, error: "Breaking a tied knot requires a reason" };
7836
+ }
7837
+ if ((knot.irreversible || knot.type === "law") && !request.override_grant_id) {
7838
+ return {
7839
+ ok: false,
7840
+ error: `Breaking ${knot.type} knot requires override_grant_id from higher authority`
7841
+ };
7842
+ }
7843
+ knot.status = "broken";
7844
+ knot.broken_at = Date.now();
7845
+ knot.break_reason = request.reason;
7846
+ return { ok: true };
7847
+ }
7848
+ return { ok: false, error: `Cannot break knot in status '${knot.status}'` };
7849
+ }
7850
+ function forkFromKnot(knot, branchId, decisionStitchId) {
7851
+ if (knot.status !== "tied" && knot.status !== "open") {
7852
+ return { ok: false, error: `Cannot fork from knot in status '${knot.status}'` };
7853
+ }
7854
+ if (decisionStitchId) {
7855
+ if (!knot.stitch_ids.includes(decisionStitchId)) {
7856
+ return { ok: false, error: `Decision stitch ${decisionStitchId} is not part of this knot` };
7857
+ }
7858
+ knot.decision_stitch_id = decisionStitchId;
7859
+ }
7860
+ knot.branch_ids.push(branchId);
7861
+ knot.status = "forked";
7862
+ return { ok: true };
7863
+ }
7864
+ function isKnotOpen(knot) {
7865
+ return knot.status === "open";
7866
+ }
7867
+ function isPointOfNoReturn(knot) {
7868
+ return knot.irreversible && knot.status === "tied";
7869
+ }
7870
+ function findKnotsForStitch(stitchId, knots) {
7871
+ return knots.filter((k) => k.stitch_ids.includes(stitchId));
7872
+ }
7873
+ function getIrreversibleKnots(knots) {
7874
+ return knots.filter((k) => k.irreversible && k.status === "tied");
7875
+ }
7876
+ function getDecisionPoints(knots) {
7877
+ return knots.filter((k) => k.type === "decision" || k.status === "forked");
7878
+ }
7879
+ var import_crypto11;
7880
+ var init_knot_engine = __esm({
7881
+ "src/needle/knot.engine.ts"() {
7882
+ import_crypto11 = require("crypto");
7883
+ }
7884
+ });
7885
+
7886
+ // src/needle/fabric.engine.ts
7887
+ function createFabric() {
7888
+ return {
7889
+ fabric_id: `fab_${(0, import_crypto12.randomBytes)(16).toString("hex")}`,
7890
+ state_hash: hashState(/* @__PURE__ */ new Map()),
7891
+ cells: /* @__PURE__ */ new Map(),
7892
+ thread_ids: [],
7893
+ stitch_count: 0,
7894
+ knot_count: 0,
7895
+ computed_at: Date.now(),
7896
+ version: 0
7897
+ };
7898
+ }
7899
+ function applyStitch(fabric, stitch, effect) {
7900
+ for (const [key, value] of Object.entries(effect.mutations)) {
7901
+ if (value === null) {
7902
+ fabric.cells.delete(key);
7903
+ } else {
7904
+ const existing = fabric.cells.get(key);
7905
+ if (existing?.locked) {
7906
+ continue;
7907
+ }
7908
+ fabric.cells.set(key, {
7909
+ key,
7910
+ value,
7911
+ last_stitch_id: stitch.stitch_id,
7912
+ last_tps: stitch.tps_coordinate,
7913
+ write_count: (existing?.write_count ?? 0) + 1,
7914
+ locked: false
7915
+ });
7916
+ }
7917
+ }
7918
+ if (!fabric.thread_ids.includes(stitch.thread_id)) {
7919
+ fabric.thread_ids.push(stitch.thread_id);
7920
+ }
7921
+ fabric.stitch_count++;
7922
+ fabric.version++;
7923
+ fabric.projected_at_tps = stitch.tps_coordinate ?? fabric.projected_at_tps;
7924
+ fabric.computed_at = Date.now();
7925
+ fabric.state_hash = hashState(fabric.cells);
7926
+ }
7927
+ function weave(stitches, resolver, knots) {
7928
+ const fabric = createFabric();
7929
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
7930
+ for (const stitch of sorted) {
7931
+ if (stitch.kind === "torn") continue;
7932
+ const effect = resolver(stitch);
7933
+ applyStitch(fabric, stitch, effect);
7934
+ }
7935
+ if (knots) {
7936
+ for (const knot of knots) {
7937
+ if (knot.irreversible && knot.status === "tied") {
7938
+ lockCellsByKnot(fabric, knot, stitches, resolver);
7939
+ fabric.knot_count++;
7940
+ }
7941
+ }
7942
+ }
7943
+ return fabric;
7944
+ }
7945
+ function projectAt(stitches, resolver, tpsFilter, knots) {
7946
+ const filtered = stitches.filter((s) => tpsFilter(s.tps_coordinate));
7947
+ return weave(filtered, resolver, knots);
7948
+ }
7949
+ function lockCellsByKnot(fabric, knot, stitches, resolver) {
7950
+ const knotStitchIds = new Set(knot.stitch_ids);
7951
+ const knotStitches = stitches.filter((s) => knotStitchIds.has(s.stitch_id));
7952
+ for (const stitch of knotStitches) {
7953
+ const effect = resolver(stitch);
7954
+ for (const key of Object.keys(effect.mutations)) {
7955
+ const cell = fabric.cells.get(key);
7956
+ if (cell) {
7957
+ cell.locked = true;
7958
+ cell.locked_by_knot = knot.knot_id;
7959
+ }
7960
+ }
7961
+ }
7962
+ }
7963
+ function lockCells(fabric, keys, knotId) {
7964
+ for (const key of keys) {
7965
+ const cell = fabric.cells.get(key);
7966
+ if (cell) {
7967
+ cell.locked = true;
7968
+ cell.locked_by_knot = knotId;
7969
+ }
7970
+ }
7971
+ }
7972
+ function queryFabric(fabric, query) {
7973
+ let results = [...fabric.cells.values()];
7974
+ if (query.keys) {
7975
+ const keySet = new Set(query.keys);
7976
+ results = results.filter((c) => keySet.has(c.key));
7977
+ }
7978
+ if (query.prefix) {
7979
+ const prefix = query.prefix;
7980
+ results = results.filter((c) => c.key.startsWith(prefix));
7981
+ }
7982
+ if (query.locked_only) {
7983
+ results = results.filter((c) => c.locked);
7984
+ }
7985
+ return results;
7986
+ }
7987
+ function getFabricValue(fabric, key) {
7988
+ return fabric.cells.get(key)?.value;
7989
+ }
7990
+ function diffFabrics(a, b) {
7991
+ const entries = [];
7992
+ let added = 0;
7993
+ let modified = 0;
7994
+ let deleted = 0;
7995
+ for (const [key, cellB] of b.cells) {
7996
+ const cellA = a.cells.get(key);
7997
+ if (!cellA) {
7998
+ entries.push({
7999
+ key,
8000
+ kind: "added",
8001
+ after: cellB.value,
8002
+ caused_by_stitch: cellB.last_stitch_id
8003
+ });
8004
+ added++;
8005
+ } else if (JSON.stringify(cellA.value) !== JSON.stringify(cellB.value)) {
8006
+ entries.push({
8007
+ key,
8008
+ kind: "modified",
8009
+ before: cellA.value,
8010
+ after: cellB.value,
8011
+ caused_by_stitch: cellB.last_stitch_id
8012
+ });
8013
+ modified++;
8014
+ }
8015
+ }
8016
+ for (const [key, cellA] of a.cells) {
8017
+ if (!b.cells.has(key)) {
8018
+ entries.push({
8019
+ key,
8020
+ kind: "deleted",
8021
+ before: cellA.value
8022
+ });
8023
+ deleted++;
8024
+ }
8025
+ }
8026
+ return {
8027
+ from_fabric_id: a.fabric_id,
8028
+ to_fabric_id: b.fabric_id,
8029
+ entries,
8030
+ added_count: added,
8031
+ modified_count: modified,
8032
+ deleted_count: deleted
8033
+ };
8034
+ }
8035
+ function hashState(cells) {
8036
+ const keys = [...cells.keys()].sort();
8037
+ const payload = keys.map((k) => `${k}=${JSON.stringify(cells.get(k).value)}`).join("\n");
8038
+ return (0, import_crypto12.createHash)("sha256").update(payload).digest("hex");
8039
+ }
8040
+ var import_crypto12;
8041
+ var init_fabric_engine = __esm({
8042
+ "src/needle/fabric.engine.ts"() {
8043
+ import_crypto12 = require("crypto");
8044
+ }
8045
+ });
8046
+
8047
+ // src/needle/pattern.engine.ts
8048
+ function detectSequencePatterns(stitches, windowSize, minOccurrences) {
8049
+ if (stitches.length < windowSize || windowSize < 2) return [];
8050
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
8051
+ const sequenceCounts = /* @__PURE__ */ new Map();
8052
+ for (let i = 0; i <= sorted.length - windowSize; i++) {
8053
+ const window = sorted.slice(i, i + windowSize);
8054
+ const key = window.map((s) => s.intent).join("\u2192");
8055
+ const ids = window.map((s) => s.stitch_id);
8056
+ const existing = sequenceCounts.get(key);
8057
+ if (existing) {
8058
+ existing.count++;
8059
+ existing.stitch_ids.push(ids);
8060
+ } else {
8061
+ sequenceCounts.set(key, { count: 1, stitch_ids: [ids] });
8062
+ }
8063
+ }
8064
+ const patterns = [];
8065
+ const now = Date.now();
8066
+ for (const [key, data] of sequenceCounts) {
8067
+ if (data.count < minOccurrences) continue;
8068
+ const intents = key.split("\u2192");
8069
+ const confidence = Math.min(data.count / (minOccurrences * 2), 1);
8070
+ patterns.push({
8071
+ pattern_id: `pat_seq_${(0, import_crypto13.randomBytes)(8).toString("hex")}`,
8072
+ kind: "sequence",
8073
+ name: `Sequence: ${intents.join(" \u2192 ")}`,
8074
+ signature: {
8075
+ intent_sequence: intents,
8076
+ min_length: windowSize,
8077
+ max_length: windowSize
8078
+ },
8079
+ confidence,
8080
+ occurrence_count: data.count,
8081
+ first_seen_at: now,
8082
+ last_seen_at: now,
8083
+ seen_in_threads: [...new Set(
8084
+ data.stitch_ids.flatMap(
8085
+ (ids) => ids.map((id) => sorted.find((s) => s.stitch_id === id)?.thread_id).filter(Boolean)
8086
+ )
8087
+ )],
8088
+ classification: "unclassified"
8089
+ });
8090
+ }
8091
+ return patterns;
8092
+ }
8093
+ function detectKnotPatterns(knots, minOccurrences) {
8094
+ const groups = /* @__PURE__ */ new Map();
8095
+ for (const knot of knots) {
8096
+ if (knot.status !== "tied") continue;
8097
+ const key = `${knot.type}:${knot.stitch_ids.length}`;
8098
+ const group = groups.get(key) ?? [];
8099
+ group.push(knot);
8100
+ groups.set(key, group);
8101
+ }
8102
+ const patterns = [];
8103
+ const now = Date.now();
8104
+ for (const [key, group] of groups) {
8105
+ if (group.length < minOccurrences) continue;
8106
+ const [type, sizeStr] = key.split(":");
8107
+ const size = parseInt(sizeStr, 10);
8108
+ const confidence = Math.min(group.length / (minOccurrences * 2), 1);
8109
+ patterns.push({
8110
+ pattern_id: `pat_knot_${(0, import_crypto13.randomBytes)(8).toString("hex")}`,
8111
+ kind: "knot",
8112
+ name: `Knot: ${type} (${size} stitches)`,
8113
+ signature: {
8114
+ knot_type: type,
8115
+ knot_size: size
8116
+ },
8117
+ confidence,
8118
+ occurrence_count: group.length,
8119
+ first_seen_at: now,
8120
+ last_seen_at: now,
8121
+ seen_in_threads: [...new Set(group.map((k) => k.thread_id))],
8122
+ classification: "unclassified"
8123
+ });
8124
+ }
8125
+ return patterns;
8126
+ }
8127
+ function matchPatterns(stitches, patterns) {
8128
+ const sorted = [...stitches].sort((a, b) => a.sequence - b.sequence);
8129
+ const matches = [];
8130
+ const now = Date.now();
8131
+ for (const pattern of patterns) {
8132
+ if (pattern.kind === "sequence" && pattern.signature.intent_sequence) {
8133
+ const seq = pattern.signature.intent_sequence;
8134
+ const seqLen = seq.length;
8135
+ for (let i = 0; i <= sorted.length - seqLen; i++) {
8136
+ const window = sorted.slice(i, i + seqLen);
8137
+ const windowIntents = window.map((s) => s.intent);
8138
+ if (windowIntents.every((intent, idx) => intent === seq[idx])) {
8139
+ matches.push({
8140
+ pattern_id: pattern.pattern_id,
8141
+ matched_stitch_ids: window.map((s) => s.stitch_id),
8142
+ match_score: 1,
8143
+ thread_id: window[0].thread_id,
8144
+ detected_at: now
8145
+ });
8146
+ }
8147
+ }
8148
+ }
8149
+ }
8150
+ return matches;
8151
+ }
8152
+ function recordOccurrence(pattern, threadId) {
8153
+ pattern.occurrence_count++;
8154
+ pattern.last_seen_at = Date.now();
8155
+ pattern.confidence = 1 - 1 / (1 + pattern.occurrence_count * 0.5);
8156
+ if (!pattern.seen_in_threads.includes(threadId)) {
8157
+ pattern.seen_in_threads.push(threadId);
8158
+ }
8159
+ }
8160
+ function detectAnomalies(recentStitches, knownPatterns, threshold = 0.7) {
8161
+ const anomalies = [];
8162
+ const sorted = [...recentStitches].sort((a, b) => a.sequence - b.sequence);
8163
+ const now = Date.now();
8164
+ for (const pattern of knownPatterns) {
8165
+ if (pattern.kind !== "sequence" || !pattern.signature.intent_sequence) continue;
8166
+ if (pattern.confidence < threshold) continue;
8167
+ const seq = pattern.signature.intent_sequence;
8168
+ if (sorted.length >= 1 && sorted.length < seq.length) {
8169
+ const partialMatch = sorted.every(
8170
+ (s, i) => i < seq.length && s.intent === seq[i]
8171
+ );
8172
+ if (partialMatch) {
8173
+ const expectedNext = seq[sorted.length];
8174
+ const lastStitch = sorted[sorted.length - 1];
8175
+ if (pattern.occurrence_count >= 3) {
8176
+ anomalies.push({
8177
+ pattern_id: `pat_anom_${(0, import_crypto13.randomBytes)(8).toString("hex")}`,
8178
+ kind: "anomaly",
8179
+ name: `Incomplete: ${pattern.name}`,
8180
+ description: `Expected '${expectedNext}' after '${lastStitch.intent}' based on pattern '${pattern.name}'`,
8181
+ signature: pattern.signature,
8182
+ confidence: pattern.confidence * 0.8,
8183
+ occurrence_count: 1,
8184
+ first_seen_at: now,
8185
+ last_seen_at: now,
8186
+ seen_in_threads: [lastStitch.thread_id],
8187
+ classification: "anomalous"
8188
+ });
8189
+ }
8190
+ }
8191
+ }
8192
+ }
8193
+ return anomalies;
8194
+ }
8195
+ var import_crypto13, InMemoryPatternStore;
8196
+ var init_pattern_engine = __esm({
8197
+ "src/needle/pattern.engine.ts"() {
8198
+ import_crypto13 = require("crypto");
8199
+ InMemoryPatternStore = class {
8200
+ constructor() {
8201
+ this.patterns = /* @__PURE__ */ new Map();
8202
+ }
8203
+ save(pattern) {
8204
+ this.patterns.set(pattern.pattern_id, pattern);
8205
+ }
8206
+ get(patternId) {
8207
+ return this.patterns.get(patternId);
8208
+ }
8209
+ findByKind(kind) {
8210
+ return [...this.patterns.values()].filter((p) => p.kind === kind);
8211
+ }
8212
+ findByIntent(intent) {
8213
+ return [...this.patterns.values()].filter(
8214
+ (p) => p.signature.intent_sequence?.includes(intent)
8215
+ );
8216
+ }
8217
+ all() {
8218
+ return [...this.patterns.values()];
8219
+ }
8220
+ };
8221
+ }
8222
+ });
8223
+
8224
+ // src/sensors/tps.sensor.ts
8225
+ var require_tps_sensor = __commonJS({
8226
+ "src/sensors/tps.sensor.ts"(exports2) {
8227
+ "use strict";
8228
+ var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
8229
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8230
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8231
+ 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;
8232
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8233
+ };
8234
+ var __metadata = exports2 && exports2.__metadata || function(k, v) {
8235
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8236
+ };
8237
+ Object.defineProperty(exports2, "__esModule", { value: true });
8238
+ exports2.TpsSensor = void 0;
8239
+ var common_1 = require("@nestjs/common");
8240
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8241
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8242
+ var TPS_EPOCH_MS = 9343548e5;
8243
+ function parseINotation(tps) {
8244
+ if (!tps.startsWith("i"))
8245
+ return null;
8246
+ const num = Number(tps.slice(1));
8247
+ if (!Number.isFinite(num))
8248
+ return null;
8249
+ return TPS_EPOCH_MS + num;
8250
+ }
8251
+ var TpsSensor2 = class TpsSensor {
8252
+ constructor(options = {}) {
8253
+ this.name = "TpsSensor";
8254
+ this.order = sensor_bands_1.BAND.POLICY + 2;
8255
+ this.maxDriftMs = options.maxDriftMs ?? 3e4;
8256
+ this.resolver = options.resolver ?? parseINotation;
8257
+ }
8258
+ supports(input) {
8259
+ const tps = input.metadata?.tps_coordinate ?? input.metadata?.tps ?? input.packet?.tps;
8260
+ return typeof tps === "string" && tps.length > 0;
8261
+ }
8262
+ async run(input) {
8263
+ const tps = input.metadata?.tps_coordinate ?? input.metadata?.tps ?? input.packet?.tps;
8264
+ const resolved = this.resolver(tps);
8265
+ if (resolved === null) {
8266
+ return {
8267
+ allow: false,
8268
+ riskScore: 80,
8269
+ reasons: [`TPS coordinate '${tps}' is structurally invalid`],
8270
+ code: "TPS_INVALID_FORMAT"
8271
+ };
8272
+ }
8273
+ const now = Date.now();
8274
+ const drift = Math.abs(now - resolved);
8275
+ if (drift > this.maxDriftMs) {
8276
+ const direction = resolved > now ? "future" : "past";
8277
+ return {
8278
+ allow: false,
8279
+ riskScore: 70,
8280
+ reasons: [
8281
+ `TPS drift ${drift}ms exceeds max ${this.maxDriftMs}ms (${direction})`
8282
+ ],
8283
+ code: "TPS_DRIFT_EXCEEDED",
8284
+ tags: { tpsDriftMs: drift, tpsDirection: direction }
8285
+ };
8286
+ }
8287
+ return {
8288
+ allow: true,
8289
+ riskScore: 0,
8290
+ reasons: [],
8291
+ tags: {
8292
+ tpsResolved: resolved,
8293
+ tpsDriftMs: drift
8294
+ }
8295
+ };
8296
+ }
8297
+ };
8298
+ exports2.TpsSensor = TpsSensor2;
8299
+ exports2.TpsSensor = TpsSensor2 = __decorate([
8300
+ (0, sensor_decorator_1.Sensor)(),
8301
+ (0, common_1.Injectable)(),
8302
+ __metadata("design:paramtypes", [Object])
8303
+ ], TpsSensor2);
8304
+ }
8305
+ });
8306
+
8307
+ // src/sensors/risk-gate.sensor.ts
8308
+ var require_risk_gate_sensor = __commonJS({
8309
+ "src/sensors/risk-gate.sensor.ts"(exports2) {
8310
+ "use strict";
8311
+ var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
8312
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8313
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8314
+ 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;
8315
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8316
+ };
8317
+ var __metadata = exports2 && exports2.__metadata || function(k, v) {
8318
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8319
+ };
8320
+ Object.defineProperty(exports2, "__esModule", { value: true });
8321
+ exports2.RiskGateSensor = void 0;
8322
+ var common_1 = require("@nestjs/common");
8323
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8324
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8325
+ var risk_1 = (init_risk(), __toCommonJS(risk_exports));
8326
+ var SEVERITY_WEIGHT = {
8327
+ low: 10,
8328
+ medium: 25,
8329
+ high: 50,
8330
+ critical: 100
8331
+ };
8332
+ var RiskGateSensor2 = class RiskGateSensor {
8333
+ constructor(options) {
8334
+ this.name = "RiskGateSensor";
8335
+ this.order = sensor_bands_1.BAND.BUSINESS + 10;
8336
+ this.collectors = options.collectors;
8337
+ this.denyThreshold = options.denyThreshold ?? 75;
8338
+ this.flagThreshold = options.flagThreshold ?? 40;
8339
+ }
8340
+ async run(input) {
8341
+ const results = await Promise.all(this.collectors.map((c) => c(input)));
8342
+ const signals = results.flat();
8343
+ let totalWeight = 0;
8344
+ let weightedSum = 0;
8345
+ for (const signal of signals) {
8346
+ const w = SEVERITY_WEIGHT[signal.severity];
8347
+ totalWeight += 1;
8348
+ weightedSum += w;
8349
+ }
8350
+ const aggregateScore = totalWeight > 0 ? Math.min(100, Math.round(weightedSum / totalWeight)) : 0;
8351
+ const evaluation = this.evaluate(aggregateScore, signals);
8352
+ input.metadata = {
8353
+ ...input.metadata ?? {},
8354
+ riskEvaluation: evaluation
8355
+ };
8356
+ if (evaluation.decision === risk_1.RiskDecision.DENY) {
8357
+ return {
8358
+ allow: false,
8359
+ riskScore: aggregateScore,
8360
+ reasons: signals.map((s) => s.message),
8361
+ code: "RISK_GATE_DENY",
8362
+ tags: { riskDecision: evaluation.decision, signalCount: signals.length }
8363
+ };
8364
+ }
8365
+ if (evaluation.decision === risk_1.RiskDecision.THROTTLE) {
8366
+ return {
8367
+ allow: false,
8368
+ riskScore: aggregateScore,
8369
+ reasons: signals.map((s) => s.message),
8370
+ code: "RISK_GATE_THROTTLE",
8371
+ retryAfterMs: evaluation.retryAfterMs,
8372
+ tags: { riskDecision: evaluation.decision, signalCount: signals.length }
8373
+ };
8374
+ }
8375
+ return {
8376
+ allow: true,
8377
+ riskScore: aggregateScore,
8378
+ reasons: signals.filter((s) => s.severity === "medium" || s.severity === "high").map((s) => s.message),
8379
+ tags: {
8380
+ riskDecision: evaluation.decision,
8381
+ signalCount: signals.length
8382
+ }
8383
+ };
8384
+ }
8385
+ evaluate(score, signals) {
8386
+ const hasCritical = signals.some((s) => s.severity === "critical");
8387
+ if (hasCritical) {
8388
+ return {
8389
+ decision: risk_1.RiskDecision.DENY,
8390
+ reason: "Critical risk signal detected",
8391
+ confidence: 1,
8392
+ signals
8393
+ };
8394
+ }
8395
+ if (score >= this.denyThreshold) {
8396
+ return {
8397
+ decision: risk_1.RiskDecision.DENY,
8398
+ reason: `Aggregate risk score ${score} exceeds deny threshold ${this.denyThreshold}`,
8399
+ confidence: score / 100,
8400
+ signals
8401
+ };
8402
+ }
8403
+ if (score >= this.flagThreshold) {
8404
+ return {
8405
+ decision: risk_1.RiskDecision.STEP_UP,
8406
+ reason: `Aggregate risk score ${score} exceeds flag threshold ${this.flagThreshold}`,
8407
+ confidence: score / 100,
8408
+ signals
8409
+ };
8410
+ }
8411
+ return {
8412
+ decision: risk_1.RiskDecision.ALLOW,
8413
+ confidence: 1 - score / 100,
8414
+ signals
8415
+ };
8416
+ }
8417
+ };
8418
+ exports2.RiskGateSensor = RiskGateSensor2;
8419
+ exports2.RiskGateSensor = RiskGateSensor2 = __decorate([
8420
+ (0, sensor_decorator_1.Sensor)(),
8421
+ (0, common_1.Injectable)(),
8422
+ __metadata("design:paramtypes", [Object])
8423
+ ], RiskGateSensor2);
8424
+ }
8425
+ });
8426
+
8427
+ // src/sensors/tickauth.sensor.ts
8428
+ var require_tickauth_sensor = __commonJS({
8429
+ "src/sensors/tickauth.sensor.ts"(exports2) {
8430
+ "use strict";
8431
+ var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
8432
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8433
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8434
+ 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;
8435
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8436
+ };
8437
+ var __metadata = exports2 && exports2.__metadata || function(k, v) {
8438
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8439
+ };
8440
+ Object.defineProperty(exports2, "__esModule", { value: true });
8441
+ exports2.TickAuthSensor = void 0;
8442
+ var common_1 = require("@nestjs/common");
8443
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
8444
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
8445
+ var TickAuthSensor2 = class TickAuthSensor {
8446
+ constructor(options = {}) {
8447
+ this.name = "TickAuthSensor";
8448
+ this.order = sensor_bands_1.BAND.IDENTITY + 40;
8449
+ this.verifier = options.verifier;
8450
+ this.matchIntent = options.matchIntent ?? true;
8451
+ this.acceptTypes = options.acceptTypes?.length ? new Set(options.acceptTypes) : null;
8452
+ }
8453
+ supports(input) {
8454
+ return !!(input.metadata?.capsule || input.metadata?.tickauthCapsule || input.metadata?.cceEnvelope?.capsule);
8455
+ }
8456
+ async run(input) {
8457
+ const capsule = input.metadata?.capsule ?? input.metadata?.tickauthCapsule ?? input.metadata?.cceEnvelope?.capsule;
8458
+ if (!capsule) {
8459
+ return {
8460
+ allow: false,
8461
+ riskScore: 90,
8462
+ reasons: ["TickAuth capsule not found"],
8463
+ code: "TICKAUTH_MISSING"
8464
+ };
8465
+ }
8466
+ if (!capsule.capsule_id || typeof capsule.capsule_id !== "string") {
8467
+ return {
8468
+ allow: false,
8469
+ riskScore: 100,
8470
+ reasons: ["TickAuth capsule has no valid capsule_id"],
8471
+ code: "TICKAUTH_INVALID_ID"
8472
+ };
8473
+ }
8474
+ const status = capsule.verification?.status;
8475
+ if (status && status !== "approved") {
8476
+ return {
8477
+ allow: false,
8478
+ riskScore: 100,
8479
+ reasons: [
8480
+ `TickAuth capsule status is '${status}'${capsule.verification?.reason ? `: ${capsule.verification.reason}` : ""}`
8481
+ ],
8482
+ code: `TICKAUTH_STATUS_${status.toUpperCase()}`
8483
+ };
8484
+ }
8485
+ if (this.acceptTypes && capsule.capsule_type) {
8486
+ if (!this.acceptTypes.has(capsule.capsule_type)) {
8487
+ return {
8488
+ allow: false,
8489
+ riskScore: 80,
8490
+ reasons: [
8491
+ `TickAuth capsule type '${capsule.capsule_type}' is not in accept list`
8492
+ ],
8493
+ code: "TICKAUTH_TYPE_REJECTED"
8494
+ };
8495
+ }
8496
+ }
8497
+ if (this.matchIntent && input.intent && capsule.intent) {
8498
+ if (capsule.intent !== input.intent) {
8499
+ return {
8500
+ allow: false,
8501
+ riskScore: 80,
8502
+ reasons: [
8503
+ `TickAuth capsule intent '${capsule.intent}' does not match AXIS intent '${input.intent}'`
8504
+ ],
8505
+ code: "TICKAUTH_INTENT_MISMATCH"
8506
+ };
8507
+ }
8508
+ }
8509
+ if (this.verifier) {
8510
+ const error = await this.verifier(capsule, input);
8511
+ if (error) {
8512
+ return {
8513
+ allow: false,
8514
+ riskScore: 90,
8515
+ reasons: [`TickAuth verification failed: ${error}`],
8516
+ code: "TICKAUTH_VERIFY_FAILED"
8517
+ };
8518
+ }
8519
+ }
8520
+ return {
8521
+ allow: true,
8522
+ riskScore: 0,
8523
+ reasons: [],
8524
+ tags: {
8525
+ tickauthCapsuleId: capsule.capsule_id,
8526
+ tickauthMode: capsule.mode,
8527
+ tickauthSingleUse: capsule.single_use
8528
+ }
8529
+ };
8530
+ }
8531
+ };
8532
+ exports2.TickAuthSensor = TickAuthSensor2;
8533
+ exports2.TickAuthSensor = TickAuthSensor2 = __decorate([
8534
+ (0, sensor_decorator_1.Sensor)(),
8535
+ (0, common_1.Injectable)(),
8536
+ __metadata("design:paramtypes", [Object])
8537
+ ], TickAuthSensor2);
6202
8538
  }
6203
8539
  });
6204
8540
 
@@ -7010,95 +9346,18 @@ var init_cce = __esm({
7010
9346
  // src/core/index.ts
7011
9347
  var core_exports = {};
7012
9348
  __export(core_exports, {
7013
- AXIS_MAGIC: () => import_axis_protocol2.AXIS_MAGIC,
7014
- AXIS_VERSION: () => import_axis_protocol2.AXIS_VERSION,
7015
9349
  AxisError: () => AxisError,
7016
9350
  AxisFrameZ: () => AxisFrameZ,
7017
- AxisMediaTypes: () => AxisMediaTypes,
7018
- BodyProfile: () => import_axis_protocol2.BodyProfile,
7019
- ERR_BAD_SIGNATURE: () => import_axis_protocol2.ERR_BAD_SIGNATURE,
7020
- ERR_CONTRACT_VIOLATION: () => import_axis_protocol2.ERR_CONTRACT_VIOLATION,
7021
- ERR_INVALID_PACKET: () => import_axis_protocol2.ERR_INVALID_PACKET,
7022
- ERR_REPLAY_DETECTED: () => import_axis_protocol2.ERR_REPLAY_DETECTED,
7023
- FLAG_BODY_TLV: () => import_axis_protocol2.FLAG_BODY_TLV,
7024
- FLAG_CHAIN_REQ: () => import_axis_protocol2.FLAG_CHAIN_REQ,
7025
- FLAG_HAS_WITNESS: () => import_axis_protocol2.FLAG_HAS_WITNESS,
7026
- MAX_BODY_LEN: () => import_axis_protocol2.MAX_BODY_LEN,
7027
- MAX_FRAME_LEN: () => import_axis_protocol2.MAX_FRAME_LEN,
7028
- MAX_HDR_LEN: () => import_axis_protocol2.MAX_HDR_LEN,
7029
- MAX_SIG_LEN: () => import_axis_protocol2.MAX_SIG_LEN,
7030
- NCERT_ALG: () => import_axis_protocol2.NCERT_ALG,
7031
- NCERT_EXP: () => import_axis_protocol2.NCERT_EXP,
7032
- NCERT_ISSUER_KID: () => import_axis_protocol2.NCERT_ISSUER_KID,
7033
- NCERT_KID: () => import_axis_protocol2.NCERT_KID,
7034
- NCERT_NBF: () => import_axis_protocol2.NCERT_NBF,
7035
- NCERT_NODE_ID: () => import_axis_protocol2.NCERT_NODE_ID,
7036
- NCERT_PAYLOAD: () => import_axis_protocol2.NCERT_PAYLOAD,
7037
- NCERT_PUB: () => import_axis_protocol2.NCERT_PUB,
7038
- NCERT_SCOPE: () => import_axis_protocol2.NCERT_SCOPE,
7039
- NCERT_SIG: () => import_axis_protocol2.NCERT_SIG,
7040
- PROOF_CAPSULE: () => import_axis_protocol2.PROOF_CAPSULE,
7041
- PROOF_JWT: () => import_axis_protocol2.PROOF_JWT,
7042
- PROOF_LOOM: () => import_axis_protocol2.PROOF_LOOM,
7043
- PROOF_MTLS: () => import_axis_protocol2.PROOF_MTLS,
7044
- PROOF_NONE: () => import_axis_protocol2.PROOF_NONE,
7045
- PROOF_WITNESS: () => import_axis_protocol2.PROOF_WITNESS,
7046
- ProofType: () => import_axis_protocol2.ProofType,
7047
- TLV: () => import_axis_protocol.TLV,
7048
- TLV_ACTOR_ID: () => import_axis_protocol2.TLV_ACTOR_ID,
7049
- TLV_AUD: () => import_axis_protocol2.TLV_AUD,
7050
- TLV_BODY_ARR: () => import_axis_protocol2.TLV_BODY_ARR,
7051
- TLV_BODY_OBJ: () => import_axis_protocol2.TLV_BODY_OBJ,
7052
- TLV_CAPSULE: () => import_axis_protocol2.TLV_CAPSULE,
7053
- TLV_EFFECT: () => import_axis_protocol2.TLV_EFFECT,
7054
- TLV_ERROR_CODE: () => import_axis_protocol2.TLV_ERROR_CODE,
7055
- TLV_ERROR_MSG: () => import_axis_protocol2.TLV_ERROR_MSG,
7056
- TLV_INDEX: () => import_axis_protocol2.TLV_INDEX,
7057
- TLV_INTENT: () => import_axis_protocol2.TLV_INTENT,
7058
- TLV_KID: () => import_axis_protocol2.TLV_KID,
7059
- TLV_LOOM_PRESENCE_ID: () => import_axis_protocol2.TLV_LOOM_PRESENCE_ID,
7060
- TLV_LOOM_THREAD_HASH: () => import_axis_protocol2.TLV_LOOM_THREAD_HASH,
7061
- TLV_LOOM_WRIT: () => import_axis_protocol2.TLV_LOOM_WRIT,
7062
- TLV_NODE: () => import_axis_protocol2.TLV_NODE,
7063
- TLV_NODE_CERT_HASH: () => import_axis_protocol2.TLV_NODE_CERT_HASH,
7064
- TLV_NODE_KID: () => import_axis_protocol2.TLV_NODE_KID,
7065
- TLV_NONCE: () => import_axis_protocol2.TLV_NONCE,
7066
- TLV_OFFSET: () => import_axis_protocol2.TLV_OFFSET,
7067
- TLV_OK: () => import_axis_protocol2.TLV_OK,
7068
- TLV_PID: () => import_axis_protocol2.TLV_PID,
7069
- TLV_PREV_HASH: () => import_axis_protocol2.TLV_PREV_HASH,
7070
- TLV_PROOF_REF: () => import_axis_protocol2.TLV_PROOF_REF,
7071
- TLV_PROOF_TYPE: () => import_axis_protocol2.TLV_PROOF_TYPE,
7072
- TLV_REALM: () => import_axis_protocol2.TLV_REALM,
7073
- TLV_RECEIPT_HASH: () => import_axis_protocol2.TLV_RECEIPT_HASH,
7074
- TLV_RID: () => import_axis_protocol2.TLV_RID,
7075
- TLV_SHA256_CHUNK: () => import_axis_protocol2.TLV_SHA256_CHUNK,
7076
- TLV_TRACE_ID: () => import_axis_protocol2.TLV_TRACE_ID,
7077
- TLV_TS: () => import_axis_protocol2.TLV_TS,
7078
- TLV_UPLOAD_ID: () => import_axis_protocol2.TLV_UPLOAD_ID,
7079
9351
  computeReceiptHash: () => computeReceiptHash,
7080
9352
  computeSignaturePayload: () => computeSignaturePayload,
7081
- decodeArray: () => import_axis_protocol.decodeArray,
7082
- decodeFrame: () => decodeFrame,
7083
- decodeObject: () => import_axis_protocol.decodeObject,
7084
- decodeTLVs: () => import_axis_protocol.decodeTLVs,
7085
- decodeTLVsList: () => import_axis_protocol.decodeTLVsList,
7086
- decodeVarint: () => import_axis_protocol3.decodeVarint,
7087
- encodeFrame: () => encodeFrame,
7088
- encodeTLVs: () => import_axis_protocol.encodeTLVs,
7089
- encodeVarint: () => import_axis_protocol3.encodeVarint,
7090
9353
  generateEd25519KeyPair: () => generateEd25519KeyPair,
7091
- getSignTarget: () => getSignTarget,
7092
9354
  sha256: () => sha2564,
7093
9355
  signFrame: () => signFrame,
7094
- varintLength: () => import_axis_protocol3.varintLength,
7095
9356
  verifyFrameSignature: () => verifyFrameSignature
7096
9357
  });
7097
9358
  var init_core = __esm({
7098
9359
  "src/core/index.ts"() {
7099
- init_constants();
7100
- init_varint();
7101
- init_tlv();
9360
+ __reExport(core_exports, require("@nextera.one/axis-protocol"));
7102
9361
  init_axis_bin();
7103
9362
  init_signature();
7104
9363
  init_axis_error();
@@ -7331,14 +9590,6 @@ __export(decorators_exports, {
7331
9590
  SENSOR_METADATA_KEY: () => SENSOR_METADATA_KEY,
7332
9591
  Sensitivity: () => Sensitivity,
7333
9592
  Sensor: () => Sensor,
7334
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
7335
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
7336
- TlvEnum: () => TlvEnum,
7337
- TlvField: () => TlvField,
7338
- TlvMinLen: () => TlvMinLen,
7339
- TlvRange: () => TlvRange,
7340
- TlvUtf8Pattern: () => TlvUtf8Pattern,
7341
- TlvValidate: () => TlvValidate,
7342
9593
  Witness: () => Witness,
7343
9594
  mergeCapsulePolicyOptions: () => mergeCapsulePolicyOptions,
7344
9595
  normalizeCapsulePolicyOptions: () => normalizeCapsulePolicyOptions
@@ -7356,7 +9607,7 @@ var init_decorators = __esm({
7356
9607
  init_intent_decorator();
7357
9608
  init_observer_decorator();
7358
9609
  init_sensor_decorator();
7359
- init_tlv_field_decorator();
9610
+ __reExport(decorators_exports, __toESM(require_tlv_field_decorator()));
7360
9611
  }
7361
9612
  });
7362
9613
 
@@ -7457,6 +9708,25 @@ var init_engine = __esm({
7457
9708
  }
7458
9709
  });
7459
9710
 
9711
+ // src/idel/idel.types.ts
9712
+ var init_idel_types = __esm({
9713
+ "src/idel/idel.types.ts"() {
9714
+ }
9715
+ });
9716
+
9717
+ // src/idel/index.ts
9718
+ var idel_exports = {};
9719
+ __export(idel_exports, {
9720
+ IdelCompiler: () => IdelCompiler,
9721
+ IdelSchemaRegistry: () => IdelSchemaRegistry
9722
+ });
9723
+ var init_idel = __esm({
9724
+ "src/idel/index.ts"() {
9725
+ init_idel_types();
9726
+ init_idel_compiler();
9727
+ }
9728
+ });
9729
+
7460
9730
  // src/loom/index.ts
7461
9731
  var loom_exports = {};
7462
9732
  __export(loom_exports, {
@@ -7466,11 +9736,98 @@ __export(loom_exports, {
7466
9736
  TLV_WRIT: () => import_axis_protocol2.TLV_LOOM_WRIT,
7467
9737
  canonicalizeGrant: () => canonicalizeGrant,
7468
9738
  canonicalizeWrit: () => canonicalizeWrit,
7469
- deriveAnchorReflection: () => deriveAnchorReflection
9739
+ createGrant: () => createGrant,
9740
+ createPresenceChallenge: () => createPresenceChallenge,
9741
+ createReceipt: () => createReceipt,
9742
+ createRevocation: () => createRevocation,
9743
+ createWrit: () => createWrit,
9744
+ deriveAnchorReflection: () => deriveAnchorReflection,
9745
+ executeLoomPipeline: () => executeLoomPipeline,
9746
+ getGrantStatus: () => getGrantStatus,
9747
+ getPresenceStatus: () => getPresenceStatus,
9748
+ grantCoversAction: () => grantCoversAction,
9749
+ isRevoked: () => isRevoked,
9750
+ renewPresence: () => renewPresence,
9751
+ signPresenceChallenge: () => signPresenceChallenge,
9752
+ updateThreadState: () => updateThreadState,
9753
+ validateGrant: () => validateGrant,
9754
+ validateWrit: () => validateWrit,
9755
+ verifyPresenceProof: () => verifyPresenceProof,
9756
+ verifyReceiptChain: () => verifyReceiptChain
7470
9757
  });
7471
9758
  var init_loom = __esm({
7472
9759
  "src/loom/index.ts"() {
7473
9760
  init_loom_types();
9761
+ init_loom_engine();
9762
+ }
9763
+ });
9764
+
9765
+ // src/needle/needle.types.ts
9766
+ var init_needle_types = __esm({
9767
+ "src/needle/needle.types.ts"() {
9768
+ }
9769
+ });
9770
+
9771
+ // src/needle/knot.types.ts
9772
+ var init_knot_types = __esm({
9773
+ "src/needle/knot.types.ts"() {
9774
+ }
9775
+ });
9776
+
9777
+ // src/needle/fabric.types.ts
9778
+ var init_fabric_types = __esm({
9779
+ "src/needle/fabric.types.ts"() {
9780
+ }
9781
+ });
9782
+
9783
+ // src/needle/pattern.types.ts
9784
+ var init_pattern_types = __esm({
9785
+ "src/needle/pattern.types.ts"() {
9786
+ }
9787
+ });
9788
+
9789
+ // src/needle/index.ts
9790
+ var needle_exports = {};
9791
+ __export(needle_exports, {
9792
+ InMemoryPatternStore: () => InMemoryPatternStore,
9793
+ addStitchToKnot: () => addStitchToKnot,
9794
+ applyStitch: () => applyStitch,
9795
+ assembleNeedle: () => assembleNeedle,
9796
+ breakKnot: () => breakKnot,
9797
+ createFabric: () => createFabric,
9798
+ detectAnomalies: () => detectAnomalies,
9799
+ detectKnotPatterns: () => detectKnotPatterns,
9800
+ detectSequencePatterns: () => detectSequencePatterns,
9801
+ diffFabrics: () => diffFabrics,
9802
+ findKnotsForStitch: () => findKnotsForStitch,
9803
+ forkFromKnot: () => forkFromKnot,
9804
+ formStitch: () => formStitch,
9805
+ getDecisionPoints: () => getDecisionPoints,
9806
+ getFabricValue: () => getFabricValue,
9807
+ getIrreversibleKnots: () => getIrreversibleKnots,
9808
+ isKnotOpen: () => isKnotOpen,
9809
+ isPointOfNoReturn: () => isPointOfNoReturn,
9810
+ lockCells: () => lockCells,
9811
+ matchPatterns: () => matchPatterns,
9812
+ openKnot: () => openKnot,
9813
+ projectAt: () => projectAt,
9814
+ queryFabric: () => queryFabric,
9815
+ recordOccurrence: () => recordOccurrence,
9816
+ runNeedlePipeline: () => runNeedlePipeline,
9817
+ tieKnot: () => tieKnot,
9818
+ validateKnot: () => validateKnot,
9819
+ weave: () => weave
9820
+ });
9821
+ var init_needle = __esm({
9822
+ "src/needle/index.ts"() {
9823
+ init_needle_types();
9824
+ init_needle_engine();
9825
+ init_knot_types();
9826
+ init_knot_engine();
9827
+ init_fabric_types();
9828
+ init_fabric_engine();
9829
+ init_pattern_types();
9830
+ init_pattern_engine();
7474
9831
  }
7475
9832
  });
7476
9833
 
@@ -8719,6 +11076,143 @@ var require_intent_registry_sensor = __commonJS({
8719
11076
  }
8720
11077
  });
8721
11078
 
11079
+ // src/sensors/law-evaluation.sensor.ts
11080
+ var require_law_evaluation_sensor = __commonJS({
11081
+ "src/sensors/law-evaluation.sensor.ts"(exports2) {
11082
+ "use strict";
11083
+ var __decorate = exports2 && exports2.__decorate || function(decorators, target, key, desc) {
11084
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11085
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
11086
+ 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;
11087
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
11088
+ };
11089
+ var __metadata = exports2 && exports2.__metadata || function(k, v) {
11090
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11091
+ };
11092
+ var LawEvaluationSensor_1;
11093
+ Object.defineProperty(exports2, "__esModule", { value: true });
11094
+ exports2.LawEvaluationSensor = void 0;
11095
+ var common_1 = require("@nestjs/common");
11096
+ var sensor_decorator_1 = (init_sensor_decorator(), __toCommonJS(sensor_decorator_exports));
11097
+ var sensor_bands_1 = (init_sensor_bands(), __toCommonJS(sensor_bands_exports));
11098
+ var law_1 = (init_law(), __toCommonJS(law_exports));
11099
+ var LawEvaluationSensor = LawEvaluationSensor_1 = class LawEvaluationSensor {
11100
+ constructor(options = {}) {
11101
+ this.options = options;
11102
+ this.logger = new common_1.Logger(LawEvaluationSensor_1.name);
11103
+ this.name = "LawEvaluationSensor";
11104
+ this.order = sensor_bands_1.BAND.POLICY + 5;
11105
+ }
11106
+ supports(input) {
11107
+ return !!this.options.evaluator && !!input.intent;
11108
+ }
11109
+ async run(input) {
11110
+ const evaluator = this.options.evaluator;
11111
+ if (!evaluator) {
11112
+ return { action: "ALLOW" };
11113
+ }
11114
+ const context = (0, law_1.buildAxisLawEvaluationContext)(input);
11115
+ let result;
11116
+ try {
11117
+ result = await evaluator(context);
11118
+ } catch (error) {
11119
+ const message = error instanceof Error ? error.message : "Unknown law evaluation error";
11120
+ this.logger.error(`Law evaluation failed for ${input.intent}: ${message}`);
11121
+ input.metadata = {
11122
+ ...input.metadata ?? {},
11123
+ lawEvaluation: {
11124
+ decision: "deny",
11125
+ reason: "Law evaluation failed",
11126
+ explanation: message
11127
+ }
11128
+ };
11129
+ return {
11130
+ action: "DENY",
11131
+ code: "LAW_EVALUATION_ERROR",
11132
+ reason: message,
11133
+ meta: { lawDecision: "deny" }
11134
+ };
11135
+ }
11136
+ input.metadata = {
11137
+ ...input.metadata ?? {},
11138
+ lawEvaluation: {
11139
+ ...result,
11140
+ context: sanitizeLawContext(context)
11141
+ }
11142
+ };
11143
+ if (result.decision === "allow") {
11144
+ return {
11145
+ allow: true,
11146
+ riskScore: 0,
11147
+ reasons: result.reason ? [result.reason] : [],
11148
+ tags: {
11149
+ lawDecision: "allow",
11150
+ ...result.applicable ? { lawApplicableArticles: result.applicable.length } : {}
11151
+ },
11152
+ meta: result
11153
+ };
11154
+ }
11155
+ if (result.decision === "conditional") {
11156
+ const mode = this.options.conditionalDecision ?? "deny";
11157
+ const reasons = [result.reason, result.explanation].filter(Boolean);
11158
+ if (mode === "allow") {
11159
+ return {
11160
+ allow: true,
11161
+ riskScore: 0,
11162
+ reasons,
11163
+ tags: {
11164
+ lawDecision: "conditional"
11165
+ },
11166
+ meta: result
11167
+ };
11168
+ }
11169
+ if (mode === "flag") {
11170
+ return {
11171
+ action: "FLAG",
11172
+ scoreDelta: 25,
11173
+ reasons: reasons.length > 0 ? reasons : ["Execution is conditionally permitted pending additional requirements"],
11174
+ meta: result
11175
+ };
11176
+ }
11177
+ return {
11178
+ action: "DENY",
11179
+ code: "LAW_CONDITIONAL",
11180
+ reason: reasons.join(" | ") || "Execution is conditionally permitted pending additional requirements",
11181
+ meta: { lawDecision: "conditional", evaluation: result }
11182
+ };
11183
+ }
11184
+ return {
11185
+ action: "DENY",
11186
+ code: "LAW_DENIED",
11187
+ reason: [result.reason, result.explanation].filter(Boolean).join(" | ") || "Execution denied by law evaluation",
11188
+ meta: { lawDecision: "deny", evaluation: result }
11189
+ };
11190
+ }
11191
+ };
11192
+ exports2.LawEvaluationSensor = LawEvaluationSensor;
11193
+ exports2.LawEvaluationSensor = LawEvaluationSensor = LawEvaluationSensor_1 = __decorate([
11194
+ (0, sensor_decorator_1.Sensor)(),
11195
+ (0, common_1.Injectable)(),
11196
+ __metadata("design:paramtypes", [Object])
11197
+ ], LawEvaluationSensor);
11198
+ function sanitizeLawContext(context) {
11199
+ return {
11200
+ actorId: context.actorId,
11201
+ intent: context.intent,
11202
+ audience: context.audience,
11203
+ tps: context.tps,
11204
+ country: context.country,
11205
+ ip: context.ip,
11206
+ path: context.path,
11207
+ clientId: context.clientId,
11208
+ deviceId: context.deviceId,
11209
+ sessionId: context.sessionId,
11210
+ capsuleId: context.capsuleId
11211
+ };
11212
+ }
11213
+ }
11214
+ });
11215
+
8722
11216
  // src/sensors/proof-presence.sensor.ts
8723
11217
  var require_proof_presence_sensor = __commonJS({
8724
11218
  "src/sensors/proof-presence.sensor.ts"(exports2) {
@@ -9421,16 +11915,40 @@ var init_sensors2 = __esm({
9421
11915
  __reExport(sensors_exports, __toESM(require_header_tlv_limit_sensor()));
9422
11916
  __reExport(sensors_exports, __toESM(require_intent_allowlist_sensor()));
9423
11917
  __reExport(sensors_exports, __toESM(require_intent_registry_sensor()));
11918
+ __reExport(sensors_exports, __toESM(require_law_evaluation_sensor()));
9424
11919
  __reExport(sensors_exports, __toESM(require_proof_presence_sensor()));
9425
11920
  __reExport(sensors_exports, __toESM(require_protocol_strict_sensor()));
9426
11921
  __reExport(sensors_exports, __toESM(require_receipt_policy_sensor()));
11922
+ __reExport(sensors_exports, __toESM(require_risk_gate_sensor()));
9427
11923
  __reExport(sensors_exports, __toESM(require_schema_validation_sensor()));
9428
11924
  __reExport(sensors_exports, __toESM(require_stream_scope_sensor()));
11925
+ __reExport(sensors_exports, __toESM(require_tickauth_sensor()));
9429
11926
  __reExport(sensors_exports, __toESM(require_tlv_parse_sensor()));
11927
+ __reExport(sensors_exports, __toESM(require_tps_sensor()));
9430
11928
  __reExport(sensors_exports, __toESM(require_varint_hardening_sensor()));
9431
11929
  }
9432
11930
  });
9433
11931
 
11932
+ // src/timeline/timeline.types.ts
11933
+ var init_timeline_types = __esm({
11934
+ "src/timeline/timeline.types.ts"() {
11935
+ }
11936
+ });
11937
+
11938
+ // src/timeline/index.ts
11939
+ var timeline_exports = {};
11940
+ __export(timeline_exports, {
11941
+ InMemoryTimelineStore: () => InMemoryTimelineStore,
11942
+ TimelineEngine: () => TimelineEngine
11943
+ });
11944
+ var init_timeline = __esm({
11945
+ "src/timeline/index.ts"() {
11946
+ init_timeline_types();
11947
+ init_timeline_store();
11948
+ init_timeline_engine();
11949
+ }
11950
+ });
11951
+
9434
11952
  // src/utils/index.ts
9435
11953
  var utils_exports = {};
9436
11954
  __export(utils_exports, {
@@ -9519,6 +12037,10 @@ __export(index_exports, {
9519
12037
  INTENT_SENSITIVITY_MAP: () => INTENT_SENSITIVITY_MAP,
9520
12038
  INTENT_SENSORS_KEY: () => INTENT_SENSORS_KEY,
9521
12039
  INTENT_TIMEOUTS: () => INTENT_TIMEOUTS,
12040
+ IdelCompiler: () => IdelCompiler,
12041
+ IdelSchemaRegistry: () => IdelSchemaRegistry,
12042
+ InMemoryPatternStore: () => InMemoryPatternStore,
12043
+ InMemoryTimelineStore: () => InMemoryTimelineStore,
9522
12044
  Intent: () => Intent,
9523
12045
  IntentBody: () => IntentBody,
9524
12046
  IntentRouter: () => import_intent2.IntentRouter,
@@ -9562,6 +12084,7 @@ __export(index_exports, {
9562
12084
  RequiredProof: () => RequiredProof,
9563
12085
  ResponseObserver: () => ResponseObserver,
9564
12086
  RiskDecision: () => RiskDecision,
12087
+ RiskGateSensor: () => import_risk_gate.RiskGateSensor,
9565
12088
  SENSITIVITY_METADATA_KEY: () => SENSITIVITY_METADATA_KEY,
9566
12089
  SENSOR_METADATA_KEY: () => SENSOR_METADATA_KEY,
9567
12090
  Schema2002_PasskeyLoginOptionsRes: () => Schema2002_PasskeyLoginOptionsRes,
@@ -9582,7 +12105,7 @@ __export(index_exports, {
9582
12105
  TLV_EFFECT: () => import_axis_protocol2.TLV_EFFECT,
9583
12106
  TLV_ERROR_CODE: () => import_axis_protocol2.TLV_ERROR_CODE,
9584
12107
  TLV_ERROR_MSG: () => import_axis_protocol2.TLV_ERROR_MSG,
9585
- TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
12108
+ TLV_FIELDS_KEY: () => import_tlv_field2.TLV_FIELDS_KEY,
9586
12109
  TLV_INDEX: () => import_axis_protocol2.TLV_INDEX,
9587
12110
  TLV_INTENT: () => import_axis_protocol2.TLV_INTENT,
9588
12111
  TLV_KID: () => import_axis_protocol2.TLV_KID,
@@ -9608,21 +12131,29 @@ __export(index_exports, {
9608
12131
  TLV_TRACE_ID: () => import_axis_protocol2.TLV_TRACE_ID,
9609
12132
  TLV_TS: () => import_axis_protocol2.TLV_TS,
9610
12133
  TLV_UPLOAD_ID: () => import_axis_protocol2.TLV_UPLOAD_ID,
9611
- TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
12134
+ TLV_VALIDATORS_KEY: () => import_tlv_field2.TLV_VALIDATORS_KEY,
9612
12135
  TLV_WRIT: () => import_axis_protocol2.TLV_LOOM_WRIT,
9613
- TlvEnum: () => TlvEnum,
9614
- TlvField: () => TlvField,
9615
- TlvMinLen: () => TlvMinLen,
9616
- TlvRange: () => TlvRange,
9617
- TlvUtf8Pattern: () => TlvUtf8Pattern,
9618
- TlvValidate: () => TlvValidate,
12136
+ TickAuthSensor: () => import_tickauth.TickAuthSensor,
12137
+ TimelineEngine: () => TimelineEngine,
12138
+ TlvEnum: () => import_tlv_field2.TlvEnum,
12139
+ TlvField: () => import_tlv_field2.TlvField,
12140
+ TlvMinLen: () => import_tlv_field2.TlvMinLen,
12141
+ TlvRange: () => import_tlv_field2.TlvRange,
12142
+ TlvUtf8Pattern: () => import_tlv_field2.TlvUtf8Pattern,
12143
+ TlvValidate: () => import_tlv_field2.TlvValidate,
12144
+ TpsSensor: () => import_tps.TpsSensor,
9619
12145
  Witness: () => Witness,
12146
+ addStitchToKnot: () => addStitchToKnot,
12147
+ applyStitch: () => applyStitch,
12148
+ assembleNeedle: () => assembleNeedle,
9620
12149
  axis1SigningBytes: () => axis1SigningBytes,
9621
12150
  b64urlDecode: () => b64urlDecode,
9622
12151
  b64urlDecodeString: () => b64urlDecodeString,
9623
12152
  b64urlEncode: () => b64urlEncode,
9624
12153
  b64urlEncodeString: () => b64urlEncodeString,
12154
+ breakKnot: () => breakKnot,
9625
12155
  buildAts1Hdr: () => buildAts1Hdr,
12156
+ buildAxisLawEvaluationContext: () => buildAxisLawEvaluationContext,
9626
12157
  buildDtoDecoder: () => import_dto_schema.buildDtoDecoder,
9627
12158
  buildPacket: () => buildPacket,
9628
12159
  buildQueueMessage: () => buildQueueMessage,
@@ -9641,11 +12172,17 @@ __export(index_exports, {
9641
12172
  computeReceiptHash: () => computeReceiptHash,
9642
12173
  computeSignaturePayload: () => computeSignaturePayload,
9643
12174
  core: () => core_exports,
12175
+ createFabric: () => createFabric,
12176
+ createGrant: () => createGrant,
9644
12177
  createObservation: () => createObservation,
12178
+ createPresenceChallenge: () => createPresenceChallenge,
12179
+ createReceipt: () => createReceipt,
12180
+ createRevocation: () => createRevocation,
12181
+ createWrit: () => createWrit,
9645
12182
  crypto: () => crypto_exports,
9646
12183
  decodeArray: () => import_axis_protocol.decodeArray,
9647
12184
  decodeAxis1Frame: () => decodeAxis1Frame,
9648
- decodeFrame: () => decodeFrame,
12185
+ decodeFrame: () => import_axis_protocol4.decodeFrame,
9649
12186
  decodeObject: () => import_axis_protocol.decodeObject,
9650
12187
  decodeQueueMessage: () => decodeQueueMessage,
9651
12188
  decodeTLVs: () => import_axis_protocol.decodeTLVs,
@@ -9653,30 +12190,52 @@ __export(index_exports, {
9653
12190
  decodeVarint: () => import_axis_protocol3.decodeVarint,
9654
12191
  decorators: () => decorators_exports,
9655
12192
  deriveAnchorReflection: () => deriveAnchorReflection,
12193
+ detectAnomalies: () => detectAnomalies,
12194
+ detectKnotPatterns: () => detectKnotPatterns,
12195
+ detectSequencePatterns: () => detectSequencePatterns,
12196
+ diffFabrics: () => diffFabrics,
9656
12197
  encVarint: () => encVarint,
9657
12198
  encodeAxis1Frame: () => encodeAxis1Frame,
9658
12199
  encodeAxisTlvDto: () => encodeAxisTlvDto,
9659
- encodeFrame: () => encodeFrame,
12200
+ encodeFrame: () => import_axis_protocol4.encodeFrame,
9660
12201
  encodeQueueMessage: () => encodeQueueMessage,
9661
12202
  encodeTLVs: () => import_axis_protocol.encodeTLVs,
9662
12203
  encodeVarint: () => import_axis_protocol3.encodeVarint,
9663
12204
  endStage: () => endStage,
9664
12205
  engine: () => engine_exports,
9665
12206
  executeCcePipeline: () => executeCcePipeline,
12207
+ executeLoomPipeline: () => executeLoomPipeline,
9666
12208
  extractDtoSchema: () => import_dto_schema.extractDtoSchema,
9667
12209
  finalizeObservation: () => finalizeObservation,
12210
+ findKnotsForStitch: () => findKnotsForStitch,
12211
+ forkFromKnot: () => forkFromKnot,
12212
+ formStitch: () => formStitch,
9668
12213
  generateEd25519KeyPair: () => generateEd25519KeyPair,
9669
12214
  getAxisExecutionContext: () => getAxisExecutionContext,
9670
- getSignTarget: () => getSignTarget,
12215
+ getDecisionPoints: () => getDecisionPoints,
12216
+ getFabricValue: () => getFabricValue,
12217
+ getGrantStatus: () => getGrantStatus,
12218
+ getIrreversibleKnots: () => getIrreversibleKnots,
12219
+ getPresenceStatus: () => getPresenceStatus,
12220
+ getSignTarget: () => import_axis_protocol4.getSignTarget,
12221
+ grantCoversAction: () => grantCoversAction,
9671
12222
  hasScope: () => hasScope,
9672
12223
  hashObservation: () => hashObservation,
12224
+ idel: () => idel_exports,
9673
12225
  isAdminOpcode: () => isAdminOpcode,
12226
+ isKnotOpen: () => isKnotOpen,
9674
12227
  isKnownOpcode: () => isKnownOpcode,
12228
+ isPointOfNoReturn: () => isPointOfNoReturn,
12229
+ isRevoked: () => isRevoked,
9675
12230
  isTimestampValid: () => isTimestampValid,
12231
+ lockCells: () => lockCells,
9676
12232
  loom: () => loom_exports,
12233
+ matchPatterns: () => matchPatterns,
9677
12234
  mergeAxisExecutionContext: () => mergeAxisExecutionContext,
12235
+ needle: () => needle_exports,
9678
12236
  nonce16: () => nonce16,
9679
12237
  normalizeSensorDecision: () => normalizeSensorDecision,
12238
+ openKnot: () => openKnot,
9680
12239
  packPasskeyLoginOptionsReq: () => packPasskeyLoginOptionsReq,
9681
12240
  packPasskeyLoginOptionsRes: () => packPasskeyLoginOptionsRes,
9682
12241
  packPasskeyLoginVerifyReq: () => packPasskeyLoginVerifyReq,
@@ -9685,32 +12244,49 @@ __export(index_exports, {
9685
12244
  parseAutoClaimEntries: () => parseAutoClaimEntries,
9686
12245
  parseScope: () => parseScope,
9687
12246
  parseStreamEntries: () => parseStreamEntries,
12247
+ projectAt: () => projectAt,
12248
+ queryFabric: () => queryFabric,
12249
+ recordOccurrence: () => recordOccurrence,
9688
12250
  recordSensor: () => recordSensor,
12251
+ renewPresence: () => renewPresence,
9689
12252
  resolveTimeout: () => resolveTimeout,
12253
+ runNeedlePipeline: () => runNeedlePipeline,
9690
12254
  schemas: () => schemas_exports,
12255
+ scoreTruth: () => scoreTruth,
9691
12256
  security: () => security_exports,
9692
12257
  sensitivityName: () => sensitivityName,
9693
12258
  sensors: () => sensors_exports,
9694
12259
  sha256: () => sha2564,
9695
12260
  signFrame: () => signFrame,
12261
+ signPresenceChallenge: () => signPresenceChallenge,
9696
12262
  stableJsonStringify: () => stableJsonStringify,
9697
12263
  startStage: () => startStage,
12264
+ tieKnot: () => tieKnot,
12265
+ timeline: () => timeline_exports,
9698
12266
  tlv: () => tlv,
9699
12267
  u64be: () => u64be,
9700
12268
  unpackPasskeyLoginOptionsReq: () => unpackPasskeyLoginOptionsReq,
9701
12269
  unpackPasskeyLoginVerifyReq: () => unpackPasskeyLoginVerifyReq,
9702
12270
  unpackPasskeyRegisterOptionsReq: () => unpackPasskeyRegisterOptionsReq,
12271
+ updateThreadState: () => updateThreadState,
9703
12272
  utf8: () => utf8,
9704
12273
  utils: () => utils_exports,
9705
12274
  validateFrameShape: () => validateFrameShape,
12275
+ validateGrant: () => validateGrant,
12276
+ validateKnot: () => validateKnot,
12277
+ validateWrit: () => validateWrit,
9706
12278
  varintLength: () => import_axis_protocol3.varintLength,
9707
12279
  varintU: () => varintU,
9708
12280
  verifyFrameSignature: () => verifyFrameSignature,
12281
+ verifyObservation: () => verifyObservation,
12282
+ verifyPresenceProof: () => verifyPresenceProof,
12283
+ verifyReceiptChain: () => verifyReceiptChain,
9709
12284
  verifyResponse: () => verifyResponse,
12285
+ weave: () => weave,
9710
12286
  withAxisExecutionContext: () => withAxisExecutionContext
9711
12287
  });
9712
12288
  module.exports = __toCommonJS(index_exports);
9713
- 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;
12289
+ 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;
9714
12290
  var init_index = __esm({
9715
12291
  "src/index.ts"() {
9716
12292
  init_chain_decorator();
@@ -9723,7 +12299,7 @@ var init_index = __esm({
9723
12299
  init_observer_decorator();
9724
12300
  init_handler_sensors_decorator();
9725
12301
  init_sensor_decorator();
9726
- init_tlv_field_decorator();
12302
+ import_tlv_field2 = __toESM(require_tlv_field_decorator());
9727
12303
  import_dto_schema = __toESM(require_dto_schema_util());
9728
12304
  init_axis_tlv_dto();
9729
12305
  import_axis_id = __toESM(require_axis_id_dto());
@@ -9736,6 +12312,7 @@ var init_index = __esm({
9736
12312
  init_stable_json();
9737
12313
  init_observation_queue_codec();
9738
12314
  init_observation_hash();
12315
+ init_truth_scoring();
9739
12316
  init_response_observer();
9740
12317
  init_constants();
9741
12318
  init_varint();
@@ -9757,6 +12334,7 @@ var init_index = __esm({
9757
12334
  init_axis_sensor();
9758
12335
  init_scopes();
9759
12336
  init_capabilities();
12337
+ init_law();
9760
12338
  init_risk();
9761
12339
  init_opcodes();
9762
12340
  init_receipt();
@@ -9776,19 +12354,33 @@ var init_index = __esm({
9776
12354
  import_sensor2 = __toESM(require_sensor_registry());
9777
12355
  init_axis_observation();
9778
12356
  import_axis_sensor_chain = __toESM(require_axis_sensor_chain_service());
12357
+ init_timeline_engine();
12358
+ init_timeline_store();
9779
12359
  init_cce_pipeline();
9780
12360
  init_cce_types();
9781
12361
  init_axis_tlv_codec();
9782
12362
  init_loom_types();
12363
+ init_loom_engine();
12364
+ init_idel_compiler();
12365
+ init_needle_engine();
12366
+ init_knot_engine();
12367
+ init_fabric_engine();
12368
+ init_pattern_engine();
12369
+ import_tps = __toESM(require_tps_sensor());
12370
+ import_risk_gate = __toESM(require_risk_gate_sensor());
12371
+ import_tickauth = __toESM(require_tickauth_sensor());
9783
12372
  init_cce();
9784
12373
  init_core();
9785
12374
  init_crypto();
9786
12375
  init_decorators();
9787
12376
  init_engine();
12377
+ init_idel();
9788
12378
  init_loom();
12379
+ init_needle();
9789
12380
  init_schemas();
9790
12381
  init_security();
9791
12382
  init_sensors2();
12383
+ init_timeline();
9792
12384
  init_utils();
9793
12385
  }
9794
12386
  });
@@ -9869,6 +12461,10 @@ init_index();
9869
12461
  INTENT_SENSITIVITY_MAP,
9870
12462
  INTENT_SENSORS_KEY,
9871
12463
  INTENT_TIMEOUTS,
12464
+ IdelCompiler,
12465
+ IdelSchemaRegistry,
12466
+ InMemoryPatternStore,
12467
+ InMemoryTimelineStore,
9872
12468
  Intent,
9873
12469
  IntentBody,
9874
12470
  IntentRouter,
@@ -9912,6 +12508,7 @@ init_index();
9912
12508
  RequiredProof,
9913
12509
  ResponseObserver,
9914
12510
  RiskDecision,
12511
+ RiskGateSensor,
9915
12512
  SENSITIVITY_METADATA_KEY,
9916
12513
  SENSOR_METADATA_KEY,
9917
12514
  Schema2002_PasskeyLoginOptionsRes,
@@ -9960,19 +12557,27 @@ init_index();
9960
12557
  TLV_UPLOAD_ID,
9961
12558
  TLV_VALIDATORS_KEY,
9962
12559
  TLV_WRIT,
12560
+ TickAuthSensor,
12561
+ TimelineEngine,
9963
12562
  TlvEnum,
9964
12563
  TlvField,
9965
12564
  TlvMinLen,
9966
12565
  TlvRange,
9967
12566
  TlvUtf8Pattern,
9968
12567
  TlvValidate,
12568
+ TpsSensor,
9969
12569
  Witness,
12570
+ addStitchToKnot,
12571
+ applyStitch,
12572
+ assembleNeedle,
9970
12573
  axis1SigningBytes,
9971
12574
  b64urlDecode,
9972
12575
  b64urlDecodeString,
9973
12576
  b64urlEncode,
9974
12577
  b64urlEncodeString,
12578
+ breakKnot,
9975
12579
  buildAts1Hdr,
12580
+ buildAxisLawEvaluationContext,
9976
12581
  buildDtoDecoder,
9977
12582
  buildPacket,
9978
12583
  buildQueueMessage,
@@ -9991,7 +12596,13 @@ init_index();
9991
12596
  computeReceiptHash,
9992
12597
  computeSignaturePayload,
9993
12598
  core,
12599
+ createFabric,
12600
+ createGrant,
9994
12601
  createObservation,
12602
+ createPresenceChallenge,
12603
+ createReceipt,
12604
+ createRevocation,
12605
+ createWrit,
9995
12606
  crypto,
9996
12607
  decodeArray,
9997
12608
  decodeAxis1Frame,
@@ -10003,6 +12614,10 @@ init_index();
10003
12614
  decodeVarint,
10004
12615
  decorators,
10005
12616
  deriveAnchorReflection,
12617
+ detectAnomalies,
12618
+ detectKnotPatterns,
12619
+ detectSequencePatterns,
12620
+ diffFabrics,
10006
12621
  encVarint,
10007
12622
  encodeAxis1Frame,
10008
12623
  encodeAxisTlvDto,
@@ -10013,20 +12628,38 @@ init_index();
10013
12628
  endStage,
10014
12629
  engine,
10015
12630
  executeCcePipeline,
12631
+ executeLoomPipeline,
10016
12632
  extractDtoSchema,
10017
12633
  finalizeObservation,
12634
+ findKnotsForStitch,
12635
+ forkFromKnot,
12636
+ formStitch,
10018
12637
  generateEd25519KeyPair,
10019
12638
  getAxisExecutionContext,
12639
+ getDecisionPoints,
12640
+ getFabricValue,
12641
+ getGrantStatus,
12642
+ getIrreversibleKnots,
12643
+ getPresenceStatus,
10020
12644
  getSignTarget,
12645
+ grantCoversAction,
10021
12646
  hasScope,
10022
12647
  hashObservation,
12648
+ idel,
10023
12649
  isAdminOpcode,
12650
+ isKnotOpen,
10024
12651
  isKnownOpcode,
12652
+ isPointOfNoReturn,
12653
+ isRevoked,
10025
12654
  isTimestampValid,
12655
+ lockCells,
10026
12656
  loom,
12657
+ matchPatterns,
10027
12658
  mergeAxisExecutionContext,
12659
+ needle,
10028
12660
  nonce16,
10029
12661
  normalizeSensorDecision,
12662
+ openKnot,
10030
12663
  packPasskeyLoginOptionsReq,
10031
12664
  packPasskeyLoginOptionsRes,
10032
12665
  packPasskeyLoginVerifyReq,
@@ -10035,28 +12668,45 @@ init_index();
10035
12668
  parseAutoClaimEntries,
10036
12669
  parseScope,
10037
12670
  parseStreamEntries,
12671
+ projectAt,
12672
+ queryFabric,
12673
+ recordOccurrence,
10038
12674
  recordSensor,
12675
+ renewPresence,
10039
12676
  resolveTimeout,
12677
+ runNeedlePipeline,
10040
12678
  schemas,
12679
+ scoreTruth,
10041
12680
  security,
10042
12681
  sensitivityName,
10043
12682
  sensors,
10044
12683
  sha256,
10045
12684
  signFrame,
12685
+ signPresenceChallenge,
10046
12686
  stableJsonStringify,
10047
12687
  startStage,
12688
+ tieKnot,
12689
+ timeline,
10048
12690
  tlv,
10049
12691
  u64be,
10050
12692
  unpackPasskeyLoginOptionsReq,
10051
12693
  unpackPasskeyLoginVerifyReq,
10052
12694
  unpackPasskeyRegisterOptionsReq,
12695
+ updateThreadState,
10053
12696
  utf8,
10054
12697
  utils,
10055
12698
  validateFrameShape,
12699
+ validateGrant,
12700
+ validateKnot,
12701
+ validateWrit,
10056
12702
  varintLength,
10057
12703
  varintU,
10058
12704
  verifyFrameSignature,
12705
+ verifyObservation,
12706
+ verifyPresenceProof,
12707
+ verifyReceiptChain,
10059
12708
  verifyResponse,
12709
+ weave,
10060
12710
  withAxisExecutionContext
10061
12711
  });
10062
12712
  //# sourceMappingURL=index.js.map