artifact-graph 0.14.1 → 0.16.0

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
@@ -1,7 +1,12 @@
1
+ var __defProp = Object.defineProperty;
1
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
2
3
  var __esm = (fn, res) => function __init() {
3
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
5
  };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
5
10
 
6
11
  // src/packet-constants.ts
7
12
  var ALWAYS_PRESENT_ITEMS, BASELINE_ITEMS_COUNT, BASELINE_CONSTRAINTS, BASELINE_CONSTRAINTS_COUNT;
@@ -370,6 +375,505 @@ var init_file_walker = __esm({
370
375
  }
371
376
  });
372
377
 
378
+ // src/doctor.ts
379
+ import yaml from "js-yaml";
380
+ import _AjvModule from "ajv";
381
+ import { readFile } from "fs/promises";
382
+ import { isAbsolute, join as join2 } from "path";
383
+ function getShapeValidator() {
384
+ if (!_validateConfigShape) {
385
+ const AjvCtor = _AjvModule;
386
+ const ajv = new AjvCtor({ allErrors: true, strict: false });
387
+ _validateConfigShape = ajv.compile(CONFIG_SHAPE_SCHEMA);
388
+ }
389
+ return _validateConfigShape;
390
+ }
391
+ function instancePathToField(instancePath, params) {
392
+ const missing = typeof params?.missingProperty === "string" ? params.missingProperty : void 0;
393
+ if (!instancePath || instancePath === "") {
394
+ return missing && missing.length > 0 ? missing : "(root)";
395
+ }
396
+ const path = instancePath.replace(/^\//, "").replace(/\//g, ".");
397
+ return missing && missing.length > 0 ? `${path}.${missing}` : path;
398
+ }
399
+ function pushError(errors, path, message) {
400
+ errors.push({ path, message, severity: "error" });
401
+ }
402
+ function warnUnknownObjectKeys(value, path, knownKeys, warnings) {
403
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
404
+ for (const key of Object.keys(value)) {
405
+ if (knownKeys.has(key)) continue;
406
+ const field = path ? `${path}.${key}` : key;
407
+ warnings.push({
408
+ path: field,
409
+ message: `Unknown config key ${key} at ${field}: kept for compatibility and not treated as a declared field.`,
410
+ severity: "warning"
411
+ });
412
+ }
413
+ }
414
+ function warnUnknownArrayObjectKeys(value, path, knownKeys, warnings) {
415
+ if (!Array.isArray(value)) return;
416
+ value.forEach((entry, index) => {
417
+ warnUnknownObjectKeys(entry, `${path}.${index}`, knownKeys, warnings);
418
+ });
419
+ }
420
+ function collectNestedUnknownKeyWarnings(document, warnings) {
421
+ warnUnknownObjectKeys(document, "", KNOWN_TOP_LEVEL_KEYS, warnings);
422
+ const types = document.types;
423
+ if (types && typeof types === "object" && !Array.isArray(types)) {
424
+ for (const [typeName, definition] of Object.entries(types)) {
425
+ const typePath = `types.${typeName}`;
426
+ warnUnknownObjectKeys(definition, typePath, TYPE_OBJECT_KEYS, warnings);
427
+ if (definition && typeof definition === "object" && !Array.isArray(definition)) {
428
+ warnUnknownArrayObjectKeys(
429
+ definition.extraFields,
430
+ `${typePath}.extraFields`,
431
+ EXTRA_FIELD_KEYS,
432
+ warnings
433
+ );
434
+ }
435
+ }
436
+ }
437
+ warnUnknownArrayObjectKeys(document.allowedEdges, "allowedEdges", EDGE_RULE_KEYS, warnings);
438
+ warnUnknownArrayObjectKeys(document.forbiddenEdges, "forbiddenEdges", EDGE_RULE_KEYS, warnings);
439
+ warnUnknownObjectKeys(document.context, "context", CONTEXT_KEYS, warnings);
440
+ const idRanges = document.idRanges;
441
+ if (idRanges && typeof idRanges === "object" && !Array.isArray(idRanges)) {
442
+ for (const [layer, ranges] of Object.entries(idRanges)) {
443
+ if (!ranges || typeof ranges !== "object" || Array.isArray(ranges)) continue;
444
+ for (const [rangeName, entry] of Object.entries(ranges)) {
445
+ warnUnknownObjectKeys(entry, `idRanges.${layer}.${rangeName}`, ID_RANGE_ENTRY_KEYS, warnings);
446
+ }
447
+ }
448
+ }
449
+ const relationSemantics = document.relationSemantics;
450
+ if (relationSemantics && typeof relationSemantics === "object" && !Array.isArray(relationSemantics)) {
451
+ for (const [kind, spec] of Object.entries(relationSemantics)) {
452
+ const specPath = `relationSemantics.${kind}`;
453
+ warnUnknownObjectKeys(spec, specPath, RELATION_SEMANTICS_KEYS, warnings);
454
+ if (spec && typeof spec === "object" && !Array.isArray(spec)) {
455
+ warnUnknownObjectKeys(
456
+ spec.partial,
457
+ `${specPath}.partial`,
458
+ RELATION_PARTIAL_KEYS,
459
+ warnings
460
+ );
461
+ }
462
+ }
463
+ }
464
+ const e2e = document.e2e;
465
+ if (e2e && typeof e2e === "object" && !Array.isArray(e2e)) {
466
+ const e2eRecord = e2e;
467
+ warnUnknownObjectKeys(e2eRecord, "e2e", E2E_KEYS, warnings);
468
+ warnUnknownArrayObjectKeys(e2eRecord.scenario_waivers, "e2e.scenario_waivers", WAIVER_KEYS, warnings);
469
+ warnUnknownArrayObjectKeys(e2eRecord.feature_waivers, "e2e.feature_waivers", WAIVER_KEYS, warnings);
470
+ warnUnknownArrayObjectKeys(e2eRecord.runners, "e2e.runners", RUNNER_KEYS, warnings);
471
+ }
472
+ }
473
+ function typeHasDefaultPaths(typeName) {
474
+ const base = DEFAULT_SCHEMA.types[typeName];
475
+ return Array.isArray(base?.paths);
476
+ }
477
+ function collectCustomTypePathErrors(types, errors) {
478
+ if (types === void 0) return;
479
+ if (typeof types !== "object" || types === null || Array.isArray(types)) return;
480
+ for (const [typeName, definition] of Object.entries(types)) {
481
+ if (definition === void 0 || definition === null) {
482
+ if (!typeHasDefaultPaths(typeName)) {
483
+ pushError(errors, `types.${typeName}.paths`, `Invalid types.${typeName}.paths: must be array`);
484
+ }
485
+ continue;
486
+ }
487
+ if (typeof definition !== "object" || Array.isArray(definition)) continue;
488
+ const paths = definition.paths;
489
+ if (paths === void 0 && !typeHasDefaultPaths(typeName)) {
490
+ pushError(errors, `types.${typeName}.paths`, `Invalid types.${typeName}.paths: must be array`);
491
+ }
492
+ }
493
+ }
494
+ function collectRelationSemanticsErrors(value, errors) {
495
+ if (value === void 0) return;
496
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
497
+ pushError(errors, "relationSemantics", "Invalid relationSemantics: must be an object keyed by relation kind.");
498
+ return;
499
+ }
500
+ for (const [kind, spec] of Object.entries(value)) {
501
+ const path = `relationSemantics.${kind}`;
502
+ if (!kind.trim() || typeof spec !== "object" || spec === null || Array.isArray(spec)) {
503
+ pushError(errors, path, `Invalid relationSemantics.${kind}: must be an object.`);
504
+ continue;
505
+ }
506
+ const record = spec;
507
+ if (typeof record.label !== "string" || !record.label.trim()) {
508
+ pushError(errors, `${path}.label`, `Invalid relationSemantics.${kind}.label: must be a non-empty string.`);
509
+ }
510
+ if (!Array.isArray(record.targetTypes) || record.targetTypes.some((item) => typeof item !== "string" || !item.trim())) {
511
+ pushError(errors, `${path}.targetTypes`, `Invalid relationSemantics.${kind}.targetTypes: must be an array of non-empty strings.`);
512
+ }
513
+ if (!Array.isArray(record.fields) || record.fields.length === 0 || record.fields.some((item) => typeof item !== "string" || !item.trim())) {
514
+ pushError(errors, `${path}.fields`, `Invalid relationSemantics.${kind}.fields: must be a non-empty array of strings.`);
515
+ }
516
+ if (record.partial !== void 0 && (typeof record.partial !== "object" || record.partial === null || Array.isArray(record.partial) || typeof record.partial.sectionField !== "string" || !record.partial.sectionField.trim())) {
517
+ pushError(
518
+ errors,
519
+ `${path}.partial.sectionField`,
520
+ `Invalid relationSemantics.${kind}.partial.sectionField: must be a non-empty string.`
521
+ );
522
+ }
523
+ }
524
+ }
525
+ function collectStatusViewsErrors(value, errors) {
526
+ if (value === void 0) return;
527
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
528
+ pushError(errors, "statusViews", "Invalid statusViews: must be an object keyed by status.");
529
+ return;
530
+ }
531
+ for (const [status, bucket] of Object.entries(value)) {
532
+ if (!status.trim() || !["current", "planned", "history"].includes(bucket)) {
533
+ pushError(errors, `statusViews.${status}`, `Invalid statusViews.${status}: expected current, planned, or history.`);
534
+ }
535
+ }
536
+ }
537
+ function collectWaiverErrors(waivers, field, errors) {
538
+ if (waivers === void 0) return;
539
+ if (!Array.isArray(waivers)) {
540
+ pushError(errors, field, `Invalid ${field}: must be an array of {id, reason} objects.`);
541
+ return;
542
+ }
543
+ waivers.forEach((entry, index) => {
544
+ const path = `${field}.${index}`;
545
+ if (typeof entry !== "object" || entry === null || !("id" in entry) || !("reason" in entry)) {
546
+ pushError(errors, path, `Invalid ${field} entry: ${JSON.stringify(entry)}. Must be {id, reason} object.`);
547
+ return;
548
+ }
549
+ const record = entry;
550
+ if (typeof record.id !== "string" || !record.id.trim()) {
551
+ pushError(errors, `${path}.id`, `Invalid ${field} entry: id must be a non-empty string. Got: ${JSON.stringify(record.id)}`);
552
+ }
553
+ if (typeof record.reason !== "string" || !record.reason.trim()) {
554
+ pushError(errors, `${path}.reason`, `Invalid ${field} entry: reason must be a non-empty string. Got: ${JSON.stringify(record.reason)}`);
555
+ }
556
+ });
557
+ }
558
+ function collectE2eConfigErrors(e2e, errors) {
559
+ if (e2e === void 0) return;
560
+ if (typeof e2e !== "object" || e2e === null || Array.isArray(e2e)) {
561
+ pushError(errors, "e2e", "Invalid e2e: must be an object.");
562
+ return;
563
+ }
564
+ const record = e2e;
565
+ for (const field of ["report_uncovered_scenarios", "report_uncovered_features"]) {
566
+ if (record[field] !== void 0 && typeof record[field] !== "boolean") {
567
+ pushError(errors, `e2e.${field}`, `Invalid e2e.${field}: must be boolean.`);
568
+ }
569
+ }
570
+ if (record.executable_ref_warning !== void 0) {
571
+ if (typeof record.executable_ref_warning !== "number" || record.executable_ref_warning < 0 || record.executable_ref_warning > 1) {
572
+ pushError(
573
+ errors,
574
+ "e2e.executable_ref_warning",
575
+ `Invalid e2e.executable_ref_warning: ${JSON.stringify(record.executable_ref_warning)}. Must be a number between 0 and 1.`
576
+ );
577
+ }
578
+ }
579
+ if (record.executable_ref_error !== void 0) {
580
+ if (typeof record.executable_ref_error !== "number" || record.executable_ref_error < 0 || record.executable_ref_error > 1) {
581
+ pushError(
582
+ errors,
583
+ "e2e.executable_ref_error",
584
+ `Invalid e2e.executable_ref_error: ${JSON.stringify(record.executable_ref_error)}. Must be a number between 0 and 1.`
585
+ );
586
+ }
587
+ }
588
+ collectWaiverErrors(record.scenario_waivers, "e2e.scenario_waivers", errors);
589
+ collectWaiverErrors(record.feature_waivers, "e2e.feature_waivers", errors);
590
+ if (record.runners === void 0) return;
591
+ if (!Array.isArray(record.runners)) {
592
+ pushError(errors, "e2e.runners", "Invalid e2e.runners: must be an array.");
593
+ return;
594
+ }
595
+ record.runners.forEach((runner, index) => {
596
+ const runnerPath = `e2e.runners.${index}`;
597
+ if (typeof runner !== "object" || runner === null) {
598
+ pushError(errors, runnerPath, "Invalid e2e.runners entry: must be an object.");
599
+ return;
600
+ }
601
+ const runnerRecord = runner;
602
+ const name = runnerRecord.name;
603
+ if (typeof name !== "string" || !name.trim()) {
604
+ pushError(errors, `${runnerPath}.name`, "Invalid e2e.runners entry: name must be a non-empty string.");
605
+ return;
606
+ }
607
+ if (typeof runnerRecord.root !== "string" || !runnerRecord.root.trim()) {
608
+ pushError(errors, `${runnerPath}.root`, `Invalid e2e.runners[${name}].root: must be a non-empty string.`);
609
+ } else {
610
+ if (isAbsolute(runnerRecord.root)) {
611
+ pushError(errors, `${runnerPath}.root`, `Invalid e2e.runners[${name}].root: "${runnerRecord.root}" must not be an absolute path.`);
612
+ }
613
+ if (runnerRecord.root.replace(/\\/g, "/").split("/").includes("..")) {
614
+ pushError(errors, `${runnerPath}.root`, `Invalid e2e.runners[${name}].root: "${runnerRecord.root}" must not contain ".." segments.`);
615
+ }
616
+ }
617
+ if (!Array.isArray(runnerRecord.include) || runnerRecord.include.length === 0) {
618
+ pushError(errors, `${runnerPath}.include`, `Invalid e2e.runners[${name}].include: must be a non-empty array of glob patterns.`);
619
+ } else {
620
+ for (const pattern of runnerRecord.include) {
621
+ if (typeof pattern !== "string" || !pattern.trim()) {
622
+ pushError(errors, `${runnerPath}.include`, `Invalid e2e.runners[${name}].include: pattern must be a non-empty string.`);
623
+ }
624
+ }
625
+ }
626
+ if (runnerRecord.exclude !== void 0) {
627
+ if (!Array.isArray(runnerRecord.exclude)) {
628
+ pushError(errors, `${runnerPath}.exclude`, `Invalid e2e.runners[${name}].exclude: must be an array.`);
629
+ } else {
630
+ for (const pattern of runnerRecord.exclude) {
631
+ if (typeof pattern !== "string" || !pattern.trim()) {
632
+ pushError(errors, `${runnerPath}.exclude`, `Invalid e2e.runners[${name}].exclude: pattern must be a non-empty string.`);
633
+ }
634
+ }
635
+ }
636
+ }
637
+ if (runnerRecord.testIgnore !== void 0) {
638
+ if (!Array.isArray(runnerRecord.testIgnore)) {
639
+ pushError(errors, `${runnerPath}.testIgnore`, `Invalid e2e.runners[${name}].testIgnore: must be an array.`);
640
+ } else {
641
+ for (const pattern of runnerRecord.testIgnore) {
642
+ if (typeof pattern !== "string" || !pattern.trim()) {
643
+ pushError(errors, `${runnerPath}.testIgnore`, `Invalid e2e.runners[${name}].testIgnore: pattern must be a non-empty string.`);
644
+ }
645
+ }
646
+ }
647
+ }
648
+ if (runnerRecord.kind !== void 0) {
649
+ if (!["unit", "integration", "e2e"].includes(runnerRecord.kind)) {
650
+ pushError(errors, `${runnerPath}.kind`, `Invalid e2e.runners[${name}].kind: "${runnerRecord.kind}". Must be unit, integration, or e2e.`);
651
+ }
652
+ }
653
+ });
654
+ }
655
+ function collectAllowedEdgesPresenceError(document, errors) {
656
+ if (!Object.prototype.hasOwnProperty.call(document, "allowedEdges")) {
657
+ pushError(errors, "allowedEdges", ALLOWED_EDGES_REQUIRED_MESSAGE);
658
+ }
659
+ }
660
+ function collectExistingLoaderErrors(document, errors) {
661
+ collectCustomTypePathErrors(document.types, errors);
662
+ collectE2eConfigErrors(document.e2e, errors);
663
+ collectRelationSemanticsErrors(document.relationSemantics, errors);
664
+ collectStatusViewsErrors(document.statusViews, errors);
665
+ collectAllowedEdgesPresenceError(document, errors);
666
+ }
667
+ function diagnoseConfigDocument(parsed) {
668
+ const errors = [];
669
+ const warnings = [];
670
+ if (parsed === void 0 || parsed === null) {
671
+ return { errors, warnings };
672
+ }
673
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
674
+ errors.push({
675
+ path: "(root)",
676
+ message: `Invalid artifact-graph.config.yaml: expected an object, got ${Array.isArray(parsed) ? "array" : typeof parsed}.`,
677
+ severity: "error"
678
+ });
679
+ return { errors, warnings };
680
+ }
681
+ const document = parsed;
682
+ const validate = getShapeValidator();
683
+ const valid = validate(document);
684
+ if (!valid) {
685
+ for (const err of validate.errors ?? []) {
686
+ const path = instancePathToField(err.instancePath, err.params);
687
+ errors.push({
688
+ path,
689
+ message: `Invalid ${path}: ${err.message ?? "validation error"}`,
690
+ severity: "error"
691
+ });
692
+ }
693
+ }
694
+ collectExistingLoaderErrors(document, errors);
695
+ collectNestedUnknownKeyWarnings(document, warnings);
696
+ return { errors, warnings };
697
+ }
698
+ async function diagnoseProjectConfig(root) {
699
+ const configPath = join2(root, "artifact-graph.config.yaml");
700
+ let raw;
701
+ try {
702
+ raw = await readFile(configPath, "utf-8");
703
+ } catch (error) {
704
+ if (error.code === "ENOENT") {
705
+ return { exists: false, errors: [], warnings: [] };
706
+ }
707
+ return {
708
+ exists: true,
709
+ errors: [{
710
+ path: "artifact-graph.config.yaml",
711
+ message: `Unable to read artifact-graph.config.yaml: ${error.message}`,
712
+ severity: "error"
713
+ }],
714
+ warnings: []
715
+ };
716
+ }
717
+ let document;
718
+ try {
719
+ document = yaml.load(raw) ?? {};
720
+ } catch (error) {
721
+ return {
722
+ exists: true,
723
+ errors: [{
724
+ path: "artifact-graph.config.yaml",
725
+ message: `Invalid artifact-graph.config.yaml: ${error.message}`,
726
+ severity: "error"
727
+ }],
728
+ warnings: []
729
+ };
730
+ }
731
+ const diagnosis = diagnoseConfigDocument(document);
732
+ return { exists: true, errors: diagnosis.errors, warnings: diagnosis.warnings };
733
+ }
734
+ var KNOWN_TOP_LEVEL_KEYS, TYPE_OBJECT_KEYS, EXTRA_FIELD_KEYS, EDGE_RULE_KEYS, CONTEXT_KEYS, ID_RANGE_ENTRY_KEYS, RELATION_SEMANTICS_KEYS, RELATION_PARTIAL_KEYS, E2E_KEYS, WAIVER_KEYS, RUNNER_KEYS, EDGE_RULE_SCHEMA, EXTRA_FIELD_SCHEMA, ID_RANGE_ENTRY_SCHEMA, CONFIG_SHAPE_SCHEMA, _validateConfigShape, ALLOWED_EDGES_REQUIRED_MESSAGE;
735
+ var init_doctor = __esm({
736
+ "src/doctor.ts"() {
737
+ "use strict";
738
+ init_index();
739
+ KNOWN_TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
740
+ "types",
741
+ "idPatterns",
742
+ "relationFields",
743
+ "allowedEdges",
744
+ "forbiddenEdges",
745
+ "statuses",
746
+ "idRanges",
747
+ "relationSemantics",
748
+ "statusViews",
749
+ "context",
750
+ "e2e"
751
+ ]);
752
+ TYPE_OBJECT_KEYS = /* @__PURE__ */ new Set([
753
+ "paths",
754
+ "idPattern",
755
+ "displayName",
756
+ "role",
757
+ "layer",
758
+ "aliases",
759
+ "target",
760
+ "extraFields",
761
+ "format",
762
+ "idField"
763
+ ]);
764
+ EXTRA_FIELD_KEYS = /* @__PURE__ */ new Set(["name", "type", "enum"]);
765
+ EDGE_RULE_KEYS = /* @__PURE__ */ new Set(["from", "to", "kind"]);
766
+ CONTEXT_KEYS = /* @__PURE__ */ new Set(["universal_baseline"]);
767
+ ID_RANGE_ENTRY_KEYS = /* @__PURE__ */ new Set(["prefix", "start", "end"]);
768
+ RELATION_SEMANTICS_KEYS = /* @__PURE__ */ new Set(["label", "targetTypes", "fields", "partial"]);
769
+ RELATION_PARTIAL_KEYS = /* @__PURE__ */ new Set(["sectionField"]);
770
+ E2E_KEYS = /* @__PURE__ */ new Set([
771
+ "executable_ref_warning",
772
+ "executable_ref_error",
773
+ "report_uncovered_scenarios",
774
+ "report_uncovered_features",
775
+ "scenario_waivers",
776
+ "feature_waivers",
777
+ "runners"
778
+ ]);
779
+ WAIVER_KEYS = /* @__PURE__ */ new Set(["id", "reason"]);
780
+ RUNNER_KEYS = /* @__PURE__ */ new Set(["name", "kind", "root", "include", "exclude", "testIgnore"]);
781
+ EDGE_RULE_SCHEMA = {
782
+ type: "object",
783
+ additionalProperties: true,
784
+ required: ["from", "to", "kind"],
785
+ properties: {
786
+ from: { type: "string", minLength: 1 },
787
+ to: { type: "string", minLength: 1 },
788
+ kind: { type: "string", minLength: 1 }
789
+ }
790
+ };
791
+ EXTRA_FIELD_SCHEMA = {
792
+ type: "object",
793
+ additionalProperties: true,
794
+ required: ["name", "type"],
795
+ properties: {
796
+ name: { type: "string", minLength: 1 },
797
+ type: { type: "string", enum: ["string", "number", "boolean", "enum"] },
798
+ enum: {
799
+ type: "array",
800
+ items: {
801
+ anyOf: [
802
+ { type: "string" },
803
+ { type: "number" },
804
+ { type: "boolean" }
805
+ ]
806
+ }
807
+ }
808
+ }
809
+ };
810
+ ID_RANGE_ENTRY_SCHEMA = {
811
+ type: "object",
812
+ additionalProperties: true,
813
+ required: ["prefix", "start", "end"],
814
+ properties: {
815
+ prefix: { type: "string" },
816
+ start: { type: "number" },
817
+ end: { type: "number" }
818
+ }
819
+ };
820
+ CONFIG_SHAPE_SCHEMA = {
821
+ type: "object",
822
+ additionalProperties: true,
823
+ properties: {
824
+ statuses: { type: "array", items: { type: "string" } },
825
+ allowedEdges: {
826
+ anyOf: [
827
+ { type: "null" },
828
+ { type: "array", items: EDGE_RULE_SCHEMA }
829
+ ]
830
+ },
831
+ forbiddenEdges: { type: "array", items: EDGE_RULE_SCHEMA },
832
+ idPatterns: {
833
+ type: "object",
834
+ additionalProperties: { type: "string" }
835
+ },
836
+ relationFields: {
837
+ type: "object",
838
+ additionalProperties: { type: "array", items: { type: "string" } }
839
+ },
840
+ context: {
841
+ type: "object",
842
+ additionalProperties: true,
843
+ properties: {
844
+ universal_baseline: { type: "boolean" }
845
+ }
846
+ },
847
+ idRanges: {
848
+ type: "object",
849
+ additionalProperties: {
850
+ type: "object",
851
+ additionalProperties: ID_RANGE_ENTRY_SCHEMA
852
+ }
853
+ },
854
+ types: {
855
+ type: "object",
856
+ additionalProperties: {
857
+ type: "object",
858
+ additionalProperties: true,
859
+ properties: {
860
+ paths: { type: "array", items: { type: "string" } },
861
+ idPattern: { type: "string" },
862
+ displayName: { type: "string" },
863
+ role: { type: "string" },
864
+ layer: { type: "string" },
865
+ aliases: { type: "array", items: { type: "string" } },
866
+ target: { type: "boolean" },
867
+ extraFields: { type: "array", items: EXTRA_FIELD_SCHEMA }
868
+ }
869
+ }
870
+ }
871
+ }
872
+ };
873
+ ALLOWED_EDGES_REQUIRED_MESSAGE = "Invalid allowedEdges: field is required. Use allowedEdges: [] or allowedEdges: null to adopt the built-in DEFAULT_SCHEMA.allowedEdges, or list explicit {from, to, kind} triples as a strict whitelist that replaces the default table.";
874
+ }
875
+ });
876
+
373
877
  // src/target-selector.ts
374
878
  function parseTargetSelector(value) {
375
879
  const separator = value.indexOf(":");
@@ -502,8 +1006,8 @@ var init_git_changes = __esm({
502
1006
  // src/versioned-traceability.ts
503
1007
  import { createHash } from "crypto";
504
1008
  import { existsSync } from "fs";
505
- import { mkdir, readFile, writeFile } from "fs/promises";
506
- import { dirname, join as join2, relative as relative2 } from "path";
1009
+ import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
1010
+ import { dirname, join as join3, relative as relative2 } from "path";
507
1011
  async function buildVersionIndex(root, graph) {
508
1012
  const scannedGraph = graph ?? await scanArtifacts(root);
509
1013
  const hashCache = /* @__PURE__ */ new Map();
@@ -639,7 +1143,7 @@ async function auditVersionLock(root, lockPath = VERSION_LOCK_PATH, graph, confi
639
1143
  for (const entry of lock.locks) {
640
1144
  if (entry.kind !== "verifies") continue;
641
1145
  const sourcePath = entry.source.path;
642
- const fullSourcePath = join2(root, sourcePath);
1146
+ const fullSourcePath = join3(root, sourcePath);
643
1147
  if (!existsSync(fullSourcePath)) continue;
644
1148
  let liveness = livenessCache.get(sourcePath);
645
1149
  if (liveness === void 0) {
@@ -734,14 +1238,14 @@ async function auditVersionLock(root, lockPath = VERSION_LOCK_PATH, graph, confi
734
1238
  currentArtifactHash: targetNode.contentHash
735
1239
  });
736
1240
  }
737
- if (!existsSync(join2(root, sourceNode.path))) {
1241
+ if (!existsSync(join3(root, sourceNode.path))) {
738
1242
  entryIssues.push({
739
1243
  status: "orphan_lock",
740
1244
  edgeId: relEdgeId,
741
1245
  message: `Artifact relation source file ${sourceNode.path} no longer exists`
742
1246
  });
743
1247
  }
744
- if (!existsSync(join2(root, targetNode.path))) {
1248
+ if (!existsSync(join3(root, targetNode.path))) {
745
1249
  entryIssues.push({
746
1250
  status: "orphan_lock",
747
1251
  edgeId: relEdgeId,
@@ -945,17 +1449,22 @@ async function bootstrapVersionLock(root, options = {}) {
945
1449
  source: sourceRefFromNode(source)
946
1450
  });
947
1451
  }
948
- const artifactRelationEntries = [];
1452
+ const artifactRelationEntries = /* @__PURE__ */ new Map();
949
1453
  for (const edge2 of artifactRelationEdges(index)) {
950
1454
  const source = nodeByUid.get(edge2.from);
951
1455
  const target = nodeByUid.get(edge2.to);
952
1456
  if (!source || !target) continue;
953
- artifactRelationEntries.push(artifactRelationLockFromEdge(edge2, source, target));
1457
+ const relationLock = artifactRelationLockFromEdge(edge2, source, target);
1458
+ const identity = artifactRelationLockSortKey(relationLock);
1459
+ if (artifactRelationEntries.has(identity)) {
1460
+ continue;
1461
+ }
1462
+ artifactRelationEntries.set(identity, relationLock);
954
1463
  }
955
1464
  const next = {
956
1465
  schemaVersion: VERSION_LOCK_SCHEMA_VERSION,
957
1466
  locks: sortBy([...entries.values()], (item) => item.edgeId),
958
- artifactRelations: sortBy(artifactRelationEntries, artifactRelationLockSortKey)
1467
+ artifactRelations: sortBy([...artifactRelationEntries.values()], artifactRelationLockSortKey)
959
1468
  };
960
1469
  await writeVersionLock(root, lockPath, next);
961
1470
  return next;
@@ -1343,7 +1852,7 @@ function renderTraceVersionMarkdown(result) {
1343
1852
  async function readVersionLock(root, lockPath) {
1344
1853
  const safeLockPath = normalizeRelativePath(root, lockPath);
1345
1854
  try {
1346
- const raw = await readFile(join2(root, safeLockPath), "utf-8");
1855
+ const raw = await readFile2(join3(root, safeLockPath), "utf-8");
1347
1856
  let parsed;
1348
1857
  try {
1349
1858
  parsed = JSON.parse(raw);
@@ -1502,7 +2011,7 @@ function requireSafeRelativePath(value, path) {
1502
2011
  }
1503
2012
  async function writeVersionLock(root, lockPath, lock) {
1504
2013
  const safeLockPath = normalizeRelativePath(root, lockPath);
1505
- const fullPath = join2(root, safeLockPath);
2014
+ const fullPath = join3(root, safeLockPath);
1506
2015
  await mkdir(dirname(fullPath), { recursive: true });
1507
2016
  await writeFile(fullPath, `${JSON.stringify(lock, null, 2)}
1508
2017
  `);
@@ -1685,7 +2194,7 @@ async function hashRelativePath(root, path, cache) {
1685
2194
  const normalized = normalizeRelativePath(root, path);
1686
2195
  const cached = cache.get(normalized);
1687
2196
  if (cached) return cached;
1688
- const content = await readFile(join2(root, normalized));
2197
+ const content = await readFile2(join3(root, normalized));
1689
2198
  const hash = `sha256:${createHash("sha256").update(content).digest("hex")}`;
1690
2199
  cache.set(normalized, hash);
1691
2200
  return hash;
@@ -1708,10 +2217,10 @@ async function getTestFileRunnerLiveness(root, filePath, config) {
1708
2217
  if (!/e2e/i.test(filePath) && !/\.e2e\./i.test(filePath)) {
1709
2218
  return "active";
1710
2219
  }
1711
- const fullSourcePath = join2(root, filePath);
2220
+ const fullSourcePath = join3(root, filePath);
1712
2221
  if (!existsSync(fullSourcePath)) return "inactive";
1713
2222
  try {
1714
- const content = await readFile(fullSourcePath, "utf-8");
2223
+ const content = await readFile2(fullSourcePath, "utf-8");
1715
2224
  return /\/\/!?\s*@(?:e2e_test|tc)\s+/.test(content) ? "active" : "inactive";
1716
2225
  } catch {
1717
2226
  return "inactive";
@@ -1774,7 +2283,7 @@ var init_versioned_traceability = __esm({
1774
2283
  });
1775
2284
 
1776
2285
  // src/impact.ts
1777
- import { isAbsolute, normalize, relative as relative3, resolve } from "path";
2286
+ import { isAbsolute as isAbsolute2, normalize, relative as relative3, resolve } from "path";
1778
2287
  async function computeImpact(root, options = {}) {
1779
2288
  const absoluteRoot = resolve(root);
1780
2289
  const mode = options.mode ?? "worktree";
@@ -1848,7 +2357,7 @@ function normalizeExplicitPaths(root, paths) {
1848
2357
  const normalized = paths.map((input) => {
1849
2358
  const value = input.trim();
1850
2359
  if (!value) return "";
1851
- const absolutePath = isAbsolute(value) ? normalize(value) : resolve(root, value);
2360
+ const absolutePath = isAbsolute2(value) ? normalize(value) : resolve(root, value);
1852
2361
  const projectRelative = relative3(root, absolutePath);
1853
2362
  const result = projectRelative.replace(/\\/g, "/").replace(/^\.\//, "");
1854
2363
  if (result === ".." || result.startsWith("../") || result.startsWith("/")) {
@@ -2467,7 +2976,7 @@ var init_packet_assembler = __esm({
2467
2976
 
2468
2977
  // src/packet-audit.ts
2469
2978
  import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
2470
- import { join as join3 } from "path";
2979
+ import { join as join4 } from "path";
2471
2980
  function parseTargetsFile(content, schema) {
2472
2981
  const validTypes = schema ? new Set(getTargetArtifactTypes(schema)) : VALID_TYPES;
2473
2982
  const validTypesLabel = [...validTypes].join(", ");
@@ -2558,7 +3067,7 @@ async function auditSingleTarget(target, graph, options) {
2558
3067
  const fmt = options.format ?? "markdown";
2559
3068
  const ext = fmt === "json" ? "json" : "md";
2560
3069
  const filename = `${target.type}-${target.id}.packet.${ext}`;
2561
- const outPath = join3(options.outDir, filename);
3070
+ const outPath = join4(options.outDir, filename);
2562
3071
  let content;
2563
3072
  if (fmt === "json") {
2564
3073
  content = JSON.stringify(packet, null, 2) + "\n";
@@ -2638,7 +3147,7 @@ async function auditPackets(root, targets, options, graph) {
2638
3147
  ...isCompact ? { summaryDetail: "compact", countsByType } : {}
2639
3148
  };
2640
3149
  if (options.outDir) {
2641
- const summaryPath = join3(options.outDir, "summary.json");
3150
+ const summaryPath = join4(options.outDir, "summary.json");
2642
3151
  await writeFile2(summaryPath, JSON.stringify(summary, null, 2) + "\n", "utf-8");
2643
3152
  }
2644
3153
  return summary;
@@ -3009,7 +3518,7 @@ var init_packet_prompt_validator = __esm({
3009
3518
  // src/native-binding-diagnostics.ts
3010
3519
  import { existsSync as existsSync2, readdirSync } from "fs";
3011
3520
  import { createRequire } from "module";
3012
- import { dirname as dirname2, join as join4 } from "path";
3521
+ import { dirname as dirname2, join as join5 } from "path";
3013
3522
  import { fileURLToPath } from "url";
3014
3523
  function parsePnpmVersion(stdout) {
3015
3524
  const trimmed = stdout.trim();
@@ -3150,7 +3659,7 @@ function buildNativeBindingSuccessDiagnostic(probeContext) {
3150
3659
  function findPackageRoot(anchorFile) {
3151
3660
  let dir = dirname2(anchorFile);
3152
3661
  for (; ; ) {
3153
- if (existsSync2(join4(dir, "package.json"))) return dir;
3662
+ if (existsSync2(join5(dir, "package.json"))) return dir;
3154
3663
  const parent = dirname2(dir);
3155
3664
  if (parent === dir) return void 0;
3156
3665
  dir = parent;
@@ -3167,9 +3676,9 @@ function abiPrebuiltHint(detail) {
3167
3676
  return match ? `\uFF1Bprebuilt \u76EE\u6807 NODE_MODULE_VERSION=${match[1]}` : "";
3168
3677
  }
3169
3678
  function betterSqlite3PackagePresent(root) {
3170
- const direct = join4(root, "node_modules", "better-sqlite3", "package.json");
3679
+ const direct = join5(root, "node_modules", "better-sqlite3", "package.json");
3171
3680
  if (existsSync2(direct)) return true;
3172
- const pnpmDir = join4(root, "node_modules", ".pnpm");
3681
+ const pnpmDir = join5(root, "node_modules", ".pnpm");
3173
3682
  let entries;
3174
3683
  try {
3175
3684
  entries = readdirSync(pnpmDir);
@@ -3178,7 +3687,7 @@ function betterSqlite3PackagePresent(root) {
3178
3687
  }
3179
3688
  return entries.some((entry) => {
3180
3689
  if (!entry.startsWith("better-sqlite3@")) return false;
3181
- return existsSync2(join4(pnpmDir, entry, "node_modules", "better-sqlite3", "package.json"));
3690
+ return existsSync2(join5(pnpmDir, entry, "node_modules", "better-sqlite3", "package.json"));
3182
3691
  });
3183
3692
  }
3184
3693
  var PNPM_ALLOW_BUILDS_SNIPPET;
@@ -3193,7 +3702,7 @@ var init_native_binding_diagnostics = __esm({
3193
3702
  import { execFile as execFile2 } from "child_process";
3194
3703
  import { constants, readFileSync, realpathSync } from "fs";
3195
3704
  import { access } from "fs/promises";
3196
- import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, resolve as resolve3 } from "path";
3705
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute3, join as join6, resolve as resolve3 } from "path";
3197
3706
  import { promisify as promisify2 } from "util";
3198
3707
  async function resolveArtifactGraphCli(root, options = {}) {
3199
3708
  const pathCli = await findCommandOnPath("artifact-graph");
@@ -3201,7 +3710,7 @@ async function resolveArtifactGraphCli(root, options = {}) {
3201
3710
  const candidates = [
3202
3711
  {
3203
3712
  source: "node_modules",
3204
- path: join5(root, "node_modules/.bin/artifact-graph"),
3713
+ path: join6(root, "node_modules/.bin/artifact-graph"),
3205
3714
  exists: false
3206
3715
  },
3207
3716
  {
@@ -3234,8 +3743,8 @@ async function resolveArtifactGraphCli(root, options = {}) {
3234
3743
  }
3235
3744
  async function doctorArtifactChain(root, options = {}) {
3236
3745
  const cli = await resolveArtifactGraphCli(root, options);
3237
- const configPath = join5(root, "artifact-graph.config.yaml");
3238
- const lockPath = join5(root, VERSION_LOCK_PATH);
3746
+ const configPath = join6(root, "artifact-graph.config.yaml");
3747
+ const lockPath = join6(root, VERSION_LOCK_PATH);
3239
3748
  const supportedCommands = cli.path ? await detectSupportedCommands(cli.path) : [];
3240
3749
  const nodeCompatible = isNodeCompatible(process.versions.node);
3241
3750
  const pnpmVersion = await detectPnpmVersion();
@@ -3255,12 +3764,28 @@ async function doctorArtifactChain(root, options = {}) {
3255
3764
  probedFrom
3256
3765
  };
3257
3766
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3767
+ const configDiagnosis = await diagnoseProjectConfig(root);
3768
+ const configShapeMessages = [
3769
+ ...configDiagnosis.errors.map((item) => item.message),
3770
+ ...configDiagnosis.warnings.map((item) => item.message)
3771
+ ];
3772
+ const loadConfigMessages = [];
3773
+ if (configDiagnosis.exists && configDiagnosis.errors.length === 0) {
3774
+ try {
3775
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_index(), index_exports));
3776
+ await loadConfig2(root);
3777
+ } catch (error) {
3778
+ loadConfigMessages.push(error.message);
3779
+ }
3780
+ }
3258
3781
  const warnings = [
3259
3782
  ...cli.warnings,
3260
3783
  ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3261
3784
  ...probe.ok ? [] : [
3262
3785
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3263
- ]
3786
+ ],
3787
+ ...configShapeMessages,
3788
+ ...loadConfigMessages
3264
3789
  ];
3265
3790
  return {
3266
3791
  schemaVersion: "1.0",
@@ -3370,7 +3895,7 @@ async function findCommandOnPath(command) {
3370
3895
  }
3371
3896
  }
3372
3897
  function resolveCandidatePath(root, candidatePath) {
3373
- return isAbsolute2(candidatePath) ? candidatePath : resolve3(root, candidatePath);
3898
+ return isAbsolute3(candidatePath) ? candidatePath : resolve3(root, candidatePath);
3374
3899
  }
3375
3900
  function isNodeCompatible(version) {
3376
3901
  const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
@@ -3440,6 +3965,7 @@ var init_cli_resolver = __esm({
3440
3965
  "src/cli-resolver.ts"() {
3441
3966
  "use strict";
3442
3967
  init_versioned_traceability();
3968
+ init_doctor();
3443
3969
  init_native_binding_diagnostics();
3444
3970
  execFileAsync2 = promisify2(execFile2);
3445
3971
  REQUIRED_NODE_VERSION = ">=22.22.2 <23";
@@ -3471,7 +3997,7 @@ var init_cli_resolver = __esm({
3471
3997
 
3472
3998
  // src/git-hook-path.ts
3473
3999
  import { execFile as execFile3 } from "child_process";
3474
- import { isAbsolute as isAbsolute3, resolve as resolve4 } from "path";
4000
+ import { isAbsolute as isAbsolute4, resolve as resolve4 } from "path";
3475
4001
  import { promisify as promisify3 } from "util";
3476
4002
  async function resolveGitHookPath(root, hookName) {
3477
4003
  const { stdout } = await execFileAsync3("git", [
@@ -3483,7 +4009,7 @@ async function resolveGitHookPath(root, hookName) {
3483
4009
  ]);
3484
4010
  const value = stdout.trim();
3485
4011
  if (!value) throw new Error(`Git returned an empty hook path for ${hookName}`);
3486
- return isAbsolute3(value) ? resolve4(value) : resolve4(root, value);
4012
+ return isAbsolute4(value) ? resolve4(value) : resolve4(root, value);
3487
4013
  }
3488
4014
  var execFileAsync3;
3489
4015
  var init_git_hook_path = __esm({
@@ -3497,7 +4023,7 @@ var init_git_hook_path = __esm({
3497
4023
  import { constants as constants2 } from "fs";
3498
4024
  import { randomUUID } from "crypto";
3499
4025
  import { lstat, mkdir as mkdir3, open, readlink, rename, unlink } from "fs/promises";
3500
- import { basename as basename2, dirname as dirname4, join as join6 } from "path";
4026
+ import { basename as basename2, dirname as dirname4, join as join7 } from "path";
3501
4027
  function detectHookInterpreter(content) {
3502
4028
  if (content.trim().length === 0) {
3503
4029
  return "empty";
@@ -3809,7 +4335,7 @@ async function removeHookAtomically(hookPath, snapshot) {
3809
4335
  }
3810
4336
  async function writeHookAtomically(hookPath, content, snapshot, mode) {
3811
4337
  await mkdir3(dirname4(hookPath), { recursive: true });
3812
- const temporaryPath = join6(dirname4(hookPath), `.${basename2(hookPath)}.${randomUUID()}.tmp`);
4338
+ const temporaryPath = join7(dirname4(hookPath), `.${basename2(hookPath)}.${randomUUID()}.tmp`);
3813
4339
  let temporaryExists = false;
3814
4340
  try {
3815
4341
  const temporary = await open(temporaryPath, "wx", mode);
@@ -3927,7 +4453,7 @@ var init_hook_installer = __esm({
3927
4453
  // src/professional-conclusion.ts
3928
4454
  import { access as access2 } from "fs/promises";
3929
4455
  import { createRequire as createRequire2 } from "module";
3930
- import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute4, join as join7, resolve as resolve5 } from "path";
4456
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute5, join as join8, resolve as resolve5 } from "path";
3931
4457
  import { pathToFileURL } from "url";
3932
4458
  async function loadContracts() {
3933
4459
  return await import(CONTRACTS_PACKAGE_NAME);
@@ -3954,7 +4480,7 @@ function harnessKind(error) {
3954
4480
  return typeof details?.kind === "string" ? details.kind : void 0;
3955
4481
  }
3956
4482
  async function missingRequiredConfig(root) {
3957
- const configPath = join7(root, "artifact-graph.config.yaml");
4483
+ const configPath = join8(root, "artifact-graph.config.yaml");
3958
4484
  try {
3959
4485
  await access2(configPath);
3960
4486
  return void 0;
@@ -4127,7 +4653,7 @@ async function assertConclusionShape(conclusion) {
4127
4653
  }
4128
4654
  }
4129
4655
  async function publishConclusion(absoluteOutput, conclusion) {
4130
- if (!isAbsolute4(absoluteOutput)) {
4656
+ if (!isAbsolute5(absoluteOutput)) {
4131
4657
  return "--conclusion-output must be an absolute path";
4132
4658
  }
4133
4659
  const outputRoot = dirname5(absoluteOutput);
@@ -4165,7 +4691,7 @@ async function runCheckProfessional(options) {
4165
4691
  if (options.conclusionOutput === void 0) {
4166
4692
  return { conclusion };
4167
4693
  }
4168
- if (!isAbsolute4(options.conclusionOutput)) {
4694
+ if (!isAbsolute5(options.conclusionOutput)) {
4169
4695
  return { conclusion, writeError: "--conclusion-output must be an absolute path" };
4170
4696
  }
4171
4697
  const writeError = await publishConclusion(resolve5(options.conclusionOutput), conclusion);
@@ -4619,9 +5145,9 @@ var init_review_result_validator = __esm({
4619
5145
 
4620
5146
  // src/contract-kernel.ts
4621
5147
  import { createHash as createHash2 } from "crypto";
4622
- import { readFile as readFile2, readdir as readdir2 } from "fs/promises";
4623
- import { join as join8 } from "path";
4624
- import _AjvModule from "ajv";
5148
+ import { readFile as readFile3, readdir as readdir2 } from "fs/promises";
5149
+ import { join as join9 } from "path";
5150
+ import _AjvModule2 from "ajv";
4625
5151
  function isOfficialNamespace(namespace) {
4626
5152
  return OFFICIAL_NAMESPACE_PATTERN.test(namespace);
4627
5153
  }
@@ -4901,7 +5427,7 @@ function validatePolicyCompatibility(policy, baseContract) {
4901
5427
  };
4902
5428
  }
4903
5429
  async function loadContract(contractPath, options) {
4904
- const rawContent = await readFile2(contractPath, "utf-8");
5430
+ const rawContent = await readFile3(contractPath, "utf-8");
4905
5431
  let schema;
4906
5432
  try {
4907
5433
  schema = JSON.parse(rawContent);
@@ -4952,7 +5478,7 @@ async function loadContractsFromDirectory(contractsDir, options) {
4952
5478
  const entries = await readdir2(contractsDir, { withFileTypes: true });
4953
5479
  for (const entry of entries) {
4954
5480
  if (entry.isDirectory()) {
4955
- const schemaPath = join8(contractsDir, entry.name, "schema.json");
5481
+ const schemaPath = join9(contractsDir, entry.name, "schema.json");
4956
5482
  const contract = await loadContract(schemaPath, options);
4957
5483
  contracts.push(contract);
4958
5484
  }
@@ -4962,7 +5488,7 @@ async function loadContractsFromDirectory(contractsDir, options) {
4962
5488
  function getValidator(schema) {
4963
5489
  const key = `${schema.$id || "default"}#${computeRevisionDigest(JSON.stringify(schema))}`;
4964
5490
  if (!_validatorCache.has(key)) {
4965
- const AjvCtor = _AjvModule;
5491
+ const AjvCtor = _AjvModule2;
4966
5492
  const ajv = new AjvCtor({ allErrors: true, strict: false });
4967
5493
  _validatorCache.set(key, ajv.compile(schema));
4968
5494
  }
@@ -5497,7 +6023,7 @@ var init_restructure_software = __esm({
5497
6023
  // src/restructure-file-set.ts
5498
6024
  import { createHash as createHash3 } from "crypto";
5499
6025
  import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
5500
- import { join as join9, resolve as resolve6 } from "path";
6026
+ import { join as join10, resolve as resolve6 } from "path";
5501
6027
  async function loadFoundationModule() {
5502
6028
  return await import(FOUNDATION_PACKAGE_NAME);
5503
6029
  }
@@ -5594,7 +6120,7 @@ async function qualifyRestructureMechanism(root) {
5594
6120
  return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5595
6121
  }
5596
6122
  async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5597
- const target = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
6123
+ const target = join10(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5598
6124
  const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5599
6125
  let info = await current();
5600
6126
  if (info === null) {
@@ -5708,7 +6234,7 @@ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5708
6234
  return await verifyMechanismResult(raw);
5709
6235
  }
5710
6236
  async function observeRestructureJournal(canonicalRoot) {
5711
- const journalRoot = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
6237
+ const journalRoot = join10(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5712
6238
  const module = await loadFoundationModule();
5713
6239
  try {
5714
6240
  return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
@@ -5917,8 +6443,8 @@ var init_restructure_file_set = __esm({
5917
6443
 
5918
6444
  // src/restructure.ts
5919
6445
  import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
5920
- import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
5921
- import { dirname as dirname6, isAbsolute as isAbsolute5, join as join10, posix, relative as relative4, resolve as resolve7 } from "path";
6446
+ import { lstat as lstat3, readFile as readFile4, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
6447
+ import { dirname as dirname6, isAbsolute as isAbsolute6, join as join11, posix, relative as relative4, resolve as resolve7 } from "path";
5922
6448
  import { fileURLToPath as fileURLToPath2 } from "url";
5923
6449
  function digestBytes(value) {
5924
6450
  return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
@@ -5934,7 +6460,7 @@ function digestRestructureValue(value) {
5934
6460
  return digestBytes(canonicalJson(value));
5935
6461
  }
5936
6462
  function normalizeRelativePath2(value) {
5937
- if (!value || value.includes("\0") || isAbsolute5(value)) return void 0;
6463
+ if (!value || value.includes("\0") || isAbsolute6(value)) return void 0;
5938
6464
  const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5939
6465
  if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5940
6466
  return normalized;
@@ -5954,7 +6480,7 @@ async function readContainedFileWithMode(root, path) {
5954
6480
  try {
5955
6481
  const info = await lstat3(absolutePath);
5956
6482
  if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
5957
- return { buffer: await readFile3(absolutePath), mode: info.mode & MAX_POSIX_MODE };
6483
+ return { buffer: await readFile4(absolutePath), mode: info.mode & MAX_POSIX_MODE };
5958
6484
  } catch (error) {
5959
6485
  if (error.code === "ENOENT") return void 0;
5960
6486
  throw error;
@@ -5982,7 +6508,7 @@ async function configSnapshot(root) {
5982
6508
  return snapshotFile(root, "artifact-graph.config.yaml");
5983
6509
  }
5984
6510
  async function loadRestructureContract(name) {
5985
- return loadContract(join10(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
6511
+ return loadContract(join11(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
5986
6512
  }
5987
6513
  async function validateDomainContract(name, value) {
5988
6514
  const contract = await loadRestructureContract(name);
@@ -6257,14 +6783,14 @@ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6257
6783
  async function visit(directory) {
6258
6784
  for (const entry of await readdir3(directory, { withFileTypes: true })) {
6259
6785
  if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6260
- const absolute = join10(directory, entry.name);
6786
+ const absolute = join11(directory, entry.name);
6261
6787
  if (entry.isDirectory()) {
6262
6788
  await visit(absolute);
6263
6789
  continue;
6264
6790
  }
6265
6791
  if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
6266
6792
  const path = relative4(root, absolute).replace(/\\/g, "/");
6267
- const raw = await readFile3(absolute, "utf8");
6793
+ const raw = await readFile4(absolute, "utf8");
6268
6794
  const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
6269
6795
  const lines = raw.split(/\r?\n/);
6270
6796
  for (const [index, line] of lines.entries()) {
@@ -6329,13 +6855,13 @@ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PU
6329
6855
  async function visit(directory) {
6330
6856
  for (const entry of await readdir3(directory, { withFileTypes: true })) {
6331
6857
  if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6332
- const absolute = join10(directory, entry.name);
6858
+ const absolute = join11(directory, entry.name);
6333
6859
  if (entry.isDirectory()) {
6334
6860
  await visit(absolute);
6335
6861
  } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
6336
6862
  const path = relative4(root, absolute).replace(/\\/g, "/");
6337
6863
  if (excludedPaths.has(path)) continue;
6338
- const raw = await readFile3(absolute, "utf8");
6864
+ const raw = await readFile4(absolute, "utf8");
6339
6865
  raw.split(/\r?\n/).forEach((line, index) => {
6340
6866
  for (const reference of references) {
6341
6867
  if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
@@ -6838,7 +7364,7 @@ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6838
7364
  }
6839
7365
  let bytes;
6840
7366
  try {
6841
- bytes = await readFile3(absolute);
7367
+ bytes = await readFile4(absolute);
6842
7368
  } catch (cause) {
6843
7369
  return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6844
7370
  }
@@ -6870,7 +7396,7 @@ function planRootIdentityFindings(document) {
6870
7396
  findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6871
7397
  }
6872
7398
  const relativePlan = relative4(document.root, document.realPath);
6873
- if (!relativePlan || relativePlan.startsWith("..") || isAbsolute5(relativePlan)) {
7399
+ if (!relativePlan || relativePlan.startsWith("..") || isAbsolute6(relativePlan)) {
6874
7400
  findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6875
7401
  }
6876
7402
  return findings;
@@ -7061,7 +7587,7 @@ var init_restructure = __esm({
7061
7587
  MAX_POSIX_MODE = 511;
7062
7588
  CREATE_MODE_BASE = 438;
7063
7589
  MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname6(fileURLToPath2(import.meta.url));
7064
- CONTRACT_ROOT = join10(MODULE_DIRECTORY, "..", "contracts");
7590
+ CONTRACT_ROOT = join11(MODULE_DIRECTORY, "..", "contracts");
7065
7591
  SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
7066
7592
  TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
7067
7593
  MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
@@ -7072,11 +7598,176 @@ var init_restructure = __esm({
7072
7598
  });
7073
7599
 
7074
7600
  // src/index.ts
7601
+ var index_exports = {};
7602
+ __export(index_exports, {
7603
+ ALWAYS_PRESENT: () => ALWAYS_PRESENT_ITEMS,
7604
+ BASELINE_CONSTRAINTS: () => BASELINE_CONSTRAINTS,
7605
+ BASELINE_CONSTRAINTS_COUNT: () => BASELINE_CONSTRAINTS_COUNT,
7606
+ BASELINE_ITEMS_COUNT: () => BASELINE_ITEMS_COUNT,
7607
+ CONTRACTS_PACKAGE_NAME: () => CONTRACTS_PACKAGE_NAME2,
7608
+ CONTRACT_ERROR_CODES: () => CONTRACT_ERROR_CODES,
7609
+ ContractCatalog: () => ContractCatalog,
7610
+ ContractError: () => ContractError,
7611
+ ContractRegistry: () => ContractRegistry,
7612
+ DEFAULT_MAX_CHARS: () => DEFAULT_MAX_CHARS,
7613
+ DEFAULT_SCHEMA: () => DEFAULT_SCHEMA,
7614
+ E2E_NORMALIZER_CONFIG: () => E2E_NORMALIZER_CONFIG,
7615
+ FILE_SET_RESULT_OBJECT: () => FILE_SET_RESULT_OBJECT,
7616
+ FOUNDATION_PACKAGE_NAME: () => FOUNDATION_PACKAGE_NAME,
7617
+ GRAPH_DOMAIN_CODES: () => GRAPH_DOMAIN_CODES,
7618
+ GRAPH_PROVIDER_ENTRY: () => GRAPH_PROVIDER_ENTRY,
7619
+ GRAPH_PROVIDER_ID: () => GRAPH_PROVIDER_ID,
7620
+ MIN_PROMPT_CHARS: () => MIN_PROMPT_CHARS,
7621
+ PROFESSIONAL_CONCLUSION_OBJECT: () => PROFESSIONAL_CONCLUSION_OBJECT,
7622
+ RESTRUCTURE_MAX_OPERATIONS: () => RESTRUCTURE_MAX_OPERATIONS,
7623
+ RESTRUCTURE_MAX_TOTAL_BYTES: () => RESTRUCTURE_MAX_TOTAL_BYTES,
7624
+ RESTRUCTURE_PLAN_SCHEMA_VERSION: () => RESTRUCTURE_PLAN_SCHEMA_VERSION,
7625
+ RESTRUCTURE_QUALIFIED_ARCH: () => RESTRUCTURE_QUALIFIED_ARCH,
7626
+ RESTRUCTURE_QUALIFIED_FILESYSTEM: () => RESTRUCTURE_QUALIFIED_FILESYSTEM,
7627
+ RESTRUCTURE_QUALIFIED_PLATFORM: () => RESTRUCTURE_QUALIFIED_PLATFORM,
7628
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH: () => RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
7629
+ RESTRUCTURE_RECOVERY_REL_PATH: () => RESTRUCTURE_RECOVERY_REL_PATH,
7630
+ RESTRUCTURE_RECOVERY_ROOT_MODE: () => RESTRUCTURE_RECOVERY_ROOT_MODE,
7631
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS: () => RESTRUCTURE_VALIDATION_TIMEOUT_MS,
7632
+ TARGET_ARTIFACT_TYPES: () => TARGET_ARTIFACT_TYPES,
7633
+ VALID_PACKET_TARGET_TYPES: () => VALID_PACKET_TARGET_TYPES,
7634
+ VERSION_INDEX_SCHEMA_VERSION: () => VERSION_INDEX_SCHEMA_VERSION,
7635
+ VERSION_LOCK_PATH: () => VERSION_LOCK_PATH,
7636
+ VERSION_LOCK_SCHEMA_VERSION: () => VERSION_LOCK_SCHEMA_VERSION,
7637
+ applyPreparedManagedHookBlocks: () => applyPreparedManagedHookBlocks,
7638
+ applyRestructure: () => applyRestructure,
7639
+ applyRestructureFileSet: () => applyRestructureFileSet,
7640
+ assemblePacket: () => assemblePacket,
7641
+ auditPackets: () => auditPackets,
7642
+ auditVersionLock: () => auditVersionLock,
7643
+ bootstrapVersionLock: () => bootstrapVersionLock,
7644
+ buildFileSetApplyRequest: () => buildFileSetApplyRequest,
7645
+ buildGraph: () => buildGraph,
7646
+ buildVersionIndex: () => buildVersionIndex,
7647
+ candidateByteDigest: () => candidateByteDigest,
7648
+ collectChangedPaths: () => collectChangedPaths,
7649
+ computeCoverageBoundary: () => computeCoverageBoundary,
7650
+ computeE2eCoverageStats: () => computeE2eCoverageStats,
7651
+ computeImpact: () => computeImpact,
7652
+ computeRevisionDigest: () => computeRevisionDigest,
7653
+ createModeForUmask: () => createModeForUmask,
7654
+ createRestructureRootBinding: () => createRestructureRootBinding,
7655
+ createRestructureValidationCallback: () => createRestructureValidationCallback,
7656
+ diagnoseConfigDocument: () => diagnoseConfigDocument,
7657
+ diagnoseProjectConfig: () => diagnoseProjectConfig,
7658
+ digestRestructureValue: () => digestRestructureValue,
7659
+ dirname: () => dirname7,
7660
+ discoverAndAuditPackets: () => discoverAndAuditPackets,
7661
+ discoverTargets: () => discoverTargets,
7662
+ doctorArtifactChain: () => doctorArtifactChain,
7663
+ ensureRestructureMechanismRoot: () => ensureRestructureMechanismRoot,
7664
+ extname: () => extname,
7665
+ filterGraphByView: () => filterGraphByView,
7666
+ formatContextMarkdown: () => formatContextMarkdown,
7667
+ gateRestructureOperationPlan: () => gateRestructureOperationPlan,
7668
+ generateE2eRegistry: () => generateE2eRegistry,
7669
+ getArtifactTypeMetadata: () => getArtifactTypeMetadata,
7670
+ getConfigDiagnostics: () => getConfigDiagnostics,
7671
+ getExternalEntryInfo: () => getExternalEntryInfo,
7672
+ getTargetArtifactTypes: () => getTargetArtifactTypes,
7673
+ inspectRestructure: () => inspectRestructure,
7674
+ installManagedHookBlock: () => installManagedHookBlock,
7675
+ isOfficialNamespace: () => isOfficialNamespace,
7676
+ isPacketTargetType: () => isPacketTargetType,
7677
+ isPacketTargetTypeDynamic: () => isPacketTargetTypeDynamic,
7678
+ isTargetArtifactType: () => isTargetArtifactType,
7679
+ isVersionLockIssueBlocking: () => isVersionLockIssueBlocking,
7680
+ loadConfig: () => loadConfig,
7681
+ loadContract: () => loadContract,
7682
+ loadContractCatalog: () => loadContractCatalog,
7683
+ loadContractsFromDirectory: () => loadContractsFromDirectory,
7684
+ loadFoundationModule: () => loadFoundationModule,
7685
+ locateSoftwareRecord: () => locateSoftwareRecord,
7686
+ markdownRecordHeadings: () => markdownRecordHeadings,
7687
+ matchesConfiguredArtifactPath: () => matchesConfiguredArtifactPath,
7688
+ nextId: () => nextId,
7689
+ normalizeE2eLegacyArtifact: () => normalizeE2eLegacyArtifact,
7690
+ normalizeToCanonical: () => normalizeToCanonical,
7691
+ observeRestructureJournal: () => observeRestructureJournal,
7692
+ parseTargetSelector: () => parseTargetSelector,
7693
+ parseTargetsFile: () => parseTargetsFile,
7694
+ planRestructure: () => planRestructure,
7695
+ planningUmask: () => planningUmask,
7696
+ prepareManagedHookBlock: () => prepareManagedHookBlock,
7697
+ projectRestructureFileSetResult: () => projectRestructureFileSetResult,
7698
+ pruneRestructureFileSet: () => pruneRestructureFileSet,
7699
+ pruneRestructureRecovery: () => pruneRestructureRecovery,
7700
+ qualifyRestructureMechanism: () => qualifyRestructureMechanism,
7701
+ queryGraph: () => queryGraph,
7702
+ recoverRestructure: () => recoverRestructure,
7703
+ recoverRestructureFileSet: () => recoverRestructureFileSet,
7704
+ refreshVersionLock: () => refreshVersionLock,
7705
+ renderCoverageBoundaryMarkdown: () => renderCoverageBoundaryMarkdown,
7706
+ renderDoctorMarkdown: () => renderDoctorMarkdown,
7707
+ renderImpactMarkdown: () => renderImpactMarkdown,
7708
+ renderMermaid: () => renderMermaid,
7709
+ renderPacketMarkdown: () => renderPacketMarkdown,
7710
+ renderPacketPrompt: () => renderPacketPrompt,
7711
+ renderTraceVersionMarkdown: () => renderTraceVersionMarkdown,
7712
+ renderVersionLockAuditMarkdown: () => renderVersionLockAuditMarkdown,
7713
+ renderVersionLockRefreshMarkdown: () => renderVersionLockRefreshMarkdown,
7714
+ replaceSoftwareHeader: () => replaceSoftwareHeader,
7715
+ resolveArtifactContext: () => resolveArtifactContext,
7716
+ resolveArtifactGraphCli: () => resolveArtifactGraphCli,
7717
+ resolveArtifactTypeName: () => resolveArtifactTypeName,
7718
+ resolveCliTarget: () => resolveCliTarget,
7719
+ resolveGitHookPath: () => resolveGitHookPath,
7720
+ resolveMatrixEdges: () => resolveMatrixEdges,
7721
+ resolveNodeTimeView: () => resolveNodeTimeView,
7722
+ resolveRealRoot: () => resolveRealRoot,
7723
+ restructureBoundaryFindings: () => restructureBoundaryFindings,
7724
+ runCheckProfessional: () => runCheckProfessional,
7725
+ runReadProof: () => runReadProof,
7726
+ scanArtifacts: () => scanArtifacts,
7727
+ traceVersion: () => traceVersion,
7728
+ updateVersionLock: () => updateVersionLock,
7729
+ validateContractAgainstSchema: () => validateContractAgainstSchema,
7730
+ validateExecutableTraceability: () => validateExecutableTraceability,
7731
+ validateGraph: () => validateGraph,
7732
+ validateNamespaceAuthority: () => validateNamespaceAuthority,
7733
+ validatePacket: () => validatePacket,
7734
+ validatePacketMarkdown: () => validatePacketMarkdown,
7735
+ validatePacketPrompt: () => validatePacketPrompt,
7736
+ validatePolicyCompatibility: () => validatePolicyCompatibility,
7737
+ validateReviewResult: () => validateReviewResult,
7738
+ validateScenarioPrdLinkIndex: () => validateScenarioPrdLinkIndex,
7739
+ validateScenarioPrdLinks: () => validateScenarioPrdLinks,
7740
+ verifyDigest: () => verifyDigest,
7741
+ verifyMechanismResult: () => verifyMechanismResult,
7742
+ versionLockIssueSeverity: () => versionLockIssueSeverity,
7743
+ writeGraphCache: () => writeGraphCache
7744
+ });
7075
7745
  import matter from "gray-matter";
7076
- import yaml from "js-yaml";
7746
+ import yaml2 from "js-yaml";
7077
7747
  import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
7078
- import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
7079
- import { basename as basename5, dirname as dirname7, extname, isAbsolute as isAbsolute6, join as join11, resolve as resolve8 } from "path";
7748
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
7749
+ import { basename as basename5, dirname as dirname7, extname, isAbsolute as isAbsolute7, join as join12, resolve as resolve8 } from "path";
7750
+ function getConfigDiagnostics(schema) {
7751
+ return configDiagnosticsBySchema.get(schema);
7752
+ }
7753
+ function edgeRule(from, to, kind) {
7754
+ return { from, to, kind };
7755
+ }
7756
+ function matchesEdgeRule(rule, fromType, toType, kind) {
7757
+ return rule.from === fromType && rule.to === toType && rule.kind === kind;
7758
+ }
7759
+ function cloneEdgeRules(rules) {
7760
+ return rules.map((rule) => ({ ...rule }));
7761
+ }
7762
+ function isEmptyAllowedEdgesValue(value) {
7763
+ return value === null || Array.isArray(value) && value.length === 0;
7764
+ }
7765
+ function resolveAllowedEdges(value) {
7766
+ if (isEmptyAllowedEdgesValue(value)) {
7767
+ return cloneEdgeRules(DEFAULT_ALLOWED_EDGES);
7768
+ }
7769
+ return cloneEdgeRules(value);
7770
+ }
7080
7771
  function isTargetArtifactType(type) {
7081
7772
  return isPacketTargetType(type);
7082
7773
  }
@@ -7118,30 +7809,22 @@ function resolveArtifactTypeName(schema, token) {
7118
7809
  return void 0;
7119
7810
  }
7120
7811
  async function loadConfig(root) {
7121
- const configPath = join11(root, "artifact-graph.config.yaml");
7122
- let parsed = {};
7812
+ const configPath = join12(root, "artifact-graph.config.yaml");
7813
+ let raw;
7123
7814
  try {
7124
- const raw = await readFile4(configPath, "utf-8");
7125
- parsed = yaml.load(raw) ?? {};
7815
+ raw = await readFile5(configPath, "utf-8");
7126
7816
  } catch (error) {
7127
- if (error.code !== "ENOENT") {
7128
- throw error;
7817
+ if (error.code === "ENOENT") {
7818
+ throw new Error(`required configuration is missing: ${configPath}`);
7129
7819
  }
7820
+ throw error;
7130
7821
  }
7131
- const ub = parsed.context?.universal_baseline;
7132
- if (ub !== void 0 && typeof ub !== "boolean") {
7133
- throw new Error(
7134
- `Invalid context.universal_baseline: ${JSON.stringify(ub)}. Must be boolean (true or false).`
7135
- );
7136
- }
7137
- if (parsed.e2e !== void 0) {
7138
- if (typeof parsed.e2e !== "object" || parsed.e2e === null || Array.isArray(parsed.e2e)) {
7139
- throw new Error("Invalid e2e: must be an object.");
7140
- }
7141
- validateE2eConfig(parsed.e2e);
7822
+ const document = yaml2.load(raw) ?? {};
7823
+ const shapeDiagnosis = diagnoseConfigDocument(document);
7824
+ if (shapeDiagnosis.errors.length > 0) {
7825
+ throw new Error(shapeDiagnosis.errors[0].message);
7142
7826
  }
7143
- validateRelationSemanticsConfig(parsed.relationSemantics);
7144
- validateStatusViewsConfig(parsed.statusViews);
7827
+ const parsed = document;
7145
7828
  const mergedE2e = parsed.e2e === void 0 ? DEFAULT_SCHEMA.e2e : {
7146
7829
  ...DEFAULT_SCHEMA.e2e,
7147
7830
  ...parsed.e2e,
@@ -7156,13 +7839,14 @@ async function loadConfig(root) {
7156
7839
  types: mergeArtifactTypes(DEFAULT_SCHEMA.types, parsed.types),
7157
7840
  idPatterns: mergeRecord(DEFAULT_SCHEMA.idPatterns, parsed.idPatterns),
7158
7841
  relationFields: mergeRecord(DEFAULT_SCHEMA.relationFields, parsed.relationFields),
7159
- allowedEdges: parsed.allowedEdges ?? DEFAULT_SCHEMA.allowedEdges,
7842
+ allowedEdges: resolveAllowedEdges(parsed.allowedEdges),
7160
7843
  forbiddenEdges: parsed.forbiddenEdges ?? DEFAULT_SCHEMA.forbiddenEdges,
7161
7844
  statuses: parsed.statuses ?? DEFAULT_SCHEMA.statuses,
7162
7845
  idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
7163
7846
  e2e: mergedE2e
7164
7847
  };
7165
7848
  validateJsonArtifactTypes(merged.types);
7849
+ configDiagnosticsBySchema.set(merged, shapeDiagnosis);
7166
7850
  return merged;
7167
7851
  }
7168
7852
  function validateJsonArtifactTypes(types) {
@@ -7187,131 +7871,6 @@ function validateJsonArtifactTypes(types) {
7187
7871
  }
7188
7872
  }
7189
7873
  }
7190
- function validateRelationSemanticsConfig(value) {
7191
- if (value === void 0) return;
7192
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
7193
- throw new Error("Invalid relationSemantics: must be an object keyed by relation kind.");
7194
- }
7195
- for (const [kind, spec] of Object.entries(value)) {
7196
- if (!kind.trim() || typeof spec !== "object" || spec === null || Array.isArray(spec)) {
7197
- throw new Error(`Invalid relationSemantics.${kind}: must be an object.`);
7198
- }
7199
- if (typeof spec.label !== "string" || !spec.label.trim()) {
7200
- throw new Error(`Invalid relationSemantics.${kind}.label: must be a non-empty string.`);
7201
- }
7202
- if (!Array.isArray(spec.targetTypes) || spec.targetTypes.some((item) => typeof item !== "string" || !item.trim())) {
7203
- throw new Error(`Invalid relationSemantics.${kind}.targetTypes: must be an array of non-empty strings.`);
7204
- }
7205
- if (!Array.isArray(spec.fields) || spec.fields.length === 0 || spec.fields.some((item) => typeof item !== "string" || !item.trim())) {
7206
- throw new Error(`Invalid relationSemantics.${kind}.fields: must be a non-empty array of strings.`);
7207
- }
7208
- if (spec.partial !== void 0 && (typeof spec.partial !== "object" || spec.partial === null || typeof spec.partial.sectionField !== "string" || !spec.partial.sectionField.trim())) {
7209
- throw new Error(`Invalid relationSemantics.${kind}.partial.sectionField: must be a non-empty string.`);
7210
- }
7211
- }
7212
- }
7213
- function validateStatusViewsConfig(value) {
7214
- if (value === void 0) return;
7215
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
7216
- throw new Error("Invalid statusViews: must be an object keyed by status.");
7217
- }
7218
- for (const [status, bucket] of Object.entries(value)) {
7219
- if (!status.trim() || !["current", "planned", "history"].includes(bucket)) {
7220
- throw new Error(`Invalid statusViews.${status}: expected current, planned, or history.`);
7221
- }
7222
- }
7223
- }
7224
- function validateE2eConfig(e2e) {
7225
- for (const field of ["report_uncovered_scenarios", "report_uncovered_features"]) {
7226
- if (e2e[field] !== void 0 && typeof e2e[field] !== "boolean") {
7227
- throw new Error(`Invalid e2e.${field}: must be boolean.`);
7228
- }
7229
- }
7230
- if (e2e.executable_ref_warning !== void 0) {
7231
- if (typeof e2e.executable_ref_warning !== "number" || e2e.executable_ref_warning < 0 || e2e.executable_ref_warning > 1) {
7232
- throw new Error(`Invalid e2e.executable_ref_warning: ${JSON.stringify(e2e.executable_ref_warning)}. Must be a number between 0 and 1.`);
7233
- }
7234
- }
7235
- if (e2e.executable_ref_error !== void 0) {
7236
- if (typeof e2e.executable_ref_error !== "number" || e2e.executable_ref_error < 0 || e2e.executable_ref_error > 1) {
7237
- throw new Error(`Invalid e2e.executable_ref_error: ${JSON.stringify(e2e.executable_ref_error)}. Must be a number between 0 and 1.`);
7238
- }
7239
- }
7240
- const validateWaivers = (waivers, field) => {
7241
- if (waivers === void 0) return;
7242
- if (!Array.isArray(waivers)) {
7243
- throw new Error(`Invalid ${field}: must be an array of {id, reason} objects.`);
7244
- }
7245
- for (const w of waivers) {
7246
- if (typeof w !== "object" || w === null || !("id" in w) || !("reason" in w)) {
7247
- throw new Error(`Invalid ${field} entry: ${JSON.stringify(w)}. Must be {id, reason} object.`);
7248
- }
7249
- if (typeof w.id !== "string" || !w.id.trim()) {
7250
- throw new Error(`Invalid ${field} entry: id must be a non-empty string. Got: ${JSON.stringify(w.id)}`);
7251
- }
7252
- if (typeof w.reason !== "string" || !w.reason.trim()) {
7253
- throw new Error(`Invalid ${field} entry: reason must be a non-empty string. Got: ${JSON.stringify(w.reason)}`);
7254
- }
7255
- }
7256
- };
7257
- validateWaivers(e2e.scenario_waivers, "e2e.scenario_waivers");
7258
- validateWaivers(e2e.feature_waivers, "e2e.feature_waivers");
7259
- if (e2e.runners !== void 0) {
7260
- if (!Array.isArray(e2e.runners)) {
7261
- throw new Error(`Invalid e2e.runners: must be an array.`);
7262
- }
7263
- for (const runner of e2e.runners) {
7264
- if (typeof runner !== "object" || runner === null) {
7265
- throw new Error(`Invalid e2e.runners entry: must be an object.`);
7266
- }
7267
- if (typeof runner.name !== "string" || !runner.name.trim()) {
7268
- throw new Error(`Invalid e2e.runners entry: name must be a non-empty string.`);
7269
- }
7270
- if (typeof runner.root !== "string" || !runner.root.trim()) {
7271
- throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
7272
- }
7273
- if (isAbsolute6(runner.root)) {
7274
- throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
7275
- }
7276
- if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
7277
- throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not contain ".." segments.`);
7278
- }
7279
- if (!Array.isArray(runner.include) || runner.include.length === 0) {
7280
- throw new Error(`Invalid e2e.runners[${runner.name}].include: must be a non-empty array of glob patterns.`);
7281
- }
7282
- for (const pattern of runner.include) {
7283
- if (typeof pattern !== "string" || !pattern.trim()) {
7284
- throw new Error(`Invalid e2e.runners[${runner.name}].include: pattern must be a non-empty string.`);
7285
- }
7286
- }
7287
- if (runner.exclude !== void 0) {
7288
- if (!Array.isArray(runner.exclude)) {
7289
- throw new Error(`Invalid e2e.runners[${runner.name}].exclude: must be an array.`);
7290
- }
7291
- for (const pattern of runner.exclude) {
7292
- if (typeof pattern !== "string" || !pattern.trim()) {
7293
- throw new Error(`Invalid e2e.runners[${runner.name}].exclude: pattern must be a non-empty string.`);
7294
- }
7295
- }
7296
- }
7297
- if (runner.testIgnore !== void 0) {
7298
- if (!Array.isArray(runner.testIgnore)) {
7299
- throw new Error(`Invalid e2e.runners[${runner.name}].testIgnore: must be an array.`);
7300
- }
7301
- for (const pattern of runner.testIgnore) {
7302
- if (typeof pattern !== "string" || !pattern.trim()) {
7303
- throw new Error(`Invalid e2e.runners[${runner.name}].testIgnore: pattern must be a non-empty string.`);
7304
- }
7305
- }
7306
- }
7307
- if (runner.kind !== void 0) {
7308
- if (!["unit", "integration", "e2e"].includes(runner.kind)) {
7309
- throw new Error(`Invalid e2e.runners[${runner.name}].kind: "${runner.kind}". Must be unit, integration, or e2e.`);
7310
- }
7311
- }
7312
- }
7313
- }
7314
- }
7315
7874
  function buildGraph(nodes, edges, diagnostics = [], root) {
7316
7875
  const graphNodes = nodes.map((node) => ({ ...node, uid: toUid(node.type, node.code) }));
7317
7876
  graphNodes.sort(compareNode);
@@ -7359,7 +7918,7 @@ async function scanArtifacts(root, schema, options = {}) {
7359
7918
  continue;
7360
7919
  }
7361
7920
  scannedFiles.set(file, type);
7362
- const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join11(root, file), "utf-8");
7921
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile5(join12(root, file), "utf-8");
7363
7922
  const parsed = parseFile(type, file, raw, config);
7364
7923
  const semantic = isJsonOriginalType(type, config) ? { edges: [], diagnostics: [] } : parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7365
7924
  nodes.push(...parsed.nodes);
@@ -7367,7 +7926,7 @@ async function scanArtifacts(root, schema, options = {}) {
7367
7926
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
7368
7927
  }
7369
7928
  }
7370
- const absoluteRoot = isAbsolute6(root) ? root : resolve8(root);
7929
+ const absoluteRoot = isAbsolute7(root) ? root : resolve8(root);
7371
7930
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
7372
7931
  return resolveMatrixEdges(graph);
7373
7932
  }
@@ -7514,8 +8073,16 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
7514
8073
  { edge: edge2 }
7515
8074
  ));
7516
8075
  }
7517
- if (schema.forbiddenEdges.some((rule) => rule.from === fromType && rule.to === toType && rule.kind === edge2.kind)) {
8076
+ if (schema.forbiddenEdges.some((rule) => matchesEdgeRule(rule, fromType, toType, edge2.kind))) {
7518
8077
  issues.push(issue("FORBIDDEN_EDGE", `Forbidden ${fromType} -> ${toType} ${edge2.kind} relation`, edge2.sourcePath, edge2.sourceLine, { edge: edge2 }));
8078
+ } else if (!schema.allowedEdges.some((rule) => matchesEdgeRule(rule, fromType, toType, edge2.kind))) {
8079
+ issues.push(issue(
8080
+ "DISALLOWED_EDGE",
8081
+ `Disallowed ${fromType} -> ${toType} ${edge2.kind} relation`,
8082
+ edge2.sourcePath,
8083
+ edge2.sourceLine,
8084
+ { edge: edge2 }
8085
+ ));
7519
8086
  }
7520
8087
  }
7521
8088
  issues.push(...validateE2eTests(graph));
@@ -7706,7 +8273,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
7706
8273
  const indexPath = "artifacts/prd/feature-index.md";
7707
8274
  let raw = "";
7708
8275
  try {
7709
- raw = await readFile4(join11(root, indexPath), "utf-8");
8276
+ raw = await readFile5(join12(root, indexPath), "utf-8");
7710
8277
  } catch (error) {
7711
8278
  if (error.code === "ENOENT") {
7712
8279
  return [];
@@ -7954,12 +8521,12 @@ function nextId(graph, schema, type, rangeName) {
7954
8521
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
7955
8522
  }
7956
8523
  async function writeGraphCache(root, graph) {
7957
- const cacheDir = join11(root, ".artifact-graph");
8524
+ const cacheDir = join12(root, ".artifact-graph");
7958
8525
  await mkdir5(cacheDir, { recursive: true });
7959
- await writeFile3(join11(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
8526
+ await writeFile3(join12(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
7960
8527
  `);
7961
8528
  const { default: Database } = await import("better-sqlite3");
7962
- const db = new Database(join11(cacheDir, "graph.sqlite"));
8529
+ const db = new Database(join12(cacheDir, "graph.sqlite"));
7963
8530
  try {
7964
8531
  db.exec(`
7965
8532
  DROP TABLE IF EXISTS nodes;
@@ -10041,7 +10608,7 @@ async function validateExecutableTraceability(root, config) {
10041
10608
  const tcKeyToFields = /* @__PURE__ */ new Map();
10042
10609
  const mdBatches = /* @__PURE__ */ new Set();
10043
10610
  for (const relPath of e2eFiles) {
10044
- const raw = await readFile4(join11(root, relPath), "utf-8");
10611
+ const raw = await readFile5(join12(root, relPath), "utf-8");
10045
10612
  const parsed = matter(raw);
10046
10613
  const data = parsed.data;
10047
10614
  const batch = String(data.test_batch ?? basename5(relPath, extname(relPath))).trim();
@@ -10083,10 +10650,10 @@ async function validateExecutableTraceability(root, config) {
10083
10650
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
10084
10651
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
10085
10652
  for (const specFile of specFiles) {
10086
- const fullSpecPath = join11(root, specFile);
10653
+ const fullSpecPath = join12(root, specFile);
10087
10654
  let content;
10088
10655
  try {
10089
- content = await readFile4(fullSpecPath, "utf-8");
10656
+ content = await readFile5(fullSpecPath, "utf-8");
10090
10657
  } catch {
10091
10658
  continue;
10092
10659
  }
@@ -10165,7 +10732,7 @@ async function validateExecutableTraceability(root, config) {
10165
10732
  if (entry.testId) {
10166
10733
  let content;
10167
10734
  try {
10168
- content = await readFile4(join11(root, normalizedRefFile), "utf-8");
10735
+ content = await readFile5(join12(root, normalizedRefFile), "utf-8");
10169
10736
  } catch {
10170
10737
  continue;
10171
10738
  }
@@ -10400,7 +10967,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
10400
10967
  let hasActiveE2eRef = false;
10401
10968
  for (const entry of parseExecutableRefLines(execRef)) {
10402
10969
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
10403
- if (!normalized || !existsSync3(join11(root, normalized))) continue;
10970
+ if (!normalized || !existsSync3(join12(root, normalized))) continue;
10404
10971
  const accepting = await getAcceptingRunners(root, normalized, runners);
10405
10972
  if (accepting.some((runner) => runner.kind === "e2e")) {
10406
10973
  hasActiveE2eRef = true;
@@ -10459,7 +11026,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
10459
11026
  const acCoverageRateByFeature = {};
10460
11027
  const featureAcMap = /* @__PURE__ */ new Map();
10461
11028
  for (const node of featureNodes) {
10462
- const acs = parseAcceptanceCriteria(await readFile4(join11(root, node.path), "utf-8"));
11029
+ const acs = parseAcceptanceCriteria(await readFile5(join12(root, node.path), "utf-8"));
10463
11030
  featureAcMap.set(node.code, new Set(acs));
10464
11031
  }
10465
11032
  const coveredAcByFeature = /* @__PURE__ */ new Map();
@@ -10507,8 +11074,8 @@ async function generateE2eRegistry(root, opts) {
10507
11074
  const batchIds = /* @__PURE__ */ new Set();
10508
11075
  let totalTestCases = 0;
10509
11076
  for (const file of files) {
10510
- const filePath = join11(root, file);
10511
- const raw = await readFile4(filePath, "utf-8");
11077
+ const filePath = join12(root, file);
11078
+ const raw = await readFile5(filePath, "utf-8");
10512
11079
  const parsed = matter(raw);
10513
11080
  const data = parsed.data;
10514
11081
  const batch = String(data.test_batch ?? basename5(file, extname(file))).trim();
@@ -10633,10 +11200,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
10633
11200
  if (!normalizedPath) {
10634
11201
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
10635
11202
  }
10636
- const fullPath = join11(root, normalizedPath);
11203
+ const fullPath = join12(root, normalizedPath);
10637
11204
  let content;
10638
11205
  try {
10639
- content = await readFile4(fullPath, "utf-8");
11206
+ content = await readFile5(fullPath, "utf-8");
10640
11207
  } catch {
10641
11208
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
10642
11209
  }
@@ -10670,7 +11237,7 @@ function detectTestLevel(specFile, content) {
10670
11237
  }
10671
11238
  function resolveExecutableRefFile(refFile, allFiles) {
10672
11239
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
10673
- if (!normalized || isAbsolute6(refFile) || normalized.split("/").includes("..")) {
11240
+ if (!normalized || isAbsolute7(refFile) || normalized.split("/").includes("..")) {
10674
11241
  return void 0;
10675
11242
  }
10676
11243
  if (allFiles.includes(normalized)) {
@@ -11252,7 +11819,7 @@ function resolveArtifactContext(graph, opts) {
11252
11819
  }
11253
11820
  if (root) {
11254
11821
  for (const ap of ALWAYS_PRESENT_ITEMS) {
11255
- const fullPath = join11(root, ap.path);
11822
+ const fullPath = join12(root, ap.path);
11256
11823
  let stat2;
11257
11824
  try {
11258
11825
  stat2 = statSync(fullPath);
@@ -11494,13 +12061,15 @@ function formatContextMarkdown(manifest) {
11494
12061
  }
11495
12062
  return lines.join("\n");
11496
12063
  }
11497
- var TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, SPECIALIZED_PARSER_TYPES, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
12064
+ var configDiagnosticsBySchema, DEFAULT_ALLOWED_EDGES, TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, SPECIALIZED_PARSER_TYPES, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
11498
12065
  var init_index = __esm({
11499
12066
  "src/index.ts"() {
11500
12067
  init_packet_constants();
11501
12068
  init_packet_validator();
11502
12069
  init_glob_matcher();
11503
12070
  init_file_walker();
12071
+ init_doctor();
12072
+ init_doctor();
11504
12073
  init_packet_constants();
11505
12074
  init_target_selector();
11506
12075
  init_impact();
@@ -11521,6 +12090,44 @@ var init_index = __esm({
11521
12090
  init_restructure();
11522
12091
  init_restructure_file_set();
11523
12092
  init_restructure_software();
12093
+ configDiagnosticsBySchema = /* @__PURE__ */ new WeakMap();
12094
+ DEFAULT_ALLOWED_EDGES = [
12095
+ edgeRule("feature", "scenario", "covers"),
12096
+ edgeRule("feature", "decision", "references"),
12097
+ edgeRule("feature", "feature", "depends_on"),
12098
+ edgeRule("feature", "design", "references"),
12099
+ edgeRule("scenario", "feature", "references"),
12100
+ edgeRule("scenario", "decision", "references"),
12101
+ edgeRule("scenario", "entity", "references"),
12102
+ edgeRule("entity", "decision", "references"),
12103
+ edgeRule("decision", "feature", "references"),
12104
+ edgeRule("decision", "scenario", "references"),
12105
+ edgeRule("design", "feature", "references"),
12106
+ edgeRule("design", "scenario", "references"),
12107
+ edgeRule("design", "decision", "references"),
12108
+ edgeRule("design", "entity", "references"),
12109
+ edgeRule("test", "feature", "verifies"),
12110
+ edgeRule("test", "scenario", "verifies"),
12111
+ edgeRule("test", "decision", "verifies"),
12112
+ edgeRule("test", "entity", "verifies"),
12113
+ edgeRule("implementation", "feature", "implements"),
12114
+ edgeRule("implementation", "scenario", "implements"),
12115
+ edgeRule("implementation", "decision", "implements"),
12116
+ edgeRule("implementation", "entity", "implements"),
12117
+ edgeRule("e2e_test", "scenario", "verifies"),
12118
+ edgeRule("e2e_test", "feature", "verifies"),
12119
+ edgeRule("e2e_test", "decision", "references"),
12120
+ edgeRule("e2e_test", "entity", "references"),
12121
+ edgeRule("rule-golden-cases", "design", "references"),
12122
+ edgeRule("traceability-matrix-v2", "traceability-matrix-v2", "references"),
12123
+ edgeRule("traceability-matrix-v2", "traceability-matrix-v2", "covers"),
12124
+ edgeRule("traceability-matrix-v2", "resolve", "references"),
12125
+ edgeRule("traceability-matrix-v2", "resolve", "covers"),
12126
+ ...["feature", "scenario", "decision", "design", "entity", "test", "e2e_test"].flatMap((to) => [
12127
+ edgeRule("traceability-matrix-v2", to, "references"),
12128
+ edgeRule("traceability-matrix-v2", to, "covers")
12129
+ ])
12130
+ ];
11524
12131
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
11525
12132
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
11526
12133
  DEFAULT_SCHEMA = {
@@ -11558,7 +12165,7 @@ var init_index = __esm({
11558
12165
  e2e_test: ["test_batch", "scope", "ac_coverage", "related_scenarios", "related_decisions", "related_entities", "\u8986\u76D6\u573A\u666F", "\u8986\u76D6\u529F\u80FD"],
11559
12166
  e2e_registry: ["batches"]
11560
12167
  },
11561
- allowedEdges: [],
12168
+ allowedEdges: DEFAULT_ALLOWED_EDGES,
11562
12169
  forbiddenEdges: [{ from: "scenario", to: "entity", kind: "references" }],
11563
12170
  statuses: ["planned", "active", "done", "deprecated"],
11564
12171
  idRanges: {},
@@ -11691,6 +12298,8 @@ export {
11691
12298
  createModeForUmask,
11692
12299
  createRestructureRootBinding,
11693
12300
  createRestructureValidationCallback,
12301
+ diagnoseConfigDocument,
12302
+ diagnoseProjectConfig,
11694
12303
  digestRestructureValue,
11695
12304
  dirname7 as dirname,
11696
12305
  discoverAndAuditPackets,
@@ -11703,6 +12312,7 @@ export {
11703
12312
  gateRestructureOperationPlan,
11704
12313
  generateE2eRegistry,
11705
12314
  getArtifactTypeMetadata,
12315
+ getConfigDiagnostics,
11706
12316
  getExternalEntryInfo,
11707
12317
  getTargetArtifactTypes,
11708
12318
  inspectRestructure,